@coderline/alphatab 1.2.2 → 1.2.3

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,7 +1,7 @@
1
1
  /**
2
- * alphaTab v1.2.2 (, build 6)
2
+ * alphaTab v1.2.3 (, build 7)
3
3
  *
4
- * Copyright © 2021, Daniel Kuschny and Contributors, All rights reserved.
4
+ * Copyright © 2022, Daniel Kuschny and Contributors, All rights reserved.
5
5
  *
6
6
  * This Source Code Form is subject to the terms of the Mozilla Public
7
7
  * License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -14,4 +14,4 @@
14
14
  * Copyright (C) 2012 Steve Folta (https://github.com/stevefolta/SFZero)
15
15
  */
16
16
 
17
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).alphaTab={})}(this,(function(e){"use strict";var t,i,s,a,r,n,o,h,l,c,d,u,p,g,f,m,y,b,S,w,_,B,T,k,v,N,x,P,E,C,F,L,M,I,D,A,R,O,G,V,H,W,U,z,X,Y,q,J,Q,j,K,$,Z,ee,te,ie,se,ae,re,ne,oe,he,le;(t=e.AlphaTabErrorType||(e.AlphaTabErrorType={}))[t.General=0]="General",t[t.Format=1]="Format",t[t.AlphaTex=2]="AlphaTex";class ce extends Error{constructor(e,t,i){super(t),this.type=e,this.inner=null!=i?i:null,Object.setPrototypeOf(this,ce.prototype)}}class de extends ce{constructor(t){super(e.AlphaTabErrorType.Format,t),Object.setPrototypeOf(this,de.prototype)}}class ue{static getValue(e){return ue._values||(ue._values=new Map),e=e.toLowerCase().split(" ").join(""),ue._values.has(e)?ue._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}}ue._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.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"}(i||(i={})),(s=e.TabRhythmMode||(e.TabRhythmMode={}))[s.Hidden=0]="Hidden",s[s.ShowWithBeams=1]="ShowWithBeams",s[s.ShowWithBars=2]="ShowWithBars",(a=e.FingeringMode||(e.FingeringMode={}))[a.ScoreDefault=0]="ScoreDefault",a[a.ScoreForcePiano=1]="ScoreForcePiano",a[a.SingleNoteEffectBand=2]="SingleNoteEffectBand",a[a.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano",(r=e.NotationMode||(e.NotationMode={}))[r.GuitarPro=0]="GuitarPro",r[r.SongBook=1]="SongBook",function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap"}(n||(n={}));class pe{constructor(){this.notationMode=e.NotationMode.GuitarPro,this.fingeringMode=e.FingeringMode.ScoreDefault,this.elements=new Map,this.rhythmMode=e.TabRhythmMode.Hidden,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!pe.defaultElements.has(e)||pe.defaultElements.get(e)}}pe.defaultElements=new Map([[n.ZerosOnDiveWhammys,!1]]);class ge{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class fe{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let i=0;i<t.tracks.length;i++){if(i<e.notation.displayTranspositionPitches.length)for(let s of t.tracks[i].staves)s.displayTranspositionPitch=-e.notation.displayTranspositionPitches[i];if(i<e.notation.transpositionPitches.length)for(let s of t.tracks[i].staves)s.transpositionPitch=-e.notation.transpositionPitches[i]}}static fingerToString(t,s,a,r){if(t.notation.fingeringMode===e.FingeringMode.ScoreForcePiano||t.notation.fingeringMode===e.FingeringMode.SingleNoteEffectBandForcePiano||ue.isPiano(s.voice.bar.staff.track.playbackInfo.program))switch(a){case i.Unknown:case i.NoOrDead:return null;case i.Thumb:return"1";case i.IndexFinger:return"2";case i.MiddleFinger:return"3";case i.AnnularFinger:return"4";case i.LittleFinger:return"5";default:return null}if(r)switch(a){case i.Unknown:case i.NoOrDead:return"0";case i.Thumb:return"T";case i.IndexFinger:return"1";case i.MiddleFinger:return"2";case i.AnnularFinger:return"3";case i.LittleFinger:return"4";default:return null}switch(a){case i.Unknown:case i.NoOrDead:return null;case i.Thumb:return"p";case i.IndexFinger:return"i";case i.MiddleFinger:return"m";case i.AnnularFinger:return"a";case i.LittleFinger:return"c";default:return null}}static isTuning(e){return!!fe.parseTuning(e)}static parseTuning(e){let t="",i="";for(let s=0;s<e.length;s++){let a=e.charCodeAt(s);if(a>=48&&a<=57){if(!t)return null;i+=String.fromCharCode(a)}else{if(!(a>=65&&a<=90||a>=97&&a<=122||35===a))return null;t+=String.fromCharCode(a)}}if(!i||!t)return null;let s=new ge;return s.octave=parseInt(i)+1,s.note=t.toLowerCase(),s.noteValue=fe.getToneForText(s.note),s}static getTuningForText(e){let t=fe.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){let t=0;switch(e.toLowerCase()){case"c":t=0;break;case"c#":case"db":t=1;break;case"d":t=2;break;case"d#":case"eb":t=3;break;case"e":t=4;break;case"f":t=5;break;case"f#":case"gb":t=6;break;case"g":t=7;break;case"g#":case"ab":t=8;break;case"a":t=9;break;case"a#":case"bb":t=10;break;case"b":t=11;break;default:return 0}return t}static newGuid(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let i="";do{i=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+i,e>>=4}while(e>0);for(;i.length<t;)i="0"+i;return i}}class me{constructor(e,t,i,s=255){this.raw=0,this.raw=0,this.raw=(255&s)<<24|(255&e)<<16|(255&t)<<8|255&i,this.updateRgba()}updateRgba(){255===this.a?this.rgba="#"+fe.toHexString(this.r,2)+fe.toHexString(this.g,2)+fe.toHexString(this.b,2):this.rgba=`rgba(${this.r},${this.g},${this.b},${this.a/255})`}get a(){return this.raw>>24&255}get r(){return this.raw>>16&255}get g(){return this.raw>>8&255}get b(){return 255&this.raw}static random(e=100){return new me(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new me(0,0,0,0);return t.raw=e,t.updateRgba(),t}case"string":{const t=e;if(t.startsWith("#")){if(4===t.length)return new me(17*parseInt(t.substring(1,1),16),17*parseInt(t.substring(2,1),16),17*parseInt(t.substring(3,1),16));if(5===t.length)return new me(17*parseInt(t.substring(1,1),16),17*parseInt(t.substring(2,1),16),17*parseInt(t.substring(3,1),16),17*parseInt(t.substring(4,1),16));if(7===t.length)return new me(parseInt(t.substring(1,2),16),parseInt(t.substring(3,2),16),parseInt(t.substring(5,2),16));if(9===t.length)return new me(parseInt(t.substring(1,2),16),parseInt(t.substring(3,2),16),parseInt(t.substring(5,2),16),parseInt(t.substring(7,2),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),i=t.lastIndexOf(")");if(-1===e||-1===i)throw new de("No values specified for rgb/rgba function");const s=t.substring(e+1,i-e-1).split(",");if(3===s.length)return new me(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]));if(4===s.length)return new me(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]),255*parseFloat(s[3]))}return null}}throw new de("Unsupported format for color")}static toJson(e){return e.raw}}me.BlackRgb="#000000";class ye{static parseEnum(t,i){switch(typeof t){case"string":const e=parseInt(t);return isNaN(e)?i[Object.keys(i).find((e=>e.toLowerCase()===t.toLowerCase()))]:e;case"number":return t;case"undefined":case"object":return null}throw new ce(e.AlphaTabErrorType.Format,`Could not parse enum value '${t}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const i in e)t(e[i],i)}}class be{constructor(e,t,i){this.text=e,this.startPos=t,this.endPos=i}}class Se{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],this._currentTokenIndex=-1,this._input="",this._currentToken=null,this._input=e,this._tokens=this.splitToTokens(e)}splitToTokens(e){const t=[];let i=0;for(;i<e.length;){let s=i;for(;s<e.length&&" "!==e.charAt(s);)s++;s>i&&t.push(new be(e.substring(i,s),i,s)),i=s+1}return t}parse(){var e;if(this.reset(),1===this._tokens.length)switch(null===(e=this._currentToken)||void 0===e?void 0:e.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.fontStyleVariantWeight(),this.fontSizeLineHeight(),this.fontFamily()}fontFamily(){if(!this._currentToken)throw new Error("Missing font list");const e=this._input.substr(this._currentToken.startPos).trim();let t=0;for(;t<e.length;){let i=e.charAt(t);if(" "===i||","==i)t++;else if('"'===i||"'"===i){const s=this.findEndOfQuote(e,t+1,i);this.families.push(e.substring(t+1,s).split("\\"+i).join(i)),t=s+1}else{const i=this.findEndOfQuote(e,t+1,",");this.families.push(e.substring(t,i).trim()),t=i+1}}}findEndOfQuote(e,t,i){let s=!1;for(;t<e.length;){const a=e.charAt(t);if(!s&&a===i)return t;s=!s&&"\\"===a,t++}return e.length}fontSizeLineHeight(){var e;if(!this._currentToken)throw new Error("Missing font size");const t=this._currentToken.text.split("/");if(t.length>=3)throw new Error(`Invalid font size '${this._currentToken}' specified`);if(this.nextToken(),t.length>=2)if("/"===t[1]){if(!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.size=t[0],this.lineHeight=t[1];else{if(!(t.length>=1))throw new Error("Missing font size");if(this.size=t[0],0===(null===(e=this._currentToken)||void 0===e?void 0:e.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(){var e,t,i,s,a;let r=!1,n=!1,o=!1,h=3,l=[];for(;;){switch(null===(e=this._currentToken)||void 0===e?void 0:e.text){case"normal":case"inherit":l.push(null===(t=this._currentToken)||void 0===t?void 0:t.text),h--,this.nextToken();break;case"italic":case"oblique":this.style=null===(i=this._currentToken)||void 0===i?void 0:i.text,r=!0,h--,this.nextToken();break;case"small-caps":this.variant=null===(s=this._currentToken)||void 0===s?void 0:s.text,n=!0,h--,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=null===(a=this._currentToken)||void 0===a?void 0:a.text,o=!0,h--,this.nextToken();break;default:return}if(0===h)break}for(;l.length>0;){const e=l.pop();o?n?r||(this.style=e):this.variant=e:this.weight=e}}reset(){this._currentTokenIndex=-1,this.nextToken()}}!function(e){e[e.Plain=0]="Plain",e[e.Bold=1]="Bold",e[e.Italic=2]="Italic"}(o||(o={}));class we{constructor(e,t,i=o.Plain){this._cssScale=0,this.family=e,this.size=t,this.style=i,this._css=this.toCssString(1)}get isBold(){return 0!=(this.style&o.Bold)}get isItalic(){return 0!=(this.style&o.Italic)}toCssString(e){if(!(this._css&&Math.abs(e-this._cssScale)<.01)){let t="";this.isBold&&(t+="bold "),this.isItalic&&(t+="italic "),t+=this.size*e,t+="px ",t+="'",t+=this.family,t+="'",this._css=t,this._cssScale=e}return this._css}static fromJson(e){switch(typeof e){case"undefined":return null;case"object":{const t=e;let i=t.get("family"),s=t.get("size"),a=ye.parseEnum(t.get("style"),o);return new we(i,s,a)}case"string":{const t=new Se(e);t.parse();let i=t.families[0];(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))&&(i=i.substr(1,i.length-2));let s=t.size.toLowerCase(),a=0;switch(s){case"xx-small":a=7;break;case"x-small":a=10;break;case"small":case"smaller":a=13;break;case"medium":a=16;break;case"large":case"larger":a=18;break;case"x-large":a=24;break;case"xx-large":a=32;break;default:try{a=s.endsWith("em")?16*parseFloat(s.substr(0,s.length-2)):s.endsWith("pt")?16*parseFloat(s.substr(0,s.length-2))/12:s.endsWith("px")?parseFloat(s.substr(0,s.length-2)):12}catch(e){a=12}}let r=o.Plain;switch("italic"===t.style&&(r|=o.Italic),t.weight.toLowerCase()){case"normal":case"lighter":break;default:r|=o.Bold}return new we(i,a,r)}default:return null}}static toJson(e){const t=new Map;return t.set("family",e.family),t.set("size",e.size),t.set("style",e.style),t}}class _e{constructor(){this.copyrightFont=new we(_e.sansFont,12,o.Bold),this.titleFont=new we(_e.serifFont,32,o.Plain),this.subTitleFont=new we(_e.serifFont,20,o.Plain),this.wordsFont=new we(_e.serifFont,15,o.Plain),this.effectFont=new we(_e.serifFont,12,o.Italic),this.fretboardNumberFont=new we(_e.sansFont,11,o.Plain),this.tablatureFont=new we(_e.sansFont,13,o.Plain),this.graceFont=new we(_e.sansFont,11,o.Plain),this.staffLineColor=new me(165,165,165,255),this.barSeparatorColor=new me(34,34,17,255),this.barNumberFont=new we(_e.sansFont,11,o.Plain),this.barNumberColor=new me(200,0,0,255),this.fingeringFont=new we(_e.serifFont,14,o.Plain),this.markerFont=new we(_e.serifFont,14,o.Bold),this.mainGlyphColor=new me(0,0,0,255),this.secondaryGlyphColor=new me(0,0,0,100),this.scoreInfoColor=new me(0,0,0,255)}}_e.sansFont="Arial",_e.serifFont="Georgia",(h=e.StaveProfile||(e.StaveProfile={}))[h.Default=0]="Default",h[h.ScoreTab=1]="ScoreTab",h[h.Score=2]="Score",h[h.Tab=3]="Tab",h[h.TabMixed=4]="TabMixed",(l=e.LayoutMode||(e.LayoutMode={}))[l.Page=0]="Page",l[l.Horizontal=1]="Horizontal";class Be{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.LayoutMode.Page,this.staveProfile=e.StaveProfile.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.resources=new _e,this.padding=null}}class Te{init(e,t){this.data=e,this.settings=t}}class ke extends ce{constructor(t="Unsupported format",i=null){super(e.AlphaTabErrorType.Format,t),this.inner=i,Object.setPrototypeOf(this,ke.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(c||(c={})),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 ve{constructor(){this.isLinear=!1,this.type=d.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,i,s){(s<1||s>5)&&(s=2);let a=new Float32Array([1,.5,1,1.5,2,3]),r=new ve;return r.type=d.Tempo,r.isLinear=e,r.ratioPosition=t,r.value=i*a[s],r}static buildInstrumentAutomation(e,t,i){let s=new ve;return s.type=d.Instrument,s.isLinear=e,s.ratioPosition=t,s.value=i,s}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(u||(u={})),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"}(p||(p={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(g||(g={}));class Ne{constructor(){this.id=Ne._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=u.G2,this.clefOttava=p.Regular,this.voices=[],this.simileMark=g.None,this.isMultiVoice=!1}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e){this.isMultiVoice=!1;for(let t=0,i=this.voices.length;t<i;t++){let i=this.voices[t];i.finish(e),t>0&&!i.isEmpty&&(this.isMultiVoice=!0)}}calculateDuration(){let e=0;for(let t of this.voices){let i=t.calculateDuration();i>e&&(e=i)}return e}}Ne._globalBarId=0;class xe{static ticksToMillis(e,t){return e*(6e4/(t*xe.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*xe.QuarterTime))|0}static toTicks(e){return xe.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),xe.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,i){return e*i/t|0}static removeTuplet(e,t,i){return e*t/i|0}static dynamicToVelocity(e){return xe.MinVelocity+e*xe.VelocityIncrement}}xe.QuarterTime=960,xe.MinVelocity=15,xe.VelocityIncrement=16;class Pe{constructor(e=0,t=0){this.offset=e,this.value=t}}Pe.MaxPosition=60,Pe.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"}(m||(m={})),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"}(y||(y={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(b||(b={})),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"}(S||(S={})),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"}(w||(w={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(_||(_={})),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"}(B||(B={})),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"}(T||(T={})),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"}(v||(v={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(N||(N={}));class Ee{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}(x=e.LogLevel||(e.LogLevel={}))[x.None=0]="None",x[x.Debug=1]="Debug",x[x.Info=2]="Info",x[x.Warning=3]="Warning",x[x.Error=4]="Error";class Ce{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...i){console.debug(Ce.format(e,t),...i)}warning(e,t,...i){console.warn(Ce.format(e,t),...i)}info(e,t,...i){console.info(Ce.format(e,t),...i)}error(e,t,...i){console.error(Ce.format(e,t),...i)}}Ce.logLevel=e.LogLevel.Info;class Fe{static shouldLog(t){return Fe.logLevel!==e.LogLevel.None&&t>=Fe.logLevel}static debug(t,i,...s){Fe.shouldLog(e.LogLevel.Debug)&&Fe.log.debug(t,i,...s)}static warning(t,i,...s){Fe.shouldLog(e.LogLevel.Warning)&&Fe.log.warning(t,i,...s)}static info(t,i,...s){Fe.shouldLog(e.LogLevel.Info)&&Fe.log.info(t,i,...s)}static error(t,i,...s){Fe.shouldLog(e.LogLevel.Error)&&Fe.log.error(t,i,...s)}}Fe.logLevel=e.LogLevel.Info,Fe.log=new Ce,function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(P||(P={})),function(e){e[e.None=-1]="None",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(E||(E={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(C||(C={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(F||(F={}));class Le{constructor(e="",t=0,i=0,s=E.None,a=E.None,r=E.None,n=E.None,o=F.Middle){this.elementType=e,this.outputMidiNumber=i,this.staffLine=t,this.noteHeadDefault=s,this.noteHeadHalf=a!==E.None?a:s,this.noteHeadWhole=r!==E.None?r:s,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case S.Whole:return this.noteHeadWhole;case S.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,i=e.beat.voice.bar.staff.track.percussionArticulations;return t<i.length?i[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 i=Me.gp6ElementAndVariationToArticulation[e];for(let s=0;s<i.length;s++){const a=Me.getArticulationByValue(i[s]);if((null==a?void 0:a.outputMidiNumber)===t.outputMidiNumber)return[e,s]}}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 Le("snare",3,38,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[37,new Le("snare",3,37,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[91,new Le("snare",3,38,E.NoteheadDiamondWhite,E.NoteheadDiamondWhite,E.NoteheadDiamondWhite)],[42,new Le("hiHat",-1,42,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[92,new Le("hiHat",-1,46,E.NoteheadCircleSlash,E.NoteheadCircleSlash,E.NoteheadCircleSlash)],[46,new Le("hiHat",-1,46,E.NoteheadCircleX,E.NoteheadCircleX,E.NoteheadCircleX)],[44,new Le("hiHat",9,44,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[35,new Le("kickDrum",8,35,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[36,new Le("kickDrum",7,36,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[50,new Le("tom",1,50,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[48,new Le("tom",2,48,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[47,new Le("tom",4,47,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[45,new Le("tom",5,45,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[43,new Le("tom",6,43,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[93,new Le("ride",0,51,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack,E.PictEdgeOfCymbal,F.Bottom)],[51,new Le("ride",0,51,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[53,new Le("ride",0,53,E.NoteheadDiamondWhite,E.NoteheadDiamondWhite,E.NoteheadDiamondWhite)],[94,new Le("ride",0,51,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack,E.ArticStaccatoAbove,F.Top)],[55,new Le("splash",-2,55,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[95,new Le("splash",-2,55,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack,E.ArticStaccatoAbove,F.Bottom)],[52,new Le("china",-3,52,E.NoteheadHeavyXHat,E.NoteheadHeavyXHat,E.NoteheadHeavyXHat)],[96,new Le("china",-3,52,E.NoteheadHeavyXHat,E.NoteheadHeavyXHat,E.NoteheadHeavyXHat)],[49,new Le("crash",-2,49,E.NoteheadHeavyX,E.NoteheadHeavyX,E.NoteheadHeavyX)],[97,new Le("crash",-2,49,E.NoteheadHeavyX,E.NoteheadHeavyX,E.NoteheadHeavyX,E.ArticStaccatoAbove,F.Bottom)],[57,new Le("crash",-1,57,E.NoteheadHeavyX,E.NoteheadHeavyX,E.NoteheadHeavyX)],[98,new Le("crash",-1,57,E.NoteheadHeavyX,E.NoteheadHeavyX,E.NoteheadHeavyX,E.ArticStaccatoAbove,F.Bottom)],[99,new Le("cowbell",1,56,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpHalf,E.NoteheadTriangleUpWhole)],[100,new Le("cowbell",1,56,E.NoteheadXBlack,E.NoteheadXHalf,E.NoteheadXWhole)],[56,new Le("cowbell",0,56,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpHalf,E.NoteheadTriangleUpWhole)],[101,new Le("cowbell",0,56,E.NoteheadXBlack,E.NoteheadXHalf,E.NoteheadXWhole)],[102,new Le("cowbell",-1,56,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpHalf,E.NoteheadTriangleUpWhole)],[103,new Le("cowbell",-1,56,E.NoteheadXBlack,E.NoteheadXHalf,E.NoteheadXWhole)],[77,new Le("woodblock",-9,77,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack)],[76,new Le("woodblock",-10,76,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack)],[60,new Le("bongo",-4,60,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[104,new Le("bongo",-5,60,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.NoteheadParenthesis,F.Middle)],[105,new Le("bongo",-6,60,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[61,new Le("bongo",-7,61,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[106,new Le("bongo",-8,61,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.NoteheadParenthesis,F.Middle)],[107,new Le("bongo",-16,61,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[66,new Le("timbale",10,66,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[65,new Le("timbale",9,65,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[68,new Le("agogo",12,68,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[67,new Le("agogo",11,67,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[64,new Le("conga",17,64,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[108,new Le("conga",16,64,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[109,new Le("conga",15,64,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.NoteheadParenthesis,F.Middle)],[63,new Le("conga",14,63,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[110,new Le("conga",13,63,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[62,new Le("conga",19,62,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.NoteheadParenthesis,F.Middle)],[72,new Le("whistle",-11,72,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[71,new Le("whistle",-17,71,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[73,new Le("guiro",38,73,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[74,new Le("guiro",37,74,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[86,new Le("surdo",36,86,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[87,new Le("surdo",35,87,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadParenthesis,F.Middle)],[54,new Le("tambourine",3,54,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack)],[111,new Le("tambourine",2,54,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack,E.StringsUpBow,F.Bottom)],[112,new Le("tambourine",1,54,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack,E.NoteheadTriangleUpBlack,E.StringsDownBow,F.Bottom)],[113,new Le("tambourine",-7,54,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[79,new Le("cuica",30,79,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[78,new Le("cuica",29,78,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[58,new Le("vibraslap",28,58,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[81,new Le("triangle",27,81,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[80,new Le("triangle",26,80,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadParenthesis,F.Middle)],[114,new Le("grancassa",25,43,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[115,new Le("piatti",18,49,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[116,new Le("piatti",24,49,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[69,new Le("cabasa",23,69,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[117,new Le("cabasa",22,69,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.StringsUpBow,F.Bottom)],[85,new Le("castanets",21,85,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[75,new Le("claves",20,75,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[70,new Le("maraca",-12,70,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[118,new Le("maraca",-13,70,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.StringsUpBow,F.Bottom)],[119,new Le("maraca",-14,70,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[120,new Le("maraca",-15,70,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.StringsUpBow,F.Bottom)],[82,new Le("shaker",-23,54,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[122,new Le("shaker",-24,54,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.StringsUpBow,F.Bottom)],[84,new Le("bellTree",-18,53,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[123,new Le("bellTree",-19,53,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole,E.StringsUpBow,F.Bottom)],[83,new Le("jingleBell",-20,53,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[124,new Le("unpitched",-21,62,E.NoteheadNull,E.NoteheadNull,E.NoteheadNull,E.GuitarGolpe,F.Top)],[125,new Le("unpitched",-22,62,E.NoteheadNull,E.NoteheadNull,E.NoteheadNull,E.GuitarGolpe,F.Bottom)],[39,new Le("handClap",3,39,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[40,new Le("snare",3,40,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[31,new Le("snare",3,40,E.NoteheadSlashedBlack2,E.NoteheadSlashedBlack2,E.NoteheadSlashedBlack2)],[41,new Le("tom",5,41,E.NoteheadBlack,E.NoteheadHalf,E.NoteheadWhole)],[59,new Le("ride",2,59,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack,E.PictEdgeOfCymbal,F.Bottom)],[126,new Le("ride",2,59,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[127,new Le("ride",2,59,E.NoteheadDiamondWhite,E.NoteheadDiamondWhite,E.NoteheadDiamondWhite)],[29,new Le("ride",2,59,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack,E.ArticStaccatoAbove,F.Top)],[30,new Le("crash",-3,49,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[33,new Le("snare",3,37,E.NoteheadXBlack,E.NoteheadXBlack,E.NoteheadXBlack)],[34,new Le("snare",3,38,E.NoteheadBlack,E.NoteheadBlack,E.NoteheadBlack)]]);class Ie{constructor(){this.id=Ie.GlobalNoteId++,this.index=0,this.accentuated=c.None,this.bendType=m.None,this.bendStyle=f.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=[],this.maxBendPoint=null,this.fret=-1,this.string=-1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.isSlurDestination=!1,this.slurOriginNoteId=-1,this.slurDestinationNoteId=-1,this.harmonicType=B.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=v.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=N.None,this.tieOriginNoteId=-1,this.tieDestinationNoteId=-1,this.isTieDestination=!1,this.leftHandFinger=i.Unknown,this.rightHandFinger=i.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=S.ThirtySecond,this.durationPercent=1,this.accidentalMode=T.Default,this.dynamics=w.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null}get hasBend(){return this.bendType!==m.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 hammerPullOrigin(){return-1===this.hammerPullOriginNoteId?null:this.beat.voice.bar.staff.track.score.getNoteById(this.hammerPullOriginNoteId)}get hammerPullDestination(){return-1===this.hammerPullDestinationNoteId?null:this.beat.voice.bar.staff.track.score.getNoteById(this.hammerPullDestinationNoteId)}get isSlurOrigin(){return!!this.slurDestination}get slurOrigin(){return-1===this.slurOriginNoteId?null:this.beat.voice.bar.staff.track.score.getNoteById(this.slurOriginNoteId)}get slurDestination(){return-1===this.slurDestinationNoteId?null:this.beat.voice.bar.staff.track.score.getNoteById(this.slurDestinationNoteId)}get isHarmonic(){return this.harmonicType!==B.None}get tieOrigin(){return-1===this.tieOriginNoteId?null:this.beat.voice.bar.staff.track.score.getNoteById(this.tieOriginNoteId)}get tieDestination(){return-1===this.tieDestinationNoteId?null:this.beat.voice.bar.staff.track.score.getNoteById(this.tieDestinationNoteId)}get isTieOrigin(){return-1!==this.tieDestinationNoteId}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+Ie.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){let e=this.realValueWithoutHarmonic;return this.isStringed&&(this.harmonicType===B.Natural?e=this.harmonicPitch+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:e+=this.harmonicPitch),e}get realValueWithoutHarmonic(){return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:this.isPiano?12*this.octave+this.tone-this.beat.voice.bar.staff.transpositionPitch:0}get harmonicPitch(){if(this.harmonicType===B.None||!this.isStringed)return 0;let e=this.harmonicValue;return fe.isAlmostEqualTo(e,2.4)?36:fe.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?this.bendPoints[0].value/2|0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2|0:this.isTieDestination&&this.tieOrigin.bendOrigin?this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.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:0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==B.Natural&&this.harmonicType!==B.None&&(e-=this.harmonicPitch),this.beat.ottava){case p._15ma:e-=24;break;case p._8va:e-=12;break;case p.Regular:break;case p._8vb:e+=12;break;case p._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case p._15ma:e-=24;break;case p._8va:e-=12;break;case p.Regular:break;case p._8vb:e+=12;break;case p._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){this.bendPoints.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===m.None&&(this.bendType=m.Custom)}finish(t){let i=new Ee((()=>Ie.nextNoteOnSameLine(this))),s=t&&t.notation.notationMode===e.NotationMode.SongBook;if(this.isTieDestination&&(this.chain(),s&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(i.value&&i.value.isLetRing?this.letRingDestination=i.value:this.letRingDestination=this,s&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(i.value&&i.value.isPalmMute?this.palmMuteDestination=i.value:this.palmMuteDestination=this),this.isHammerPullOrigin){let e=Ie.findHammerPullDestination(this);e?(this.hammerPullDestinationNoteId=e.id,e.hammerPullOriginNoteId=this.id):this.isHammerPullOrigin=!1}switch(this.slideOutType){case v.Shift:case v.Legato:this.slideTarget=i.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=v.None}let a=null;if(this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===v.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===P.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this)),this.bendPoints.length>0&&this.bendType===m.Custom){let e=this.isContinuedBend=this.isTieDestination&&this.tieOrigin.hasBend;if(4===this.bendPoints.length){let t=this.bendPoints[0],i=this.bendPoints[1],s=this.bendPoints[2],a=this.bendPoints[3];i.value===s.value?a.value>t.value?i.value>a.value?this.bendType=m.BendRelease:!e&&t.value>0?(this.bendType=m.PrebendBend,this.bendPoints.splice(2,1),this.bendPoints.splice(1,1)):(this.bendType=m.Bend,this.bendPoints.splice(2,1),this.bendPoints.splice(1,1)):a.value<t.value?e?(this.bendType=m.Release,this.bendPoints.splice(2,1),this.bendPoints.splice(1,1)):(this.bendType=m.PrebendRelease,this.bendPoints.splice(2,1),this.bendPoints.splice(1,1)):i.value>t.value?this.bendType=m.BendRelease:t.value>0&&!e?(this.bendType=m.Prebend,this.bendPoints.splice(2,1),this.bendPoints.splice(1,1)):(this.bendType=m.Hold,this.bendPoints.splice(2,1),this.bendPoints.splice(1,1)):Fe.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===this.bendPoints.length){let t=this.bendPoints[0],i=this.bendPoints[1];i.value>t.value?!e&&t.value>0?this.bendType=m.PrebendBend:this.bendType=m.Bend:i.value<t.value?this.bendType=e?m.Release:m.PrebendRelease:this.bendType=m.Hold}}else 0===this.bendPoints.length&&(this.bendType=m.None);this.initialBendValue>0&&(this.accidentalMode=T.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Ie.MaxOffsetForSameLineSearch;){let i=t.getNoteOnString(e.string);if(i)return i;t=t.nextBeat}return null}static findHammerPullDestination(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Ie.MaxOffsetForSameLineSearch;){let i=t.getNoteOnString(e.string);if(i)return i;for(let s=e.string;s>0;s--)if(i=t.getNoteOnString(s),i){if(i.isLeftHandTapped)return i;break}for(let s=e.string;s<=e.beat.voice.bar.staff.tuning.length;s++)if(i=t.getNoteOnString(s),i){if(i.isLeftHandTapped)return i;break}t=t.nextBeat}return null}static findTieOrigin(e){let t=e.beat.previousBeat;for(;t&&t.voice.bar.index>=e.beat.voice.bar.index-Ie.MaxOffsetForSameLineSearch;){if(e.isStringed){let i=t.getNoteOnString(e.string);if(i)return i}else if(-1===e.octave&&-1===e.tone){if(e.index<t.notes.length)return t.notes[e.index]}else{let i=t.getNoteWithRealValue(e.realValue);if(i)return i}t=t.previousBeat}return null}chain(){if(this.beat.voice.bar.staff.track.score.registerNote(this),!this.isTieDestination)return;let e;-1===this.tieOriginNoteId?(e=Ie.findTieOrigin(this),this.tieOriginNoteId=e?e.id:-1):e=this.tieOrigin,e?(e.tieDestinationNoteId=this.id,this.fret=e.fret,this.octave=e.octave,this.tone=e.tone,e.hasBend&&(this.bendOrigin=this.tieOrigin)):this.isTieDestination=!1}}Ie.GlobalNoteId=0,Ie.MaxOffsetForSameLineSearch=3;class De{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!==_.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of De.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}De.HalfTicks=1920,De.QuarterTicks=960,De.EighthTicks=480,De.SixteenthTicks=240,De.ThirtySecondTicks=120,De.SixtyFourthTicks=60,De.OneHundredTwentyEighthTicks=30,De.TwoHundredFiftySixthTicks=15,De.AllTicks=[De.HalfTicks,De.QuarterTicks,De.EighthTicks,De.SixteenthTicks,De.ThirtySecondTicks,De.SixtyFourthTicks,De.OneHundredTwentyEighthTicks,De.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"}(L||(L={}));class Ae{static clone(e){const t=new Pe;return t.offset=e.offset,t.value=e.value,t}}class Re{static clone(e){const t=new Ie;t.index=e.index,t.accentuated=e.accentuated,t.bendType=e.bendType,t.bendStyle=e.bendStyle,t.isContinuedBend=e.isContinuedBend,t.bendPoints=[];for(const i of e.bendPoints)t.addBendPoint(Ae.clone(i));return t.fret=e.fret,t.string=e.string,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.hammerPullOriginNoteId=e.hammerPullOriginNoteId,t.hammerPullDestinationNoteId=e.hammerPullDestinationNoteId,t.isSlurDestination=e.isSlurDestination,t.slurOriginNoteId=e.slurOriginNoteId,t.slurDestinationNoteId=e.slurDestinationNoteId,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.tieOriginNoteId=e.tieOriginNoteId,t.tieDestinationNoteId=e.tieDestinationNoteId,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.isFingering=e.isFingering,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t}}class Oe{static clone(e){const t=new ve;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Ge{static clone(e){const t=new He;t.index=e.index,t.notes=[];for(const i of e.notes)t.addNote(Re.clone(i));t.isEmpty=e.isEmpty,t.whammyStyle=e.whammyStyle,t.ottava=e.ottava,t.isLegatoOrigin=e.isLegatoOrigin,t.duration=e.duration,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.automations=[];for(const i of e.automations)t.automations.push(Oe.clone(i));t.dots=e.dots,t.fadeIn=e.fadeIn,t.lyrics=e.lyrics?e.lyrics.slice():null,t.hasRasgueado=e.hasRasgueado,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,t.whammyBarPoints=[];for(const i of e.whammyBarPoints)t.addWhammyBarPoint(Ae.clone(i));return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t}}class Ve{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){0===this.beats.length&&(this.id=e.absoluteDisplayStart+"_"+e.voice.index),e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}}!function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext"}(M||(M={}));class He{constructor(){this.id=He._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=p.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=S.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=y.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=L.None,this.whammyBarPoints=[],this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=N.None,this.chordId=null,this.graceType=_.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=P.None,this.tremoloSpeed=null,this.crescendo=b.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=w.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=M.Auto}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===S.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return this.whammyBarType!==L.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.chords.get(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}addWhammyBarPoint(e){this.whammyBarPoints.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===L.None&&(this.whammyBarType=L.Custom)}removeWhammyBarPoint(e){if(e<0||e>=this.whammyBarPoints.length)return;this.whammyBarPoints.splice(e,1);let t=this.whammyBarPoints[e];if(t===this.maxWhammyPoint){this.maxWhammyPoint=null;for(let e of this.whammyBarPoints)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(t===this.minWhammyPoint){this.minWhammyPoint=null;for(let e of this.whammyBarPoints)(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e)}}addNote(e){e.beat=this,e.index=this.notes.length,this.notes.push(e),e.isStringed&&this.noteStringLookup.set(e.string,e)}removeNote(e){let t=this.notes.indexOf(e);t>=0&&this.notes.splice(t,1)}getAutomation(e){for(let t=0,i=this.automations.length;t<i;t++){let i=this.automations[t];if(i.type===e)return i}return null}getNoteOnString(e){return this.noteStringLookup.has(e)?this.noteStringLookup.get(e):null}calculateDuration(){if(this.isFullBarRest)return this.voice.bar.masterBar.calculateDuration();let e=xe.toTicks(this.duration);return 2===this.dots?e=xe.applyDot(e,!0):1===this.dots&&(e=xe.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=xe.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case _.BeforeBeat:case _.OnBeat:switch(this.duration){case S.Sixteenth:this.playbackDuration=xe.toTicks(S.SixtyFourth);break;case S.ThirtySecond:this.playbackDuration=xe.toTicks(S.OneHundredTwentyEighth);break;default:this.playbackDuration=xe.toTicks(S.ThirtySecond)}this.displayDuration=0;break;case _.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===_.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==_.None&&t)&&(e&&t&&t.check(this)||(t=new De(this.voice),t.check(this)),this.tupletGroup=t)}finish(t){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(ve.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case _.OnBeat:case _.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?S.Eighth:2===e?S.Sixteenth:S.ThirtySecond}let i=t?t.notation.notationMode:e.NotationMode.GuitarPro,s="grad"===this.text||"grad."===this.text;s&&i===e.NotationMode.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++){let h=this.notes[o];if(h.dynamics=this.dynamics,h.finish(t),h.isLetRing&&(this.isLetRing=!0),h.isPalmMute&&(this.isPalmMute=!0),i===e.NotationMode.SongBook&&h.hasBend&&this.graceType!==_.BendGrace){if(!h.isTieOrigin)switch(h.bendType){case m.Bend:case m.PrebendRelease:case m.PrebendBend:a=!0}s||h.bendStyle===f.Gradual?(s=!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&&t&&t.notation.notationMode===e.NotationMode.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}if(this.whammyBarPoints.length>0&&this.whammyBarType===L.Custom){i===e.NotationMode.SongBook&&(this.whammyStyle=s?f.Gradual:f.Fast);let t=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=t,4===this.whammyBarPoints.length){let s=this.whammyBarPoints[0],a=this.whammyBarPoints[1],r=this.whammyBarPoints[2],n=this.whammyBarPoints[3];a.value===r.value?s.value<a.value&&a.value<n.value||s.value>a.value&&a.value>n.value?(0===s.value||t?this.whammyBarType=L.Dive:this.whammyBarType=L.PrediveDive,this.whammyBarPoints.splice(2,1),this.whammyBarPoints.splice(1,1)):s.value>a.value&&a.value<n.value||s.value<a.value&&a.value>n.value?(this.whammyBarType=L.Dip,a.offset!==r.offset&&i!==e.NotationMode.SongBook||this.whammyBarPoints.splice(2,1)):s.value===a.value&&a.value===n.value?(0===s.value||t?this.whammyBarType=L.Hold:this.whammyBarType=L.Predive,this.whammyBarPoints.splice(2,1),this.whammyBarPoints.splice(1,1)):Fe.warning("Model","Unsupported whammy type detected, fallback to custom",null):Fe.warning("Model","Unsupported whammy type detected, fallback to custom",null)}}if(this.updateDurations(),a){let e=Ge.clone(this);e.id=He._globalBeatId++,e.pickStroke=P.None;for(let t=0,i=e.notes.length;t<i;t++){let i=e.notes[t],s=this.notes[t];if(i.bendType=m.None,i.maxBendPoint=null,i.bendPoints=[],i.bendStyle=f.Default,i.id=Ie.GlobalNoteId++,s.isTieOrigin&&(i.tieDestinationNoteId=s.tieDestination.id,s.tieDestination.tieOriginNoteId=i.id),s.isTieDestination&&(i.tieOriginNoteId=s.tieOrigin?s.tieOrigin.id:-1,s.tieOrigin.tieDestinationNoteId=i.id),s.hasBend&&s.isTieOrigin){let e=Ie.findTieOrigin(s);if(e&&e.hasBend){i.bendType=m.Hold;let e=s.bendPoints[s.bendPoints.length-1];i.addBendPoint(new Pe(0,e.value)),i.addBendPoint(new Pe(Pe.MaxPosition,e.value))}}i.isTieDestination=!0}this.graceType=_.BendGrace,this.graceGroup=new Ve,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.updateDurations(),this.voice.insertBeat(this,e)}}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(){for(const e of this.notes)this.noteValueLookup.set(e.realValue,e),e.chain()}}He._globalBeatId=0;class We{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(I||(I={}));class Ue{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,i,s){if(!e)return;let a=I.Begin,r=I.Begin,n=!1,o=0;for(;t<e.length;){let i=e.charCodeAt(t);switch(a){case I.IgnoreSpaces:switch(i){case Ue.CharCodeLF:case Ue.CharCodeCR:case Ue.CharCodeTab:break;case Ue.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case I.Begin:switch(i){case Ue.CharCodeBrackedOpen:a=I.Comment;break;default:o=t,a=I.Text;continue}break;case I.Comment:switch(i){case Ue.CharCodeBrackedClose:a=I.Begin}break;case I.Text:switch(i){case Ue.CharCodeDash:a=I.Dash;break;case Ue.CharCodeCR:case Ue.CharCodeLF:case Ue.CharCodeSpace:let i=e.substr(o,t-o);this.addChunk(i,s),a=I.IgnoreSpaces,r=I.Begin}break;case I.Dash:switch(i){case Ue.CharCodeDash:break;default:let i=e.substr(o,t-o);this.addChunk(i,s),n=!0,a=I.IgnoreSpaces,r=I.Begin;continue}}t++}a===I.Text&&t!==o&&this.addChunk(e.substr(o,t-o),s)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){let t=e.split("+").join(" "),i=t.length;for(;i>0&&"_"===t.charAt(i-1);)i--;return i!==t.length?t.substr(0,i):t}}Ue.CharCodeLF=10,Ue.CharCodeTab=9,Ue.CharCodeCR=13,Ue.CharCodeSpace=32,Ue.CharCodeBrackedClose=93,Ue.CharCodeBrackedOpen=91,Ue.CharCodeDash=45,function(e){e[e.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(D||(D={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(A||(A={})),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"}(R||(R={}));class ze{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=D.C,this.keySignatureType=A.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.tripletFeel=R.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=new Map,this.start=0,this.isAnacrusis=!1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let i of t.staves){let t=this.index<i.bars.length?i.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*xe.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){this.fermata.set(e,t)}getFermata(e){return this.fermata.has(e.playbackStart)?this.fermata.get(e.playbackStart):null}}ze.MaxAlternateEndings=8;class Xe{constructor(){this.hideDynamics=!1}}class Ye{constructor(){this.masterBars=[],this.openings=[],this.closings=[],this.isOpened=!1,this.isClosed=!1}addMasterBar(e){0===this.openings.length&&this.openings.push(e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd?(this.closings.push(e),this.isClosed=!0,this.isOpened||(this.masterBars[0].isRepeatStart=!0,this.isOpened=!0)):this.isClosed&&(this.isClosed=!1,this.openings.push(e))}}class qe{constructor(){this._noteByIdLookup=new Map,this._currentRepeatGroup=new Ye,this.album="",this.artist="",this.copyright="",this.instructions="",this.music="",this.notices="",this.subTitle="",this.title="",this.words="",this.tab="",this.tempo=120,this.tempoLabel="",this.masterBars=[],this.tracks=[],this.stylesheet=new Xe}rebuildRepeatGroups(){let e=new Ye;for(let t of this.masterBars)(t.isRepeatStart||this._currentRepeatGroup.isClosed&&t.alternateEndings<=0)&&(e=new Ye),e.addMasterBar(t)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+e.previousMasterBar.calculateDuration()),(e.isRepeatStart||this._currentRepeatGroup.isClosed&&e.alternateEndings<=0)&&(this._currentRepeatGroup=new Ye),this._currentRepeatGroup.addMasterBar(e),this.masterBars.push(e)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){this._noteByIdLookup.clear();for(let t=0,i=this.tracks.length;t<i;t++)this.tracks[t].finish(e)}registerNote(e){this._noteByIdLookup.set(e.id,e)}getNoteById(e){return this._noteByIdLookup.has(e)?this._noteByIdLookup.get(e):null}}class Je{constructor(){this.marker="",this.text=""}}class Qe{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 je{constructor(e="",t=null,i=!1){this.isStandard=i,this.name=e,this.tunings=null!=t?t:[]}static getTextForTuning(e,t){let i=je.getTextPartsForTuning(e);return t?i.join(""):i[0]}static getTextPartsForTuning(e,t=-1){return[["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"][e%12],((e/12|0)+t).toString()]}static getDefaultTuningFor(e){return je._defaultTunings.has(e)?je._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return je._sevenStrings;case 6:return je._sixStrings;case 5:return je._fiveStrings;case 4:return je._fourStrings}return[]}static initialize(){je._defaultTunings.set(7,new je("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),je._sevenStrings.push(je._defaultTunings.get(7)),je._defaultTunings.set(6,new je("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),je._sixStrings.push(je._defaultTunings.get(6)),je._sixStrings.push(new je("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),je._sixStrings.push(new je("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),je._sixStrings.push(new je("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),je._sixStrings.push(new je("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),je._sixStrings.push(new je("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),je._sixStrings.push(new je("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),je._sixStrings.push(new je("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),je._sixStrings.push(new je("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),je._sixStrings.push(new je("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),je._sixStrings.push(new je("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),je._sixStrings.push(new je("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),je._sixStrings.push(new je("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),je._sixStrings.push(new je("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),je._sixStrings.push(new je("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),je._sixStrings.push(new je("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),je._sixStrings.push(new je("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),je._sixStrings.push(new je("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),je._sixStrings.push(new je("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),je._sixStrings.push(new je("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),je._sixStrings.push(new je("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),je._sixStrings.push(new je("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),je._sixStrings.push(new je("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),je._sixStrings.push(new je("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),je._sixStrings.push(new je("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),je._sixStrings.push(new je("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),je._sixStrings.push(new je("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),je._sixStrings.push(new je("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),je._sixStrings.push(new je("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),je._sixStrings.push(new je("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),je._sixStrings.push(new je("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),je._defaultTunings.set(5,new je("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),je._fiveStrings.push(je._defaultTunings.get(5)),je._fiveStrings.push(new je("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),je._fiveStrings.push(new je("Banjo Open D Tuning",[62,57,54,50,69],!1)),je._fiveStrings.push(new je("Banjo Open G Tuning",[62,59,55,50,67],!1)),je._fiveStrings.push(new je("Banjo G Minor Tuning",[62,58,55,50,67],!1)),je._fiveStrings.push(new je("Banjo G Modal Tuning",[62,57,55,50,67],!1)),je._defaultTunings.set(4,new je("Bass Standard Tuning",[43,38,33,28],!0)),je._fourStrings.push(je._defaultTunings.get(4)),je._fourStrings.push(new je("Bass Tune down ½ step",[42,37,32,27],!1)),je._fourStrings.push(new je("Bass Tune down 1 step",[41,36,31,26],!1)),je._fourStrings.push(new je("Bass Tune down 2 step",[39,34,29,24],!1)),je._fourStrings.push(new je("Bass Dropped D Tuning",[43,38,33,26],!1)),je._fourStrings.push(new je("Ukulele C Tuning",[45,40,36,43],!1)),je._fourStrings.push(new je("Ukulele G Tuning",[52,47,43,38],!1)),je._fourStrings.push(new je("Mandolin Standard Tuning",[64,57,50,43],!1)),je._fourStrings.push(new je("Mandolin or Violin Tuning",[76,69,62,55],!1)),je._fourStrings.push(new je("Viola Tuning",[69,62,55,48],!1)),je._fourStrings.push(new je("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=je.getPresetsFor(e.length);for(let i=0,s=t.length;i<s;i++){let s=t[i],a=!0;for(let t=0,i=e.length;t<i;t++)if(e[t]!==s.tunings[t]){a=!1;break}if(a)return s}return null}finish(){const e=je.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}je._sevenStrings=[],je._sixStrings=[],je._fiveStrings=[],je._fourStrings=[],je._defaultTunings=new Map,je.defaultAccidentals=["","#","","#","","","#","","#","","#",""],je.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],je.initialize();class Ke{constructor(){this.index=0,this.bars=[],this.chords=new Map,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new je("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e){this.stringTuning.finish();for(let t=0,i=this.bars.length;t<i;t++)this.bars[t].finish(e)}addChord(e,t){t.staff=this,this.chords.set(e,t)}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}class $e{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Qe,this.color=new me(200,0,0,255),this.name="",this.shortName="",this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new Ke)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e){this.shortName||(this.shortName=this.name,this.shortName.length>$e.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,$e.ShortNameMaxLength)));for(let t=0,i=this.staves.length;t<i;t++)this.staves[t].finish(e)}applyLyrics(e){for(let t of e)t.finish();let t=this.staves[0];for(let i=0;i<e.length;i++){let s=e[i];if(s.startBar>=0&&s.startBar<t.bars.length){let a=t.bars[s.startBar].voices[0].beats[0];for(let t=0;t<s.chunks.length&&a;t++){for(;a&&(a.isEmpty||a.isRest);)a=a.nextBeat;a&&(a.lyrics||(a.lyrics=new Array(e.length)),a.lyrics[i]=s.chunks[t],a=a.nextBeat)}}}}}$e.ShortNameMaxLength=10;class Ze{constructor(){this.id=Ze._globalBarId++,this.index=0,this.beats=[],this.isEmpty=!0}insertBeat(e,t){t.nextBeat=e.nextBeat,t.nextBeat&&(t.nextBeat.previousBeat=t),t.previousBeat=e,t.voice=this,e.nextBeat=t,this.beats.splice(e.index+1,0,t)}addBeat(e){e.voice=this,e.index=this.beats.length,this.beats.push(e),e.isEmpty||(this.isEmpty=!1)}chain(e){if(this.bar){if(e.index<this.beats.length-1)e.nextBeat=this.beats[e.index+1],e.nextBeat.previousBeat=e;else if(e.isLastOfVoice&&e.voice.bar.nextBar){let t=this.bar.nextBar.voices[this.index];t.beats.length>0?(e.nextBeat=t.beats[0],e.nextBeat.previousBeat=e):e.nextBeat.previousBeat=e}e.chain()}}addGraceBeat(e){if(0===this.beats.length)return void this.addBeat(e);let t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this.isEmpty=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e){this._beatLookup=new Map;let t=null;for(let e=0;e<this.beats.length;e++){let i=this.beats[e];i.index=e,this.chain(i),i.graceType===_.None?(i.graceGroup=t,t&&(t.isComplete=!0),t=null):(t||(t=new Ve),t.addBeat(i))}let i=0,s=0;for(let t=0;t<this.beats.length;t++){let a=this.beats[t];if(a.index=t,a.finish(e),a.graceType===_.None){if(a.graceGroup){const e=a.graceGroup.beats[0],t=a.graceGroup.beats[a.graceGroup.beats.length-1];if(e.graceType!==_.BendGrace){let i=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case _.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=i,s=e.previousBeat.voice==this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-i):s=-i;for(const e of a.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=s,this._beatLookup.set(e.playbackStart,a),s+=e.playbackDuration;break;case _.OnBeat:a.playbackDuration-=i,s=t.voice===this?t.playbackStart+t.playbackDuration:-i}}}a.fermata?this.bar.masterBar.addFermata(a.playbackStart,a.fermata):a.fermata=this.bar.masterBar.getFermata(a),this._beatLookup.set(a.playbackStart,a)}a.displayStart=i,a.playbackStart=s,a.finishTuplet(),i+=a.displayDuration,s+=a.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;let e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}}Ze._globalBarId=0,function(e){e[e.No=0]="No",e[e.Eof=1]="Eof",e[e.Number=2]="Number",e[e.DoubleDot=3]="DoubleDot",e[e.Dot=4]="Dot",e[e.String=5]="String",e[e.Tuning=6]="Tuning",e[e.LParensis=7]="LParensis",e[e.RParensis=8]="RParensis",e[e.LBrace=9]="LBrace",e[e.RBrace=10]="RBrace",e[e.Pipe=11]="Pipe",e[e.MetaCommand=12]="MetaCommand",e[e.Multiply=13]="Multiply",e[e.LowerThan=14]="LowerThan",e[e.Property=15]="Property"}(O||(O={}));class et extends ce{constructor(t){super(e.AlphaTabErrorType.AlphaTex,t),this.position=0,this.nonTerm="",this.expected=O.No,this.symbol=O.No,Object.setPrototypeOf(this,et.prototype)}static symbolError(e,t,i,s,a=null){let r;r=a?`MalFormed AlphaTex: @${e}: Error on block ${t}, invalid value: ${a}`:`MalFormed AlphaTex: @${e}: Error on block ${t}, expected a ${O[i]} found a ${O[s]}: '${a}'`;let n=new et(r);return n.position=e,n.nonTerm=t,n.expected=i,n.symbol=s,n.symbolData=a,n}static errorMessage(e,t){let i=new et(t="MalFormed AlphaTex: @"+e+": "+t);return i.position=e,i}}class tt extends Te{constructor(){super(),this._trackChannel=0,this._ch=0,this._curChPos=0,this._sy=O.No,this._allowNegatives=!1,this._allowTuning=!1,this._currentDuration=S.QuadrupleWhole,this._currentDynamics=w.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1}get name(){return"AlphaTex"}readScore(){try{if(this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._currentDuration=S.Quarter,this._currentDynamics=w.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===O.LowerThan)throw new ke("Unknown start sign <");this.score(),this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);return this._score}catch(e){throw e instanceof et?new ke(e.message):e}}consolidate(){for(let e of this._score.tracks)for(let t of e.staves)for(;t.bars.length<this._score.masterBars.length;){let e=this.newBar(t),i=new He;i.isEmpty=!0,e.voices[0].addBeat(i)}}error(e,t,i=!0){let s;throw s=i?et.symbolError(this._curChPos,e,t,this._sy,null):et.symbolError(this._curChPos,e,t,t,this._syData),Fe.error(this.name,s.message),s}errorMessage(e){let t=et.errorMessage(this._curChPos,e);throw Fe.error(this.name,t.message),t}createDefaultScore(){this._score=new qe,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new $e,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++,this._currentStaff=this._currentTrack.staves[0],this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=je.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=w.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":return u.G2;case"f4":case"bass":return u.F4;case"c3":case"tenor":return u.C3;case"c4":case"alto":return u.C4;case"n":case"neutral":return u.Neutral;default:return u.G2}}parseClefFromInt(e){switch(e){case 43:return u.G2;case 65:return u.F4;case 48:return u.C3;case 60:return u.C4;default:return u.G2}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":return R.NoTripletFeel;case"t16":case"triplet-16th":return R.Triplet16th;case"t8":case"triplet-8th":return R.Triplet8th;case"d16":case"dotted-16th":return R.Dotted16th;case"d8":case"dotted-8th":return R.Dotted8th;case"s16":case"scottish-16th":return R.Scottish16th;case"s8":case"scottish-8th":return R.Scottish8th;default:return R.NoTripletFeel}}parseTripletFeelFromInt(e){switch(e){case 0:return R.NoTripletFeel;case 1:return R.Triplet16th;case 2:return R.Triplet8th;case 3:return R.Dotted16th;case 4:return R.Dotted8th;case 5:return R.Scottish16th;case 6:return R.Scottish8th;default:return R.NoTripletFeel}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":return-7;case"gb":return-6;case"db":return-5;case"ab":return-4;case"eb":return-3;case"bb":return-2;case"f":return-1;case"c":return 0;case"g":return 1;case"d":return 2;case"a":return 3;case"e":return 4;case"b":return 5;case"f#":return 6;case"c#":return 7;default:return 0}}nextChar(){let e=this.data.readByte();return-1===e?this._ch=0:(this._ch=e,this._curChPos++),this._ch}newSy(){this._sy=O.No;do{if(this._ch===tt.Eof)this._sy=O.Eof;else if(32===this._ch||11===this._ch||13===this._ch||10===this._ch||9===this._ch)this._ch=this.nextChar();else if(47===this._ch)if(this._ch=this.nextChar(),47===this._ch)for(;13!==this._ch&&10!==this._ch&&this._ch!==tt.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;0!==this._ch;)if(42===this._ch){if(this._ch=this.nextChar(),47===this._ch){this._ch=this.nextChar();break}}else this._ch=this.nextChar();else this.error("symbol",O.String,!1);else if(34===this._ch||39===this._ch){let e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=O.String;this._ch!==e&&this._ch!==tt.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)if(this._allowNegatives&&this.isDigit(this._ch)){let e=this.readNumber();this._sy=O.Number,this._syData=e}else this._sy=O.String,this._syData=this.readName();else if(46===this._ch)this._sy=O.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=O.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=O.LParensis,this._ch=this.nextChar();else if(92===this._ch){this._ch=this.nextChar();let e=this.readName();this._sy=O.MetaCommand,this._syData=e}else if(41===this._ch)this._sy=O.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=O.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=O.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=O.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=O.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=O.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch)){let e=this.readNumber();this._sy=O.Number,this._syData=e}else if(tt.isLetter(this._ch)){let e=this.readName(),t=this._allowTuning?fe.parseTuning(e):null;t?(this._sy=O.Tuning,this._syData=t):(this._sy=O.String,this._syData=e)}else this.error("symbol",O.String,!1)}while(this._sy===O.No);return this._sy}static isLetter(e){return!tt.isTerminal(e)&&(e>=33&&e<=47||e>=58&&e<=126||e>128)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||92===e}isDigit(e){return e>=48&&e<=57||45===e&&this._allowNegatives}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(tt.isLetter(this._ch)||this.isDigit(this._ch)||35===this._ch);return e}readNumber(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(this.isDigit(this._ch));return parseInt(e)}score(){if(this._sy===O.Eof)throw new ke("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new ke("No alphaTex data found")}metaData(){let e=!1,t=!0;for(;this._sy===O.MetaCommand&&t;){switch(this._syData.toLowerCase()){case"title":this._sy=this.newSy(),this._sy===O.String?this._score.title=this._syData:this.error("title",O.String,!0),this._sy=this.newSy(),e=!0;break;case"subtitle":this._sy=this.newSy(),this._sy===O.String?this._score.subTitle=this._syData:this.error("subtitle",O.String,!0),this._sy=this.newSy(),e=!0;break;case"artist":this._sy=this.newSy(),this._sy===O.String?this._score.artist=this._syData:this.error("artist",O.String,!0),this._sy=this.newSy(),e=!0;break;case"album":this._sy=this.newSy(),this._sy===O.String?this._score.album=this._syData:this.error("album",O.String,!0),this._sy=this.newSy(),e=!0;break;case"words":this._sy=this.newSy(),this._sy===O.String?this._score.words=this._syData:this.error("words",O.String,!0),this._sy=this.newSy(),e=!0;break;case"music":this._sy=this.newSy(),this._sy===O.String?this._score.music=this._syData:this.error("music",O.String,!0),this._sy=this.newSy(),e=!0;break;case"copyright":this._sy=this.newSy(),this._sy===O.String?this._score.copyright=this._syData:this.error("copyright",O.String,!0),this._sy=this.newSy(),e=!0;break;case"tempo":this._sy=this.newSy(),this._sy===O.Number?this._score.tempo=this._syData:this.error("tempo",O.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",O.String,!1):t=!1}}return e?(this._sy!==O.Dot&&this.error("song",O.Dot,!0),this._sy=this.newSy()):this._sy===O.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===O.Number?this._currentStaff.capo=this._syData:this.error("capo",O.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case O.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",O.Tuning,!0),this._sy=this.newSy();break;case O.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===O.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",O.Tuning,!0)}return e!==this._currentStaff.tuning.length&&this._currentStaff.chords.size>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===O.Number){let e=this._syData;e>=0&&e<=128?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",O.Number,!1)}else if(this._sy===O.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=ue.getValue(e)}else this.error("instrument",O.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let t=new Ue;return t.startBar=0,t.text="",this._sy===O.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===O.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",O.String,!0),this._lyrics.get(this._currentTrack.index).push(t),!0;case"chord":this._sy=this.newSy();let i=new We;this.chordProperties(i),this._sy===O.String?(i.name=this._syData,this._sy=this.newSy()):this.error("chord-name",O.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===O.Number?i.strings.push(this._syData):this._sy===O.String&&"x"===this._syData.toLowerCase()&&i.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,i.name),i),!0;default:return!1}}chordProperties(e){if(this._sy===O.LBrace){for(this._sy=this.newSy();this._sy===O.String;)switch(this._syData.toLowerCase()){case"firstfret":switch(this._sy=this.newSy(),this._sy){case O.Number:e.firstFret=this._syData;break;default:this.error("chord-firstfret",O.Number,!0)}this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case O.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case O.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",O.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case O.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case O.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",O.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case O.String:e.showName="false"!==this._syData.toLowerCase();break;case O.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",O.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===O.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",O.String,!1)}this._sy!==O.RBrace&&this.error("chord-properties",O.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==O.Eof;)if(this._sy===O.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==O.MetaCommand)break;this.bar()}return e}trackStaffMeta(){let e=!1;if(this._sy===O.MetaCommand){e=!0;let t=this._syData.toLowerCase();"track"===t&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===O.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===O.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===O.MetaCommand&&(t=this._syData.toLowerCase(),"staff"===t&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=w.F),this.staffProperties()))}return e}staffProperties(){if(this._sy!==O.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===O.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy();break;case"tabs":t=!0,this._sy=this.newSy();break;default:this.error("staff-properties",O.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==O.RBrace&&this.error("staff-properties",O.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta();let t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){let e=new ze;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const i=this.barMeta(t);if(!this._staffTuningApplied&&!this._staffHasExplicitTuning){const e=this._currentTrack.playbackInfo.program;this._currentStaff.displayTranspositionPitch=0,this._currentStaff.stringTuning.tunings=[],15==e||e>=24&&e<=31?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=je.getDefaultTuningFor(6).tunings):e>=32&&e<=39?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):40==e||44==e||45==e||48==e||49==e||50==e||51==e?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==e?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==e?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==e?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):105==e?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==e?this._currentStaff.stringTuning.tunings=[57,52,45]:107==e?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==e&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0}let s=!1,a=t.voices[0];for(;this._sy!==O.Pipe&&this._sy!==O.Eof&&this.beat(a);)s=!0;if(0===a.beats.length){let e=new He;e.isEmpty=!0,a.addBeat(e)}return e||i||s}newBar(e){let t=new Ne;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let i=new Ze;return t.addVoice(i),t}beat(e){this.beatDuration();let t=new He;if(e.addBeat(t),this._sy===O.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==O.RParensis&&this._sy!==O.Eof&&this.note(t););this._sy!==O.RParensis&&this.error("note-list",O.RParensis,!0),this._sy=this.newSy()}else if(this._sy===O.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===O.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==O.Number&&this.error("duration",O.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._sy=this.newSy()),t.duration=this._currentDuration,t.dynamics=this._currentDynamics,1===this._currentTuplet||t.hasTuplet||this.applyTuplet(t,this._currentTuplet);let i=1;this._sy===O.Multiply&&(this._sy=this.newSy(),this._sy!==O.Number?this.error("multiplier",O.Number,!0):i=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let s=0;s<i-1;s++)e.addBeat(Ge.clone(t));return!0}beatDuration(){if(this._sy===O.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==O.Number&&this.error("duration",O.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===O.LBrace)){for(this._sy=this.newSy();this._sy===O.String;){switch(this._syData.toLowerCase()){case"tu":this._sy=this.newSy(),this._sy!==O.Number&&this.error("duration-tuplet",O.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();break;default:this.error("beat-duration",O.String,!1)}}this._sy!==O.RBrace&&this.error("beat-duration",O.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===O.LBrace){for(this._sy=this.newSy();this._sy===O.String;)this._syData=this._syData.toLowerCase(),this.applyBeatEffect(e)||this.error("beat-effects",O.String,!1);this._sy!==O.RBrace&&this.error("beat-effects",O.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)return e.fadeIn=!0,this._sy=this.newSy(),!0;if("v"===t)return e.vibrato=N.Slight,this._sy=this.newSy(),!0;if("s"===t)return e.slap=!0,this._sy=this.newSy(),!0;if("p"===t)return e.pop=!0,this._sy=this.newSy(),!0;if("tt"===t)return e.tap=!0,this._sy=this.newSy(),!0;if("dd"===t)return e.dots=2,this._sy=this.newSy(),!0;if("d"===t)return e.dots=1,this._sy=this.newSy(),!0;if("su"===t)return e.pickStroke=P.Up,this._sy=this.newSy(),!0;if("sd"===t)return e.pickStroke=P.Down,this._sy=this.newSy(),!0;if("tu"===t)return this._sy=this.newSy(),this._sy!==O.Number?(this.error("tuplet",O.Number,!0),!1):(this.applyTuplet(e,this._syData),this._sy=this.newSy(),!0);if("tb"===t||"tbe"===t){let i="tbe"===t;if(this._sy=this.newSy(),this._sy!==O.LParensis)return this.error("tremolobar-effect",O.LParensis,!0),!1;for(this._allowNegatives=!0,this._sy=this.newSy();this._sy!==O.RParensis&&this._sy!==O.Eof;){let t=0,s=0;if(i){if(this._sy!==O.Number)return this.error("tremolobar-effect",O.Number,!0),!1;if(t=this._syData,this._sy=this.newSy(),this._sy!==O.Number)return this.error("tremolobar-effect",O.Number,!0),!1;s=this._syData}else{if(this._sy!==O.Number)return this.error("tremolobar-effect",O.Number,!0),!1;t=0,s=this._syData}e.addWhammyBarPoint(new Pe(t,s)),this._sy=this.newSy()}for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(i)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{let t=e.whammyBarPoints.length,i=60/t|0,s=0;for(;s<t;)e.whammyBarPoints[s].offset=Math.min(60,s*i),s++}return this._allowNegatives=!1,this._sy!==O.RParensis?(this.error("tremolobar-effect",O.RParensis,!0),!1):(this._sy=this.newSy(),!0)}if("ch"===t){this._sy=this.newSy();let t=this._syData,i=this.getChordId(this._currentStaff,t);if(!this._currentStaff.chords.has(i)){let e=new We;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(i,e)}return e.chordId=i,this._sy=this.newSy(),!0}if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=_.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=_.BendGrace,this._sy=this.newSy()):e.graceType=_.BeforeBeat,!0;if("dy"===t){switch(this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=w.PPP;break;case"pp":e.dynamics=w.PP;break;case"p":e.dynamics=w.P;break;case"mp":e.dynamics=w.MP;break;case"mf":e.dynamics=w.MF;break;case"f":e.dynamics=w.F;break;case"ff":e.dynamics=w.FF;break;case"fff":e.dynamics=w.FFF}return this._currentDynamics=e.dynamics,this.newSy(),!0}if("cre"===t)return e.crescendo=b.Crescendo,this.newSy(),!0;if("dec"===t)return e.crescendo=b.Decrescendo,this.newSy(),!0;if("tp"===t){this._sy=this.newSy();let t=S.Eighth;if(this._sy===O.Number){switch(this._syData){case 8:t=S.Eighth;break;case 16:t=S.Sixteenth;break;case 32:t=S.ThirtySecond;break;default:t=S.Eighth}this._sy=this.newSy()}return e.tremoloSpeed=t,!0}return!1}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}note(e){let t=!1,i=!1,s=-1,a=-1,r=-1;switch(this._sy){case O.Number:s=this._syData;break;case O.String:t="x"===this._syData,i="-"===this._syData,i||t?s=0:this.error("note-fret",O.Number,!0);break;case O.Tuning:let e=this._syData;a=e.octave,r=e.noteValue;break;default:return!1}this._sy=this.newSy();let n=-1===a&&this._currentStaff.tuning.length>0,o=-1;n&&(this._sy!==O.Dot&&this.error("note",O.Dot,!0),this._sy=this.newSy(),this._sy!==O.Number&&this.error("note-string",O.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",O.Number,!1),this._sy=this.newSy());let h=new Ie;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=i,i||(h.fret=s)):(h.octave=a,h.tone=r,h.isTieDestination=i),e.addNote(h),this.noteEffects(h),!0}noteEffects(e){if(this._sy===O.LBrace){for(this._sy=this.newSy();this._sy===O.String;){let t=this._syData.toLowerCase();if(this._syData=t,"b"===t||"be"===t){let t="be"===this._syData;for(this._sy=this.newSy(),this._sy!==O.LParensis&&this.error("bend-effect",O.LParensis,!0),this._sy=this.newSy();this._sy!==O.RParensis&&this._sy!==O.Eof;){let i=0,s=0;t?(this._sy!==O.Number&&this.error("bend-effect-value",O.Number,!0),i=this._syData,this._sy=this.newSy(),this._sy!==O.Number&&this.error("bend-effect-value",O.Number,!0),s=this._syData):(this._sy!==O.Number&&this.error("bend-effect-value",O.Number,!0),s=this._syData),e.addBendPoint(new Pe(i,s)),this._sy=this.newSy()}for(;e.bendPoints.length>60;)e.bendPoints.splice(e.bendPoints.length-1,1);if(t)e.bendPoints.sort(((e,t)=>e.offset-t.offset));else{let t=e.bendPoints.length,i=60/(t-1)|0,s=0;for(;s<t;)e.bendPoints[s].offset=Math.min(60,s*i),s++}this._sy!==O.RParensis&&this.error("bend-effect",O.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=B.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=B.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=B.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=B.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=B.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==O.Number&&this.error("trill-effect",O.Number,!0);let t=this._syData;this._sy=this.newSy();let i=S.Sixteenth;if(this._sy===O.Number){switch(this._syData){case 16:i=S.Sixteenth;break;case 32:i=S.ThirtySecond;break;case 64:i=S.SixtyFourth;break;default:i=S.Sixteenth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=i}else if("v"===t)this._sy=this.newSy(),e.vibrato=N.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=v.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=v.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=v.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=v.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=v.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=v.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=c.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=c.Heavy;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=i.Thumb;this._sy===O.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=i.Thumb;this._sy===O.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,O.String,!1)}this._sy!==O.RBrace&&this.error("note-effect",O.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return i.Thumb;case 2:return i.IndexFinger;case 3:return i.MiddleFinger;case 4:return i.AnnularFinger;case 5:return i.LittleFinger}return i.Thumb}parseDuration(e){switch(e){case-4:return S.QuadrupleWhole;case-2:return S.DoubleWhole;case 1:return S.Whole;case 2:return S.Half;case 4:return S.Quarter;case 8:return S.Eighth;case 16:return S.Sixteenth;case 32:return S.ThirtySecond;case 64:return S.SixtyFourth;case 128:return S.OneHundredTwentyEighth;default:return S.Quarter}}barMeta(e){let t=!1,i=e.masterBar;for(;this._sy===O.MetaCommand;){t=!0;let s=this._syData.toLowerCase();if("ts"===s)this._sy=this.newSy(),this._sy!==O.Number&&this.error("timesignature-numerator",O.Number,!0),i.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==O.Number&&this.error("timesignature-denominator",O.Number,!0),i.timeSignatureDenominator=this._syData,this._sy=this.newSy();else if("ro"===s)i.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===s)this._sy=this.newSy(),this._sy!==O.Number&&this.error("repeatclose",O.Number,!0),i.repeatCount=this._syData,this._sy=this.newSy();else if("ks"===s)this._sy=this.newSy(),this._sy!==O.String&&this.error("keysignature",O.String,!0),i.keySignature=this.parseKeySignature(this._syData.toLowerCase()),this._sy=this.newSy();else if("clef"===s){switch(this._sy=this.newSy(),this._sy){case O.String:e.clef=this.parseClefFromString(this._syData.toLowerCase());break;case O.Number:e.clef=this.parseClefFromInt(this._syData);break;case O.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",O.String,!0)}this._sy=this.newSy()}else if("tempo"===s){this._sy=this.newSy(),this._sy!==O.Number&&this.error("tempo",O.Number,!0);let e=new ve;e.isLinear=!1,e.type=d.Tempo,e.value=this._syData,i.tempoAutomation=e,this._sy=this.newSy()}else if("section"===s){this._sy=this.newSy(),this._sy!==O.String&&this.error("section",O.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy===O.String&&(t=e,e=this._syData,this._sy=this.newSy());let s=new Je;s.marker=t,s.text=e,i.section=s}else if("tf"===s){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case O.String:i.tripletFeel=this.parseTripletFeelFromString(this._syData.toLowerCase());break;case O.Number:i.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",O.String,!0)}this._sy=this.newSy()}else"ac"===s?(i.isAnacrusis=!0,this._sy=this.newSy()):0!==e.index||this.handleStaffMeta()||this.error("measure-effects",O.String,!1)}if(0===i.index&&!i.tempoAutomation){let e=new ve;e.isLinear=!1,e.type=d.Tempo,e.value=this._score.tempo,i.tempoAutomation=e}return t}}tt.Eof=0;class it{static uint16ToInt16(e){return it._dataView.setUint16(0,e,!0),it._dataView.getInt16(0,!0)}static int16ToUint32(e){return it._dataView.setInt16(0,e,!0),it._dataView.getUint32(0,!0)}static int32ToUint16(e){return it._dataView.setInt32(0,e,!0),it._dataView.getUint16(0,!0)}static int32ToInt16(e){return it._dataView.setInt32(0,e,!0),it._dataView.getInt16(0,!0)}static int32ToUint32(e){return it._dataView.setInt32(0,e,!0),it._dataView.getUint32(0,!0)}static uint8ToInt8(e){return it._dataView.setUint8(0,e),it._dataView.getInt8(0)}}it._conversionBuffer=new ArrayBuffer(8),it._dataView=new DataView(it._conversionBuffer);class st{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readInt32LE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte();return e.readByte()<<24|s<<16|i<<8|t}static readUInt32LE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte();return e.readByte()<<24|s<<16|i<<8|t}static decodeUInt32LE(e,t){let i=e[t],s=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|s<<8|i}static readUInt16LE(e){let t=e.readByte(),i=e.readByte();return it.int32ToUint16(i<<8|t)}static readInt16LE(e){let t=e.readByte(),i=e.readByte();return it.int32ToInt16(i<<8|t)}static readUInt32BE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte(),a=e.readByte();return it.int32ToUint32(t<<24|i<<16|s<<8|a)}static readUInt16BE(e){let t=e.readByte(),i=e.readByte();return it.int32ToInt16(t<<8|i)}static readInt16BE(e){let t=e.readByte(),i=e.readByte();return it.int32ToInt16(t<<8|i)}static readByteArray(e,t){let i=new Uint8Array(t);return e.read(i,0,t),i}static read8BitChars(e,t){let i=new Uint8Array(t);return e.read(i,0,i.length),st.toString(i,"utf-8")}static read8BitString(e){let t="",i=e.readByte();for(;0!==i;)t+=String.fromCharCode(i),i=e.readByte();return t}static read8BitStringLength(e,t){let i="",s=-1;for(let a=0;a<t;a++){let t=e.readByte();0===t&&-1===s&&(s=a),i+=String.fromCharCode(t)}let a=i;return s>=0?a.substr(0,s):a}static readSInt8(e){let t=e.readByte();return-256*((255&t)>>7)+(255&t)}static readInt24(e,t){let i=e[t]|e[t+1]<<8|e[t+2]<<16;return 8388608==(8388608&i)&&(i|=255<<24),i}static readInt16(e,t){return it.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let i=st.detectEncoding(e);return i&&(t=i),t||(t="utf-8"),new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(t>>0&255)}static writeInt32LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}}class at extends Te{constructor(){super(),this._versionNumber=0,this._globalTripletFeel=R.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map}get name(){return"Guitar Pro 3-5"}readScore(){return this.readVersion(),this._score=new qe,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=rt.gpReadBool(this.data)?R.Triplet8th:R.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=rt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=st.readInt32LE(this.data),this._versionNumber>=510&&rt.gpReadBool(this.data),st.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=st.readInt32LE(this.data),this._trackCount=st.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=ve.buildTempoAutomation(!1,0,this._score.tempo,2),this._score.masterBars[0].tempoAutomation.text=this._score.tempoLabel),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readVersion(){let e=rt.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(at.VersionString))throw new ke("Unsupported format");e=e.substr(at.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),Fe.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){var e;this._score.title=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let t=st.readInt32LE(this.data),i="";for(let s=0;s<t;s++)s>0&&(i+="\r\n"),i+=null===(e=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding))||void 0===e?void 0:e.toString();this._score.notices=i}readLyrics(){this._lyrics=[],this._lyricsTrack=st.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new Ue;e.startBar=st.readInt32LE(this.data)-1,e.text=rt.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)rt.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Qe;t.primaryChannel=e,t.secondaryChannel=e,t.program=st.readInt32LE(this.data),t.volume=this.data.readByte(),t.balance=this.data.readByte(),this.data.skip(6),this._playbackInfos.push(t)}}readMasterBars(){for(let e=0;e<this._barCount;e++)this.readMasterBar()}readMasterBar(){let e=null;this._score.masterBars.length>0&&(e=this._score.masterBars[this._score.masterBars.length-1]);let t=new ze,i=this.data.readByte();if(0!=(1&i)?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),0!=(2&i)?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=0!=(4&i),0!=(8&i)&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),0!=(16&i))if(this._versionNumber<500){let i=e,s=0;for(;i&&(!i.isRepeatEnd||i===e)&&!i.isRepeatStart;)s|=i.alternateEndings,i=i.previousMasterBar;let a=0,r=this.data.readByte();for(let e=0;e<8;e++){let t=1<<e;r>e&&0==(s&t)&&(a|=t)}t.alternateEndings=a}else t.alternateEndings=this.data.readByte();if(0!=(32&i)){let e=new Je;e.text=rt.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",rt.gpReadColor(this.data,!1),t.section=e}if(0!=(64&i)?(t.keySignature=st.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&0!=(3&i)&&this.data.skip(4),this._versionNumber>=500&&0==(16&i)&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=R.Triplet8th;break;case 2:t.tripletFeel=R.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=0!=(128&i),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new $e;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],i=this.data.readByte();e.name=rt.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),0!=(1&i)&&(t.isPercussion=!0);let s=st.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=st.readInt32LE(this.data);s>e&&a.push(t)}t.stringTuning.tunings=a;let r=st.readInt32LE(this.data),n=st.readInt32LE(this.data)-1,o=st.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){let s=this._playbackInfos[n];s.port=r,s.isSolo=0!=(16&i),s.isMute=0!=(32&i),s.secondaryChannel=o,ue.isGuitar(s.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=s}t.capo=st.readInt32LE(this.data),e.color=rt.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),rt.gpReadStringIntByte(this.data,this.settings.importer.encoding),rt.gpReadStringIntByte(this.data,this.settings.importer.encoding))}readBars(){for(let e=0;e<this._barCount;e++)for(let e=0;e<this._trackCount;e++)this.readBar(this._score.tracks[e])}readBar(e){let t=new Ne,i=e.staves[0];i.isPercussion&&(t.clef=u.Neutral),i.addBar(t);let s=1;this._versionNumber>=500&&(this.data.readByte(),s=2);for(let i=0;i<s;i++)this.readVoice(e,t)}readVoice(e,t){let i=st.readInt32LE(this.data);if(0===i)return;let s=new Ze;t.addVoice(s);for(let a=0;a<i;a++)this.readBeat(e,t,s)}readBeat(e,t,i){let s=new He,a=this.data.readByte();if(0!=(1&a)&&(s.dots=1),0!=(64&a)){let e=this.data.readByte();s.isEmpty=0==(2&e)}switch(i.addBeat(s),st.readSInt8(this.data)){case-2:s.duration=S.Whole;break;case-1:s.duration=S.Half;break;case 0:s.duration=S.Quarter;break;case 1:s.duration=S.Eighth;break;case 2:s.duration=S.Sixteenth;break;case 3:s.duration=S.ThirtySecond;break;case 4:s.duration=S.SixtyFourth;break;default:s.duration=S.Quarter}if(0!=(32&a))switch(s.tupletNumerator=st.readInt32LE(this.data),s.tupletNumerator){case 1:s.tupletDenominator=1;break;case 3:s.tupletDenominator=2;break;case 5:case 6:case 7:s.tupletDenominator=4;break;case 9:case 10:case 11:case 12:case 13:s.tupletDenominator=8;break;case 2:case 4:case 8:break;default:s.tupletNumerator=1,s.tupletDenominator=1}0!=(2&a)&&this.readChord(s);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(0!=(4&a)){const t=rt.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const i=new Ue;i.text=t.trim(),i.finish(!0);const s=[];for(let e=i.chunks.length-1;e>=0;e--)s.push(i.chunks[e]);this._beatTextChunksByTrack.set(e.index,s)}else s.text=t}let n=B.None;0!=(8&a)&&(n=this.readBeatEffects(s)),0!=(16&a)&&this.readMixTableChange(s);let o=this.data.readByte();for(let a=6;a>=0;a--)if(0!=(o&1<<a)&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,i,s,6-a);n!==B.None&&(r.harmonicType=n,r.harmonicType===B.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),0!=(8&this.data.readByte())&&this.data.readByte()}r&&!s.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(s.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){let t=new We,i=fe.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=rt.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=st.readInt32LE(this.data);for(let i=0;i<7;i++){let s=st.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}let i=this.data.readByte(),s=new Uint8Array(5);this.data.read(s,0,s.length);for(let e=0;e<i;e++)t.barreFrets.push(s[e]);this.data.skip(26)}else if(0!==this.data.readByte())if(this._versionNumber>=400){this.data.skip(16),t.name=rt.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=st.readInt32LE(this.data);for(let i=0;i<7;i++){let s=st.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}let i=this.data.readByte(),s=new Uint8Array(5);this.data.read(s,0,s.length);for(let e=0;e<i;e++)t.barreFrets.push(s[e]);this.data.skip(26)}else{this.data.skip(25),t.name=rt.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=st.readInt32LE(this.data);for(let i=0;i<6;i++){let s=st.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}this.data.skip(36)}else{let i=this._versionNumber>=406?7:6;if(t.name=rt.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=st.readInt32LE(this.data),t.firstFret>0)for(let s=0;s<i;s++){let i=st.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}}t.name&&(e.chordId=i,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){let t=this.data.readByte(),i=0;if(this._versionNumber>=400&&(i=this.data.readByte()),e.fadeIn=0!=(16&t),(this._versionNumber<400&&0!=(1&t)||0!=(2&t))&&(e.vibrato=N.Slight),e.hasRasgueado=0!=(1&i),0!=(32&t)&&this._versionNumber>=400){switch(st.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(0!=(32&t)){switch(st.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(0!=(4&i)&&this.readTremoloBarEffect(e),0!=(64&t)){let t=0,i=0;this._versionNumber<500?(i=this.data.readByte(),t=this.data.readByte()):(t=this.data.readByte(),i=this.data.readByte()),t>0?(e.brushType=y.BrushUp,e.brushDuration=at.toStrokeValue(t)):i>0&&(e.brushType=y.BrushDown,e.brushDuration=at.toStrokeValue(i))}if(0!=(2&i))switch(st.readSInt8(this.data)){case 0:e.pickStroke=P.None;break;case 1:e.pickStroke=P.Up;break;case 2:e.pickStroke=P.Down}if(this._versionNumber<400){if(0!=(4&t))return B.Natural;if(0!=(8&t))return B.Artificial}return B.None}readTremoloBarEffect(e){this.data.readByte(),st.readInt32LE(this.data);let t=st.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new Pe(0,0);t.offset=st.readInt32LE(this.data),t.value=st.readInt32LE(this.data)/at.BendStep|0,rt.gpReadBool(this.data),e.addWhammyBarPoint(t)}}static toStrokeValue(e){switch(e){case 1:case 2:return 30;case 3:return 60;case 4:return 120;case 5:return 240;case 6:return 480;default:return 0}}readMixTableChange(e){let t=new nt;t.instrument=st.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=st.readSInt8(this.data),t.balance=st.readSInt8(this.data);let i=st.readSInt8(this.data),s=st.readSInt8(this.data),a=st.readSInt8(this.data),r=st.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=rt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=st.readInt32LE(this.data),t.volume>=0&&this.data.readByte(),t.balance>=0&&this.data.readByte(),i>=0&&this.data.readByte(),s>=0&&this.data.readByte(),a>=0&&this.data.readByte(),r>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=st.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(rt.gpReadStringIntByte(this.data,this.settings.importer.encoding),rt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let i=new ve;i.isLinear=!0,i.type=d.Volume,i.value=t.volume,e.automations.push(i)}if(t.balance>=0){let i=new ve;i.isLinear=!0,i.type=d.Balance,i.value=t.balance,e.automations.push(i)}if(t.instrument>=0){let i=new ve;i.isLinear=!0,i.type=d.Instrument,i.value=t.instrument,e.automations.push(i)}if(t.tempo>=0){let i=new ve;i.isLinear=!0,i.type=d.Tempo,i.value=t.tempo,e.automations.push(i),e.voice.bar.masterBar.tempoAutomation=i}}readNote(e,t,i,s,a){let r=new Ie;r.string=t.staff.tuning.length-a;let n=this.data.readByte();if(0!=(2&n)?r.accentuated=c.Heavy:0!=(64&n)&&(r.accentuated=c.Normal),r.isGhost=0!=(4&n),0!=(32&n)){let e=this.data.readByte();3===e?r.isDead=!0:2===e&&(r.isTieDestination=!0)}if(0!=(1&n)&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),0!=(16&n)){let e=st.readSInt8(this.data);r.dynamics=this.toDynamicValue(e),s.dynamics=r.dynamics}0!=(32&n)&&(r.fret=st.readSInt8(this.data)),0!=(128&n)&&(r.leftHandFinger=st.readSInt8(this.data),r.rightHandFinger=st.readSInt8(this.data),r.isFingering=!0);let o=!1;if(this._versionNumber>=500){0!=(1&n)&&(r.durationPercent=rt.gpReadDouble(this.data)),o=0!=(2&this.data.readByte())}if(s.addNote(r),0!=(8&n)&&this.readNoteEffects(e,i,s,r),t.staff.isPercussion&&(r.percussionArticulation=r.fret,r.string=-1,r.fret=-1),o){const e=je.defaultAccidentals[r.realValueWithoutHarmonic%12];"#"===e?r.accidentalMode=T.ForceFlat:"b"===e&&(r.accidentalMode=T.ForceSharp)}return r}toDynamicValue(e){switch(e){case 1:return w.PPP;case 2:return w.PP;case 3:return w.P;case 4:return w.MP;case 5:return w.MF;case 6:return w.F;case 7:return w.FF;case 8:return w.FFF;default:return w.F}}readNoteEffects(e,t,i,s){let a=this.data.readByte(),r=0;this._versionNumber>=400&&(r=this.data.readByte()),0!=(1&a)&&this.readBend(s),0!=(16&a)&&this.readGrace(t,s),0!=(4&r)&&this.readTremoloPicking(i),0!=(8&r)?this.readSlide(s):this._versionNumber<400&&0!=(4&a)&&(s.slideOutType=v.Shift),0!=(16&r)&&this.readArtificialHarmonic(s),0!=(32&r)&&this.readTrill(s),s.isLetRing=0!=(8&a),s.isHammerPullOrigin=0!=(2&a),0!=(64&r)&&(s.vibrato=N.Slight),s.isPalmMute=0!=(2&r),s.isStaccato=0!=(1&r)}readBend(e){this.data.readByte(),st.readInt32LE(this.data);let t=st.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new Pe(0,0);t.offset=st.readInt32LE(this.data),t.value=st.readInt32LE(this.data)/at.BendStep|0,rt.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let i=new He,s=new Ie;switch(s.string=t.string,s.fret=st.readSInt8(this.data),i.duration=S.ThirtySecond,i.dynamics=this.toDynamicValue(st.readSInt8(this.data)),st.readSInt8(this.data)){case 0:break;case 1:s.slideOutType=v.Legato,s.slideTarget=t;break;case 2:break;case 3:s.isHammerPullOrigin=!0}if(s.dynamics=i.dynamics,this.data.skip(1),this._versionNumber<500)i.graceType=_.BeforeBeat;else{let e=this.data.readByte();s.isDead=0!=(1&e),i.graceType=0!=(2&e)?_.OnBeat:_.BeforeBeat}e.addGraceBeat(i),i.addNote(s)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=S.Eighth;break;case 2:e.tremoloSpeed=S.Sixteenth;break;case 3:e.tremoloSpeed=S.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=st.readSInt8(this.data);0!=(1&t)?e.slideOutType=v.Shift:0!=(2&t)?e.slideOutType=v.Legato:0!=(4&t)?e.slideOutType=v.OutDown:0!=(8&t)&&(e.slideOutType=v.OutUp),0!=(16&t)?e.slideInType=k.IntoFromBelow:0!=(32&t)&&(e.slideInType=k.IntoFromAbove)}else{switch(st.readSInt8(this.data)){case 1:e.slideOutType=v.Shift;break;case 2:e.slideOutType=v.Legato;break;case 3:e.slideOutType=v.OutDown;break;case 4:e.slideOutType=v.OutUp;break;case-1:e.slideInType=k.IntoFromBelow;break;case-2:e.slideInType=k.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=B.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=B.Artificial;break;case 3:e.harmonicType=B.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=B.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=B.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=B.Natural;break;case 3:e.harmonicType=B.Tap;break;case 4:e.harmonicType=B.Pinch;break;case 5:e.harmonicType=B.Semi;break;case 15:case 17:case 22:e.harmonicType=B.Artificial}}deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=S.Sixteenth;break;case 2:e.trillSpeed=S.ThirtySecond;break;case 3:e.trillSpeed=S.SixtyFourth}}}at.VersionString="FICHIER GUITAR PRO ",at.BendStep=25;class rt{static gpReadDouble(e){let t=new Uint8Array(8);return e.read(t,0,t.length),new Float64Array(t.buffer)[0]}static gpReadFloat(e){let t=new Uint8Array(4);return t[3]=e.readByte(),t[2]=e.readByte(),t[2]=e.readByte(),t[1]=e.readByte(),new Float32Array(t.buffer)[0]}static gpReadColor(e,t=!1){let i=e.readByte(),s=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new me(i,s,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),rt.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return rt.gpReadString(e,st.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let i=st.readInt32LE(e)-1;return e.readByte(),rt.gpReadString(e,i,t)}static gpReadString(e,t,i){let s=new Uint8Array(t);return e.read(s,0,s.length),st.toString(s,i)}static gpWriteString(e,t){const i=st.stringToBytes(t);e.writeByte(t.length),e.write(i,0,i.length)}static gpReadStringByteLength(e,t,i){let s=e.readByte(),a=rt.gpReadString(e,s,i);return s<t&&e.skip(t-s),a}}class nt{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class ot{constructor(){this._capacity=0,this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return ot.withCapacity(0)}static withCapacity(e){let t=new ot;return t._buffer=new Uint8Array(e),t._capacity=e,t}static fromBuffer(e){let t=new ot;return t._buffer=e,t._capacity=t.length=e.length,t}static fromString(e){let t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return ot.fromBuffer(t)}reset(){this.position=0}skip(e){this.position+=e}setCapacity(e){if(e!==this._capacity){if(e>0){let t=new Uint8Array(e);this.length>0&&t.set(this._buffer.subarray(0,0+this.length),0),this._buffer=t}this._capacity=e}}readByte(){return this.length-this.position<=0?-1:this._buffer[this.position++]}read(e,t,i){let s=this.length-this.position;if(s>i&&(s=i),s<=0)return 0;if(s<=8){let i=s;for(;--i>=0;)e[t+i]=this._buffer[this.position+i]}else e.set(this._buffer.subarray(this.position,this.position+s),t);return this.position+=s,s}writeByte(e){let t=new Uint8Array(1);t[0]=e,this.write(t,0,1)}write(e,t,i){let s=this.position+i;if(s>this.length&&(s>this._capacity&&this.ensureCapacity(s),this.length=s),i<=8&&e!==this._buffer){let s=i;for(;--s>=0;)this._buffer[this.position+s]=e[t+s]}else{let s=Math.min(i,e.length-t);this._buffer.set(e.subarray(t,t+s),this.position)}this.position=s}ensureCapacity(e){if(e>this._capacity){let t=e;t<256&&(t=256),t<2*this._capacity&&(t=2*this._capacity),this.setCapacity(t)}}readAll(){return this.toArray()}toArray(){let e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}}class ht{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(G||(G={}));class lt{constructor(e){this.raw=new Map;let t=ot.fromBuffer(e),i=st.readInt32BE(t);for(let e=0;e<i;e++){let e=rt.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case G.Boolean:let i=1===t.readByte();this.addValue(e,i);break;case G.Integer:let s=st.readInt32BE(t);this.addValue(e,s);break;case G.Float:let a=rt.gpReadFloat(t);this.addValue(e,a);break;case G.String:let r=rt.gpReadString(t,st.readInt16BE(t),"utf-8");this.addValue(e,r);break;case G.Point:let n=st.readInt32BE(t),o=st.readInt32BE(t);this.addValue(e,new Pe(n,o));break;case G.Size:let h=st.readInt32BE(t),l=st.readInt32BE(t);this.addValue(e,new Pe(h,l));break;case G.Rectangle:let c=new ht;c.x=st.readInt32BE(t),c.y=st.readInt32BE(t),c.w=st.readInt32BE(t),c.h=st.readInt32BE(t),this.addValue(e,c);break;case G.Color:let d=rt.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,i]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=i}}addValue(e,t){this.raw.set(e,t)}static writeForScore(e){const t=ot.withCapacity(128);return st.writeInt32BE(t,1),lt.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,i){rt.gpWriteString(e,t),e.writeByte(G.Boolean),e.writeByte(i?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(V||(V={}));class ct{constructor(){this.type=V.Short,this.length=0}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(H||(H={}));class dt{constructor(){this.nodeType=H.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==H.Element&&e.nodeType!==H.CDATA||(this.firstElement=e)}getAttribute(e){return this.attributes.has(e)?this.attributes.get(e):""}getElementsByTagName(e,t=!1){let i=[];return this.searchElementsByTagName(this.childNodes,i,e,t),i}searchElementsByTagName(e,t,i,s=!1){for(let a of e)a&&a.nodeType===H.Element&&a.localName===i&&t.push(a),s&&this.searchElementsByTagName(a.childNodes,t,i,!0)}findChildElement(e){for(let t of this.childNodes)if(t&&t.nodeType===H.Element&&t.localName===e)return t;return null}addElement(e){const t=new dt;return t.nodeType=H.Element,t.localName=e,this.addChild(t),t}get innerText(){var e,t;if(this.nodeType===H.Element||this.nodeType===H.Document){if(this.firstElement&&this.firstElement.nodeType===H.CDATA)return this.firstElement.innerText;let t="";for(let i of this.childNodes)t+=null===(e=i.innerText)||void 0===e?void 0:e.toString();return t.trim()}return null!==(t=this.value)&&void 0!==t?t:""}set innerText(e){const t=new dt;t.nodeType=H.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new dt;t.nodeType=H.CDATA,t.value=null!=e?e:"",this.childNodes=[t]}}class ut extends ce{constructor(t,i,s){super(e.AlphaTabErrorType.Format,t),this.pos=0,this.xml=i,this.pos=s,Object.setPrototypeOf(this,ut.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"}(W||(W={}));class pt{static parse(e,t,i){var s;let a=e.charCodeAt(t),r=W.Begin,n=W.Begin,o=0,h="",l=W.Begin,c=null,d=null,u=0,p=0;for(;t<e.length;){switch(a=e.charCodeAt(t),r){case W.IgnoreSpaces:switch(a){case pt.CharCodeLF:case pt.CharCodeCR:case pt.CharCodeTab:case pt.CharCodeSpace:break;default:r=n;continue}break;case W.Begin:switch(a){case pt.CharCodeLowerThan:r=W.IgnoreSpaces,n=W.BeginNode;break;default:o=t,r=W.Pcdata;continue}break;case W.Pcdata:if(a===pt.CharCodeLowerThan){h+=e.substr(o,t-o);let s=new dt;s.nodeType=H.Text,s.value=h,h="",i.addChild(s),r=W.IgnoreSpaces,n=W.BeginNode}else a===pt.CharCodeAmp&&(h+=e.substr(o,t-o),r=W.Escape,l=W.Pcdata,o=t+1);break;case W.Cdata:if(a===pt.CharCodeBrackedClose&&e.charCodeAt(t+1)===pt.CharCodeBrackedClose&&e.charCodeAt(t+2)===pt.CharCodeGreaterThan){let s=new dt;s.nodeType=H.CDATA,s.value=e.substr(o,t-o),i.addChild(s),t+=2,r=W.Begin}break;case W.BeginNode:switch(a){case pt.CharCodeExclamation:if(e.charCodeAt(t+1)===pt.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ut("Expected <![CDATA[",e,t);t+=5,r=W.Cdata,o=t+1}else if(e.charCodeAt(t+1)===pt.CharCodeUpperD||e.charCodeAt(t+1)===pt.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ut("Expected <!DOCTYPE",e,t);t+=8,r=W.Doctype,o=t+1}else{if(e.charCodeAt(t+1)!==pt.CharCodeMinus||e.charCodeAt(t+2)!==pt.CharCodeMinus)throw new ut("Expected \x3c!--",e,t);t+=2,r=W.Comment,o=t+1}break;case pt.CharCodeQuestion:r=W.Header,o=t;break;case pt.CharCodeSlash:if(!i)throw new ut("Expected node name",e,t);o=t+1,r=W.IgnoreSpaces,n=W.Close;break;default:r=W.TagName,o=t;continue}break;case W.TagName:if(!pt.isValidChar(a)){if(t===o)throw new ut("Expected node name",e,t);c=new dt,c.nodeType=H.Element,c.localName=e.substr(o,t-o),i.addChild(c),r=W.IgnoreSpaces,n=W.Body;continue}break;case W.Body:switch(a){case pt.CharCodeSlash:r=W.WaitEnd;break;case pt.CharCodeGreaterThan:r=W.Childs;break;default:r=W.AttribName,o=t;continue}break;case W.AttribName:if(!pt.isValidChar(a)){if(o===t)throw new ut("Expected attribute name",e,t);if(d=e.substr(o,t-o),c.attributes.has(d))throw new ut(`Duplicate attribute [${d}]`,e,t);r=W.IgnoreSpaces,n=W.Equals;continue}break;case W.Equals:switch(a){case pt.CharCodeEquals:r=W.IgnoreSpaces,n=W.AttvalBegin;break;default:throw new ut("Expected =",e,t)}break;case W.AttvalBegin:switch(a){case pt.CharCodeDoubleQuote:case pt.CharCodeSingleQuote:h="",r=W.AttribVal,o=t+1,p=a}break;case W.AttribVal:switch(a){case pt.CharCodeAmp:h+=e.substr(o,t-o),r=W.Escape,l=W.AttribVal,o=t+1;break;default:if(a===p){h+=e.substr(o,t-o);let i=h;h="",c.attributes.set(d,i),r=W.IgnoreSpaces,n=W.Body}}break;case W.Childs:o=t=pt.parse(e,t,c),r=W.Begin;break;case W.WaitEnd:switch(a){case pt.CharCodeGreaterThan:r=W.Begin;break;default:throw new ut("Expected >",e,t)}break;case W.WaitEndRet:switch(a){case pt.CharCodeGreaterThan:return t;default:throw new ut("Expected >",e,t)}case W.Close:if(!pt.isValidChar(a)){if(o===t)throw new ut("Expected node name",e,t);if(e.substr(o,t-o)!==i.localName)throw new ut("Expected </"+i.localName+">",e,t);r=W.IgnoreSpaces,n=W.WaitEndRet;continue}break;case W.Comment:a===pt.CharCodeMinus&&e.charCodeAt(t+1)===pt.CharCodeMinus&&e.charCodeAt(t+2)===pt.CharCodeGreaterThan&&(t+=2,r=W.Begin);break;case W.Doctype:if(a===pt.CharCodeBrackedOpen)u++;else if(a===pt.CharCodeBrackedClose)u--;else if(a===pt.CharCodeGreaterThan&&0===u){let s=new dt;s.nodeType=H.DocumentType,s.value=e.substr(o,t-o),i.addChild(s),r=W.Begin}break;case W.Header:a===pt.CharCodeQuestion&&e.charCodeAt(t+1)===pt.CharCodeGreaterThan&&(t++,r=W.Begin);break;case W.Escape:if(a===pt.CharCodeSemi){let i=e.substr(o,t-o);if(i.charCodeAt(0)===pt.CharCodeSharp){let e=i.charCodeAt(1)===pt.CharCodeLowerX?parseInt("0"+i.substr(1,i.length-1)):parseInt(i.substr(1,i.length-1));h+=String.fromCharCode(e)}else pt.Escapes.has(i)?h+=pt.Escapes.get(i):h+=null===(s="&"+i+";")||void 0===s?void 0:s.toString();o=t+1,r=l}else pt.isValidChar(a)||a===pt.CharCodeSharp||(h+="&",h+=e.substr(o,t-o),o=--t+1,r=l)}t++}if(r===W.Begin&&(o=t,r=W.Pcdata),r===W.Pcdata){if(t!==o){h+=e.substr(o,t-o);let s=new dt;s.nodeType=H.Text,s.value=h,i.addChild(s)}return t}if(r===W.Escape&&l===W.Pcdata){h+="&",h+=e.substr(o,t-o);let s=new dt;return s.nodeType=H.Text,s.value=h,i.addChild(s),t}throw new ut("Unexpected end",e,t)}static isValidChar(e){return e>=pt.CharCodeLowerA&&e<=pt.CharCodeLowerZ||e>=pt.CharCodeUpperA&&e<=pt.CharCodeUpperZ||e>=pt.CharCode0&&e<=pt.CharCode9||e===pt.CharCodeColon||e===pt.CharCodeDot||e===pt.CharCodeUnderscore||e===pt.CharCodeMinus}}pt.CharCodeLF=10,pt.CharCodeTab=9,pt.CharCodeCR=13,pt.CharCodeSpace=32,pt.CharCodeLowerThan=60,pt.CharCodeAmp=38,pt.CharCodeBrackedClose=93,pt.CharCodeBrackedOpen=91,pt.CharCodeGreaterThan=62,pt.CharCodeExclamation=33,pt.CharCodeUpperD=68,pt.CharCodeLowerD=100,pt.CharCodeMinus=45,pt.CharCodeQuestion=63,pt.CharCodeSlash=47,pt.CharCodeEquals=61,pt.CharCodeDoubleQuote=34,pt.CharCodeSingleQuote=39,pt.CharCodeSharp=35,pt.CharCodeLowerX=120,pt.CharCodeLowerA=97,pt.CharCodeLowerZ=122,pt.CharCodeUpperA=65,pt.CharCodeUpperZ=90,pt.CharCode0=48,pt.CharCode9=57,pt.CharCodeColon=58,pt.CharCodeDot=46,pt.CharCodeUnderscore=95,pt.CharCodeSemi=59,pt.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class gt{constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}static write(e,t,i){const s=new gt(t,i);return s.writeNode(e),s.toString()}writeNode(e){switch(e.nodeType){case H.None:break;case H.Element:this._result.length>0&&this.writeLine(),this.write("<"+e.localName);for(const[t,i]of e.attributes)this.write(` ${t}="`),this.writeAttributeValue(i),this.write('"');if(0===e.childNodes.length)this.write("/>");else{if(this.write(">"),1!==e.childNodes.length||e.firstElement){this.indent();for(const t of e.childNodes)t.nodeType===H.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case H.Text:e.value&&this.write(e.value);break;case H.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case H.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case H.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const i=e.charAt(t);switch(i){case"<":this._result.push("&lt;");break;case">":this._result.push("&gt;");break;case"&":this._result.push("&amp;");break;case"'":this._result.push("&apos;");break;case'"':this._result.push("&quot;");break;default:this._result.push(i)}}}write(e){this._isStartOfLine&&this._result.push(this._currentIndention),this._result.push(e),this._isStartOfLine=!1}writeLine(e=null){e&&this.write(e),this._indention.length>0&&!this._isStartOfLine&&(this._result.push("\n"),this._isStartOfLine=!0)}toString(){return this._result.join("").trimRight()}}class ft extends dt{constructor(){super(),this.nodeType=H.Document}parse(e){pt.parse(e,0,this)}toString(e="",t=!1){return gt.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(U||(U={}));class mt{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=S.Quarter}}class yt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class bt{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;let i=new ft;try{i.parse(e)}catch(e){throw new ke("Could not parse XML",e)}if(this.parseDom(i),this.buildModel(),this.score.finish(t),!this._skipApplyLyrics&&this._lyricsByTrack.size>0)for(const[e,t]of this._lyricsByTrack){this._tracksById.get(e).applyLyrics(t)}}parseDom(e){let t=e.firstElement;if(t){if("GPIF"!==t.localName)throw new ke("Root node of XML was not GPIF");this.score=new qe;for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Score":this.parseScoreNode(e);break;case"MasterTrack":this.parseMasterTrackNode(e);break;case"Tracks":this.parseTracksNode(e);break;case"MasterBars":this.parseMasterBarsNode(e);break;case"Bars":this.parseBars(e);break;case"Voices":this.parseVoices(e);break;case"Beats":this.parseBeats(e);break;case"Notes":this.parseNotes(e);break;case"Rhythms":this.parseRhythms(e)}}}parseScoreNode(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Title":this.score.title=t.firstChild.innerText;break;case"SubTitle":this.score.subTitle=t.firstChild.innerText;break;case"Artist":this.score.artist=t.firstChild.innerText;break;case"Album":this.score.album=t.firstChild.innerText;break;case"Words":this.score.words=t.firstChild.innerText;break;case"Music":this.score.music=t.firstChild.innerText;break;case"WordsAndMusic":if(t.firstChild&&""!==t.firstChild.innerText){let e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,i){for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Automation":this.parseAutomation(s,t,i)}}parseAutomation(e,t,i){let s=null,a=!1,r=-1,n=0,o=0,h=null,l=0,c=null;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Type":s=t.innerText;break;case"Linear":a="true"===t.innerText.toLowerCase();break;case"Bar":r=parseInt(t.innerText);break;case"Position":n=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===H.CDATA)h=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(o=parseFloat(e[0]),l=1):(o=parseFloat(e[0]),l=parseInt(e[1]))}break;case"Text":c=t.innerText}if(!s)return;let d=null;switch(s){case"Tempo":d=ve.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&i&&i.has(h)&&(d=ve.buildInstrumentAutomation(a,n,i.get(h).program))}d&&(c&&(d.text=c),r>=0&&(t.has(r)||t.set(r,[]),t.get(r).push(d)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Track":this.parseTrack(t)}}parseTrack(e){this._articulationByName=new Map;let t=new $e;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Name":t.name=s.innerText;break;case"Color":let e=s.innerText.split(" ");if(e.length>=3){let i=parseInt(e[0]),s=parseInt(e[1]),a=parseInt(e[2]);t.color=new me(i,s,a,255)}break;case"Instrument":let a=s.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,s);break;case"NotationPatch":this.parseNotationPatch(t,s);break;case"ShortName":t.shortName=s.innerText;break;case"Lyrics":this.parseLyrics(i,s);break;case"Properties":this.parseTrackProperties(t,s);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,s);break;case"Sounds":this.parseSounds(i,t,s);break;case"PlaybackState":let r=s.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,s);break;case"Staves":this.parseStaves(t,s);break;case"Transpose":this.parseTranspose(t,s);break;case"RSE":this.parseRSE(t,s);break;case"Automations":this.parseTrackAutomations(i,s)}this._tracksById.set(i,t)}parseTrackAutomations(e,t){const i=new Map;this._automationsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,i,this._soundsByTrack.get(e))}parseNotationPatch(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"LineCount":const t=parseInt(i.innerText);for(let i of e.staves)i.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,i)}}parseInstrumentSet(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Type":switch(i.innerText){case"drumKit":for(let t of e.staves)t.isPercussion=!0}if("drumKit"===i.innerText)for(let t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,i);break;case"LineCount":const t=parseInt(i.innerText);for(let i of e.staves)i.standardNotationLineCount=t}}parseElements(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Element":this.parseElement(e,i)}}parseElement(e,t){const i=t.findChildElement("Type"),s=i?i.innerText:"";for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Name":case"Articulations":this.parseArticulations(e,i,s)}}parseArticulations(e,t,i){for(let s of t.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Articulation":this.parseArticulation(e,s,i)}}parseArticulation(e,t,i){const s=new Le;s.outputMidiNumber=-1,s.elementType=i;let a="";for(let e of t.childNodes)if(e.nodeType===H.Element){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(s.outputMidiNumber=parseInt(t));break;case"TechniqueSymbol":s.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":s.techniqueSymbolPlacement=F.Bottom;break;case"inside":s.techniqueSymbolPlacement=F.Middle;break;case"above":s.techniqueSymbolPlacement=F.Bottom;break;case"below":s.techniqueSymbolPlacement=F.Top}break;case"Noteheads":const i=t.split(" ");i.length>=1&&(s.noteHeadDefault=this.parseNoteHead(i[0])),i.length>=2&&(s.noteHeadHalf=this.parseNoteHead(i[1])),i.length>=3&&(s.noteHeadWhole=this.parseNoteHead(i[2])),s.noteHeadHalf==E.None&&(s.noteHeadHalf=s.noteHeadDefault),s.noteHeadWhole==E.None&&(s.noteHeadWhole=s.noteHeadDefault);break;case"StaffLine":t.length>0&&(s.staffLine=parseInt(t))}}-1!==s.outputMidiNumber?(e.percussionArticulations.push(s),a.length>0&&this._articulationByName.set(a,s)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=s.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return E.PictEdgeOfCymbal;case"articStaccatoAbove":return E.ArticStaccatoAbove;case"noteheadParenthesis":return E.NoteheadParenthesis;case"stringsUpBow":return E.StringsUpBow;case"stringsDownBow":return E.StringsDownBow;case"guitarGolpe":return E.GuitarGolpe;default:return E.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return E.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return E.NoteheadDoubleWhole;case"noteheadWhole":return E.NoteheadWhole;case"noteheadHalf":return E.NoteheadHalf;case"noteheadBlack":return E.NoteheadBlack;case"noteheadNull":return E.NoteheadNull;case"noteheadXOrnate":return E.NoteheadXOrnate;case"noteheadTriangleUpWhole":return E.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return E.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return E.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return E.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return E.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return E.NoteheadDiamondWhiteWide;case"noteheadCircleX":return E.NoteheadCircleX;case"noteheadXWhole":return E.NoteheadXWhole;case"noteheadXHalf":return E.NoteheadXHalf;case"noteheadXBlack":return E.NoteheadXBlack;case"noteheadParenthesis":return E.NoteheadParenthesis;case"noteheadSlashedBlack2":return E.NoteheadSlashedBlack2;case"noteheadCircleSlash":return E.NoteheadCircleSlash;case"noteheadHeavyX":return E.NoteheadHeavyX;case"noteheadHeavyXHat":return E.NoteheadHeavyXHat;default:return Fe.warning("GPIF","Unknown notehead symbol",e),E.None}}parseStaves(e,t){let i=0;for(let s of t.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Staff":e.ensureStaveCount(i+1);let t=e.staves[i];this.parseStaff(t,s),i++}}parseStaff(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Properties":this.parseStaffProperties(e,i)}}parseStaffProperties(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Property":this.parseStaffProperty(e,i)}}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Pitches":let s=t.findChildElement("Pitches").innerText.split(" "),a=new Array(s.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=parseInt(s[e]);e.stringTuning.tunings=a;break;case"Label":e.stringTuning.name=i.innerText}e.isPercussion||(e.showTablature=!0);break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForStaff(e,t);break;case"CapoFret":let i=parseInt(t.findChildElement("Fret").innerText);e.capo=i}}parseLyrics(e,t){let i=[];for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Line":i.push(this.parseLyricsLine(e))}this._lyricsByTrack.set(e,i)}parseLyricsLine(e){let t=new Ue;for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Offset":t.startBar=parseInt(i.innerText);break;case"Text":t.text=i.innerText}return t}parseDiagramCollectionForTrack(e,t){let i=t.findChildElement("Items");for(let t of i.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Item":this.parseDiagramItemForTrack(e,t)}}parseDiagramCollectionForStaff(e,t){let i=t.findChildElement("Items");for(let t of i.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Item":this.parseDiagramItemForStaff(e,t)}}parseDiagramItemForTrack(e,t){let i=new We,s=t.getAttribute("id");for(let t of e.staves)t.addChord(s,i);this.parseDiagramItemForChord(i,t)}parseDiagramItemForStaff(e,t){let i=new We,s=t.getAttribute("id");e.addChord(s,i),this.parseDiagramItemForChord(i,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");let s=t.findChildElement("Diagram"),a=parseInt(s.getAttribute("stringCount")),r=parseInt(s.getAttribute("baseFret"));e.firstFret=r+1;for(let t=0;t<a;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Fret":let s=parseInt(t.getAttribute("string"));e.strings[a-s-1]=r+parseInt(t.getAttribute("fret"));break;case"Fingering":let n=new Map;for(let s of t.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Position":let t=i.Unknown,a=r+parseInt(s.getAttribute("fret"));switch(s.getAttribute("finger")){case"Index":t=i.IndexFinger;break;case"Middle":t=i.MiddleFinger;break;case"Rank":t=i.AnnularFinger;break;case"Pinky":t=i.LittleFinger;break;case"Thumb":t=i.Thumb}t!==i.Unknown&&(n.has(t)?e.barreFrets.push(a):n.set(t,!0))}break;case"Property":switch(t.getAttribute("name")){case"ShowName":e.showName="true"===t.getAttribute("value");break;case"ShowDiagram":e.showDiagram="true"===t.getAttribute("value");break;case"ShowFingering":e.showFingering="true"===t.getAttribute("value")}}}parseTrackProperties(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Property":this.parseTrackProperty(e,i)}}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":let i=t.findChildElement("Pitches").innerText.split(" "),s=new Array(i.length);for(let e=0;e<s.length;e++)s[s.length-1-e]=parseInt(i[e]);for(let t of e.staves)t.stringTuning.tunings=s,t.showStandardNotation=!0,t.showTablature=!0;break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForTrack(e,t);break;case"CapoFret":let a=parseInt(t.findChildElement("Fret").innerText);for(let t of e.staves)t.capo=a}}parseGeneralMidi(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Program":e.playbackInfo.program=parseInt(i.innerText);break;case"Port":e.playbackInfo.port=parseInt(i.innerText);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=parseInt(i.innerText);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=parseInt(i.innerText)}if("Percussion"===t.getAttribute("table"))for(let t of e.staves)t.isPercussion=!0}parseSounds(e,t,i){for(let s of i.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Sound":this.parseSound(e,t,s)}}parseSound(e,t,i){const s=new yt;for(let e of i.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Name":s.name=e.innerText;break;case"Path":s.path=e.innerText;break;case"Role":s.role=e.innerText;break;case"MIDI":this.parseSoundMidi(s,e)}"Factory"!==s.role&&0!==t.playbackInfo.program||(t.playbackInfo.program=s.program),this._soundsByTrack.has(e)||this._soundsByTrack.set(e,new Map),this._soundsByTrack.get(e).set(s.uniqueId,s)}parseSoundMidi(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Program":e.program=parseInt(i.innerText)}}parsePartSounding(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"TranspositionPitch":for(let t of e.staves)t.displayTranspositionPitch=parseInt(i.innerText)}}parseTranspose(e,t){let i=0,s=0;for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Chromatic":s=parseInt(e.innerText);break;case"Octave":i=parseInt(e.innerText)}for(let t of e.staves)t.displayTranspositionPitch=12*i+s}parseRSE(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"ChannelStrip":this.parseChannelStrip(e,i)}}parseChannelStrip(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Parameters":this.parseChannelStripParameters(e,i)}}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){let i=t.firstChild.value.split(" ");i.length>=12&&(e.playbackInfo.balance=Math.floor(16*parseFloat(i[11])),e.playbackInfo.volume=Math.floor(16*parseFloat(i[12])))}}parseMasterBarsNode(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"MasterBar":this.parseMasterBar(t)}}parseMasterBar(e){let t=new ze;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Time":let e=i.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new Je,t.section.marker=i.findChildElement("Letter").innerText,t.section.text=i.findChildElement("Text").innerText;break;case"Repeat":"true"===i.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===i.getAttribute("end").toLowerCase()&&i.getAttribute("count")&&(t.repeatCount=parseInt(i.getAttribute("count")));break;case"AlternateEndings":let s=i.innerText.split(" "),a=0;for(let e=0;e<s.length;e++)a|=1<<-1+parseInt(s[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(i.innerText.split(" "));break;case"TripletFeel":switch(i.innerText){case"NoTripletFeel":t.tripletFeel=R.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=R.Triplet8th;break;case"Triplet16th":t.tripletFeel=R.Triplet16th;break;case"Dotted8th":t.tripletFeel=R.Dotted8th;break;case"Dotted16th":t.tripletFeel=R.Dotted16th;break;case"Scottish8th":t.tripletFeel=R.Scottish8th;break;case"Scottish16th":t.tripletFeel=R.Scottish16th}break;case"Key":t.keySignature=parseInt(i.findChildElement("AccidentalCount").innerText);let r=i.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=A.Major;break;case"minor":t.keySignatureType=A.Minor}break;case"Fermatas":this.parseFermatas(t,i)}this._masterBars.push(t)}parseFermatas(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Fermata":this.parseFermata(e,i)}}parseFermata(e,t){let i=0,s=new ct;for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":s.type=V.Short;break;case"Medium":s.type=V.Medium;break;case"Long":s.type=V.Long}break;case"Length":s.length=parseFloat(e.innerText);break;case"Offset":let t=e.innerText.split("/");if(2===t.length){i=parseInt(t[0])/parseInt(t[1])*xe.QuarterTime|0}}e.addFermata(i,s)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Bar":this.parseBar(t)}}parseBar(e){let t=new Ne,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Voices":this._voicesOfBar.set(i,s.innerText.split(" "));break;case"Clef":switch(s.innerText){case"Neutral":t.clef=u.Neutral;break;case"G2":t.clef=u.G2;break;case"F4":t.clef=u.F4;break;case"C4":t.clef=u.C4;break;case"C3":t.clef=u.C3}break;case"Ottavia":switch(s.innerText){case"8va":t.clefOttava=p._8va;break;case"15ma":t.clefOttava=p._15ma;break;case"8vb":t.clefOttava=p._8vb;break;case"15mb":t.clefOttava=p._15mb}break;case"SimileMark":switch(s.innerText){case"Simple":t.simileMark=g.Simple;break;case"FirstOfDouble":t.simileMark=g.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=g.SecondOfDouble}}this._barsById.set(i,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Voice":this.parseVoice(t)}}parseVoice(e){let t=new Ze,i=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Beats":this._beatsOfVoice.set(i,t.innerText.split(" "))}this._voiceById.set(i,t)}parseBeats(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Beat":this.parseBeat(t)}}parseBeat(e){let t=new He,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Notes":this._notesOfBeat.set(i,s.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(i,s.getAttribute("ref"));break;case"Fadding":"FadeIn"===s.innerText&&(t.fadeIn=!0);break;case"Tremolo":switch(s.innerText){case"1/2":t.tremoloSpeed=S.Eighth;break;case"1/4":t.tremoloSpeed=S.Sixteenth;break;case"1/8":t.tremoloSpeed=S.ThirtySecond}break;case"Chord":t.chordId=s.innerText;break;case"Hairpin":switch(s.innerText){case"Crescendo":t.crescendo=b.Crescendo;break;case"Decrescendo":t.crescendo=b.Decrescendo}break;case"Arpeggio":"Up"===s.innerText?t.brushType=y.ArpeggioUp:t.brushType=y.ArpeggioDown;break;case"Properties":this.parseBeatProperties(s,t);break;case"XProperties":this.parseBeatXProperties(s,t);break;case"FreeText":t.text=s.innerText;break;case"TransposedPitchStemOrientation":switch(s.innerText){case"Upward":t.preferredBeamDirection=U.Up;break;case"Downward":t.preferredBeamDirection=U.Down}break;case"Dynamic":switch(s.innerText){case"PPP":t.dynamics=w.PPP;break;case"PP":t.dynamics=w.PP;break;case"P":t.dynamics=w.P;break;case"MP":t.dynamics=w.MP;break;case"MF":t.dynamics=w.MF;break;case"F":t.dynamics=w.F;break;case"FF":t.dynamics=w.FF;break;case"FFF":t.dynamics=w.FFF}break;case"GraceNotes":switch(s.innerText){case"OnBeat":t.graceType=_.OnBeat;break;case"BeforeBeat":t.graceType=_.BeforeBeat}break;case"Legato":"true"===s.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new Pe(0,0);e.value=this.toBendValue(parseFloat(s.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(s.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new Pe(0,0);a.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new Pe(0,0);r.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let n=new Pe(0,0);n.value=this.toBendValue(parseFloat(s.getAttribute("destinationValue"))),n.offset=this.toBendOffset(parseFloat(s.getAttribute("destinationOffset"))),t.addWhammyBarPoint(n);break;case"Ottavia":switch(s.innerText){case"8va":t.ottava=p._8va;break;case"8vb":t.ottava=p._8vb;break;case"15ma":t.ottava=p._15ma;break;case"15mb":t.ottava=p._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(s),this._skipApplyLyrics=!0}this._beatById.set(i,t)}parseBeatLyrics(e){const t=[];for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Line":t.push(i.innerText)}return t}parseBeatXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"XProperty":let e=0;switch(i.getAttribute("id")){case"1124204545":e=parseInt(i.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(i.findChildElement("Int").innerText),t.brushDuration=e}}}parseBeatProperties(e,t){let i=!1,s=null,a=null,r=null,n=null,o=null;for(let h of e.childNodes)if(h.nodeType===H.Element)switch(h.localName){case"Property":switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=y.BrushUp:t.brushType=y.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=P.Up:t.pickStroke=P.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":i=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":s||(s=new Pe(0,0)),s.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":s||(s=new Pe(0,0)),s.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleValue":a=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset1":r=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset2":n=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationValue":o||(o=new Pe(Pe.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new Pe(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}i&&(s||(s=new Pe(0,0)),o||(o=new Pe(Pe.MaxPosition,0)),t.addWhammyBarPoint(s),r&&a&&t.addWhammyBarPoint(new Pe(r,a)),n&&a&&t.addWhammyBarPoint(new Pe(n,a)),r||n||!a||t.addWhammyBarPoint(new Pe(Pe.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Note":this.parseNote(t)}}parseNote(e){let t=new Ie,s=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===H.Element)switch(a.localName){case"Properties":this.parseNoteProperties(a,t,s);break;case"AntiAccent":"normal"===a.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(a.innerText),t.trillSpeed=S.Sixteenth;break;case"Accent":let e=parseInt(a.innerText);0!=(1&e)&&(t.isStaccato=!0),0!=(4&e)&&(t.accentuated=c.Heavy),0!=(8&e)&&(t.accentuated=c.Normal);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=N.Slight;break;case"Wide":t.vibrato=N.Wide}break;case"LeftFingering":switch(t.isFingering=!0,a.innerText){case"P":t.leftHandFinger=i.Thumb;break;case"I":t.leftHandFinger=i.IndexFinger;break;case"M":t.leftHandFinger=i.MiddleFinger;break;case"A":t.leftHandFinger=i.AnnularFinger;break;case"C":t.leftHandFinger=i.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,a.innerText){case"P":t.rightHandFinger=i.Thumb;break;case"I":t.rightHandFinger=i.IndexFinger;break;case"M":t.rightHandFinger=i.MiddleFinger;break;case"A":t.rightHandFinger=i.AnnularFinger;break;case"C":t.rightHandFinger=i.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(a.innerText)}this._noteById.set(s,t)}parseNoteProperties(e,t,i){let s=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(let d of e.childNodes)if(d.nodeType===H.Element)switch(d.localName){case"Property":switch(d.getAttribute("name")){case"String":t.string=parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(i,!0);break;case"HarmonicType":let e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=B.None;break;case"Natural":t.harmonicType=B.Natural;break;case"Artificial":t.harmonicType=B.Artificial;break;case"Pinch":t.harmonicType=B.Pinch;break;case"Tap":t.harmonicType=B.Tap;break;case"Semi":t.harmonicType=B.Semi;break;case"Feedback":t.harmonicType=B.Feedback}break;case"HarmonicFret":let u=d.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(d.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(d.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":s=!0;break;case"BendOriginValue":a||(a=new Pe(0,0)),a.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new Pe(0,0)),a.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new Pe(Pe.MaxPosition,0)),h.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new Pe(0,0)),h.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(d.findChildElement("Flags").innerText);0!=(1&p)?t.slideOutType=v.Shift:0!=(2&p)?t.slideOutType=v.Legato:0!=(4&p)?t.slideOutType=v.OutDown:0!=(8&p)&&(t.slideOutType=v.OutUp),0!=(16&p)?t.slideInType=k.IntoFromBelow:0!=(32&p)&&(t.slideInType=k.IntoFromAbove),0!=(64&p)?t.slideOutType=v.PickSlideDown:0!=(128&p)&&(t.slideOutType=v.PickSlideUp)}}s&&(a||(a=new Pe(0,0)),h||(h=new Pe(Pe.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new Pe(n,r)),o&&r&&t.addBendPoint(new Pe(o,r)),n||o||!r||t.addBendPoint(new Pe(Pe.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=Me.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const i=e.findChildElement("Pitch");if(i)for(let e of i.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Accidental":switch(e.innerText){case"x":t.accidentalMode=T.ForceDoubleSharp;break;case"#":t.accidentalMode=T.ForceSharp;break;case"b":t.accidentalMode=T.ForceFlat;break;case"bb":t.accidentalMode=T.ForceDoubleFlat}}}toBendValue(e){return e*bt.BendPointValueFactor|0}toBendOffset(e){return e*bt.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Rhythm":this.parseRhythm(t)}}parseRhythm(e){let t=new mt,i=e.getAttribute("id");t.id=i;for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"NoteValue":switch(i.innerText){case"Long":t.value=S.QuadrupleWhole;break;case"DoubleWhole":t.value=S.DoubleWhole;break;case"Whole":t.value=S.Whole;break;case"Half":t.value=S.Half;break;case"Quarter":t.value=S.Quarter;break;case"Eighth":t.value=S.Eighth;break;case"16th":t.value=S.Sixteenth;break;case"32nd":t.value=S.ThirtySecond;break;case"64th":t.value=S.SixtyFourth;break;case"128th":t.value=S.OneHundredTwentyEighth;break;case"256th":t.value=S.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(i.getAttribute("num")),t.tupletDenominator=parseInt(i.getAttribute("den"));break;case"AugmentationDot":t.dots=parseInt(i.getAttribute("count"))}this._rhythmById.set(i,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){let t=this._masterBars[e];this.score.addMasterBar(t)}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e);this.score.addTrack(t)}for(let e of this._barsOfMasterBar){let t=0;for(let i=0,s=0;i<e.length&&s<this.score.tracks.length;i++){let a=e[i];if(a!==bt.InvalidId){let e=this._barsById.get(a),i=this.score.tracks[s],r=i.staves[t];if(r.addBar(e),this._voicesOfBar.has(a))for(let t of this._voicesOfBar.get(a))if(t!==bt.InvalidId){let i=this._voiceById.get(t);if(e.addVoice(i),this._beatsOfVoice.has(t))for(let e of this._beatsOfVoice.get(t))if(e!==bt.InvalidId){let t=Ge.clone(this._beatById.get(e));i.addBeat(t);let s=this._rhythmOfBeat.get(e),a=this._rhythmById.get(s);if(t.duration=a.value,t.dots=a.dots,t.tupletNumerator=a.tupletNumerator,t.tupletDenominator=a.tupletDenominator,this._notesOfBeat.has(e))for(let i of this._notesOfBeat.get(e))if(i!==bt.InvalidId){const e=Re.clone(this._noteById.get(i));r.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(i)&&(t.tap=!0)}}}else{let t=new Ze;e.addVoice(t);let i=new He;i.isEmpty=!0,i.duration=S.Quarter,t.addBeat(i)}t===i.staves.length-1?(s++,t=0):t++}else s++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),i=!1;for(const e of t.staves)if(e.isPercussion){i=!0;break}if(i||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const i=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,s]of i)if(t.staves.length>0&&e<t.staves[0].bars.length){const i=t.staves[0].bars[e];if(i.voices.length>0&&i.voices[0].beats.length>0){const e=i.voices[0].beats[0];for(const t of s)e.automations.push(t)}}}}for(const[e,t]of this._masterTrackAutomations){let i=this.score.masterBars[e];for(let s=0,a=t.length;s<a;s++){let a=t[s];a.type===d.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),i.tempoAutomation=a)}}}}bt.InvalidId="-1",bt.BendPointPositionFactor=Pe.MaxPosition/100,bt.BendPointValueFactor=.04;class St{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class wt{constructor(){this.isMultiRest=!1,this.tracks=[]}}class _t{constructor(e){this.parts=[],this.zoomLevel=0,this.layout=0;let t=ot.fromBuffer(e),i=st.readInt32BE(t);for(let e=0;e<i;e++){let e=new wt;this.parts.push(e),e.isMultiRest=rt.gpReadBool(t);let i=st.readInt32BE(t);for(let s=0;s<i;s++){let i=t.readByte();0===i&&(i=1);let s=new St;s.showStandardNotation=0!=(1&i),s.showTablature=0!=(2&i),s.showSlash=0!=(4&i),e.tracks.push(s)}}}apply(e){let t=0,i=0;for(let s of this.parts)for(let a of s.tracks){if(i<e.tracks.length){let s=e.tracks[i];if(t<s.staves.length){let e=s.staves[t];e.showTablature=a.showTablature,e.showStandardNotation=a.showStandardNotation}}i++,i>=e.tracks.length&&(t++,i=0)}}static writeForScore(e){const t=ot.withCapacity(128),i=[new wt];for(const t of e.tracks)for(const e of t.staves){const t=new St;if(t.showStandardNotation=e.showStandardNotation,t.showTablature=e.showTablature,0===e.index)i[0].tracks.push(t);else{let e=new wt;e.tracks.push(t),i.push(e)}}st.writeInt32BE(t,i.length);for(const e of i){t.writeByte(e.isMultiRest?1:0),st.writeInt32BE(t,e.tracks.length);for(const i of e.tracks){let e=0;i.showStandardNotation&&(e|=1),i.showTablature&&(e|=2),i.showSlash&&(e|=4),t.writeByte(e)}}return t.toArray()}}class Bt{}class Tt extends Bt{constructor(e){super(),this.n=e}}class kt extends Bt{constructor(e,t){super(),this.left=e,this.right=t}}class vt extends Bt{constructor(e,t){super(),this.n=e,this.table=t}}class Nt{static make(e,t,i,s){let a=[],r=[];if(s>32)throw new de("Invalid huffman");for(let e=0;e<s;e++)a.push(0),r.push(0);for(let r=0;r<i;r++){let i=e[r+t];if(i>=s)throw new de("Invalid huffman");a[i]++}let n=0;for(let e=1;e<s-1;e++)n=n+a[e]<<1,r[e]=n;let o=new Map;for(let s=0;s<i;s++){let i=e[s+t];if(0!==i){let e=r[i-1];r[i-1]=e+1,o.set(e<<5|i,s)}}return Nt.treeCompress(new kt(Nt.treeMake(o,s,0,1),Nt.treeMake(o,s,1,1)))}static treeMake(e,t,i,s){if(s>t)throw new de("Invalid huffman");let a=i<<5|s;return e.has(a)?new Tt(e.get(a)):(i<<=1,s+=1,new kt(Nt.treeMake(e,t,i,s),Nt.treeMake(e,t,1|i,s)))}static treeCompress(e){let t=Nt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof kt)return new kt(Nt.treeCompress(e.left),Nt.treeCompress(e.right));throw new de("assert")}let i=1<<t,s=[];for(let e=0;e<i;e++)s.push(new Tt(-1));return Nt.treeWalk(s,0,0,t,e),new vt(t,s)}static treeWalk(e,t,i,s,a){a instanceof kt&&s>0?(Nt.treeWalk(e,t,i+1,s-1,a.left),Nt.treeWalk(e,t|1<<i,i+1,s-1,a.right)):e[t]=Nt.treeCompress(a)}static treeDepth(e){if(e instanceof Tt)return 0;if(e instanceof vt)throw new de("assert");if(e instanceof kt){let t=Nt.treeDepth(e.left),i=Nt.treeDepth(e.right);return 1+(t<i?t:i)}return 0}}!function(e){e[e.Head=0]="Head",e[e.Block=1]="Block",e[e.CData=2]="CData",e[e.Flat=3]="Flat",e[e.Crc=4]="Crc",e[e.Dist=5]="Dist",e[e.DistOne=6]="DistOne",e[e.Done=7]="Done"}(z||(z={}));class xt{constructor(){this.buffer=new Uint8Array(xt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(xt.BufferSize);this.pos-=xt.Size,e.set(this.buffer.subarray(xt.Size,xt.Size+this.pos),0),this.buffer=e}addBytes(e,t,i){this.pos+i>xt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+i),this.pos),this.pos+=i}addByte(e){this.pos===xt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}xt.Size=32768,xt.BufferSize=65536;class Pt{constructor(e){this._nbits=0,this._bits=0,this._state=z.Block,this._isFinal=!1,this._huffman=Pt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new xt,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Nt.make(e,0,288,10)}readBytes(e,t,i){if(this._needed=i,this._outpos=t,this._output=e,i>0)for(;this.inflateLoop(););return i-this._needed}inflateLoop(){switch(this._state){case z.Head:let e=this._input.readByte();if(8!==(15&e))throw new de("Invalid data");let t=this._input.readByte(),i=0!=(32&t);if(((e<<8)+t)%31!=0)throw new de("Invalid data");if(i)throw new de("Unsupported dictionary");return this._state=z.Block,!0;case z.Crc:return this._state=z.Done,!0;case z.Done:return!1;case z.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=st.readUInt16LE(this._input),st.readUInt16LE(this._input)!==65535-this._len)throw new de("Invalid data");this._state=z.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=Pt._fixedHuffman,this._huffdist=null,this._state=z.CData,!0;case 2:let t=this.getBits(5)+257,i=this.getBits(5)+1,s=this.getBits(4)+4;for(let e=0;e<s;e++)this._lengths[Pt.CodeLengthsPos[e]]=this.getBits(3);for(let e=s;e<19;e++)this._lengths[Pt.CodeLengthsPos[e]]=0;this._huffman=Nt.make(this._lengths,0,19,8);let a=[];for(let e=0;e<t+i;e++)a.push(0);return this.inflateLengths(a,t+i),this._huffdist=Nt.make(a,t,i,16),this._huffman=Nt.make(a,0,t,16),this._state=z.CData,!0;default:throw new de("Invalid data")}case z.Flat:{let e=this._len<this._needed?this._len:this._needed,t=st.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?z.Crc:z.Block),this._needed>0}case z.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=z.CData),this._needed>0}case z.Dist:for(;this._len>0&&this._needed>0;){let e=this._len<this._dist?this._len:this._dist,t=this._needed<e?this._needed:e;this.addDist(this._dist,t),this._len-=t}return 0===this._len&&(this._state=z.CData),this._needed>0;case z.CData:let s=this.applyHuffman(this._huffman);if(s<256)return this.addByte(s),this._needed>0;if(256===s)return this._state=this._isFinal?z.Crc:z.Block,!0;{s=s-257&255;let e=Pt.LenExtraBitsTbl[s];if(-1===e)throw new de("Invalid data");this._len=Pt.LenBaseValTbl[s]+this.getBits(e);let t=this._huffdist,i=t?this.applyHuffman(t):this.getRevBits(5);if(e=Pt.DistExtraBitsTbl[i],-1===e)throw new de("Invalid data");if(this._dist=Pt.DistBaseValTbl[i]+this.getBits(e),this._dist>this._window.available())throw new de("Invalid data");return this._state=1===this._dist?z.DistOne:z.Dist,!0}}return!1}addDistOne(e){let t=this._window.getLastChar();for(let i=0;i<e;i++)this.addByte(t)}addByte(e){this._window.addByte(e),this._output[this._outpos]=e,this._needed--,this._outpos++}addDist(e,t){this.addBytes(this._window.buffer,this._window.pos-e,t)}getBit(){0===this._nbits&&(this._nbits=8,this._bits=this._input.readByte());let e=1==(1&this._bits);return this._nbits--,this._bits=this._bits>>1,e}getBits(e){for(;this._nbits<e;)this._bits=this._bits|this._input.readByte()<<this._nbits,this._nbits+=8;let t=this._bits&(1<<e)-1;return this._nbits-=e,this._bits=this._bits>>e,t}getRevBits(e){return 0===e?0:this.getBit()?1<<e-1|this.getRevBits(e-1):this.getRevBits(e-1)}resetBits(){this._bits=0,this._nbits=0}addBytes(e,t,i){this._window.addBytes(e,t,i),this._output.set(e.subarray(t,t+i),this._outpos),this._needed-=i,this._outpos+=i}inflateLengths(e,t){let i=0,s=0;for(;i<t;){let a=this.applyHuffman(this._huffman);switch(a){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:s=a,e[i]=a,i++;break;case 16:let r=i+3+this.getBits(2);if(r>t)throw new de("Invalid data");for(;i<r;)e[i]=s,i++;break;case 17:if(i+=3+this.getBits(3),i>t)throw new de("Invalid data");break;case 18:if(i+=11+this.getBits(7),i>t)throw new de("Invalid data");break;default:throw new de("Invalid data")}}}applyHuffman(e){if(e instanceof Tt)return e.n;if(e instanceof kt)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof vt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new de("Invalid data")}}Pt.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],Pt.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],Pt.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],Pt.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],Pt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Pt._fixedHuffman=Pt.buildFixedHuffman();class Et{constructor(e,t){this.fullName=e;let i=e.lastIndexOf("/");this.fileName=-1===i||i===e.length-1?this.fullName:e.substr(i+1),this.data=t}}Et.OptionalDataDescriptorSignature=134695760,Et.CompressionMethodDeflate=8,Et.LocalFileHeaderSignature=67324752,Et.CentralFileHeaderSignature=33639248,Et.EndOfCentralDirSignature=101010256;class Ct{constructor(e){this._readable=e}read(){let e=[];for(;;){let t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){let e=this._readable;if(st.readInt32LE(e)!==Et.LocalFileHeaderSignature)return null;st.readUInt16LE(e);let t=st.readUInt16LE(e),i=st.readUInt16LE(e),s=0!==i;if(s&&i!==Et.CompressionMethodDeflate)return null;st.readInt16LE(this._readable),st.readInt16LE(this._readable),st.readInt32LE(e),st.readInt32LE(e);let a,r=st.readInt32LE(e),n=st.readInt16LE(e),o=st.readInt16LE(e),h=st.toString(st.readByteArray(e,n),"utf-8");if(e.skip(o),s){let e=ot.empty(),t=new Pt(this._readable),i=new Uint8Array(65536);for(;;){let s=t.readBytes(i,0,i.length);if(e.write(i,0,s),s<i.length)break}a=e.toArray()}else a=st.readByteArray(this._readable,r);if(0!=(8&t)){st.readInt32LE(this._readable)===Et.OptionalDataDescriptorSignature&&st.readInt32LE(this._readable),st.readInt32LE(this._readable),st.readInt32LE(this._readable)}return new Et(h,a)}}class Ft extends Te{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){Fe.debug(this.name,"Loading ZIP entries");let e,t=new Ct(this.data);try{e=t.read()}catch(e){throw new ke("No Zip archive",e)}Fe.debug(this.name,"Zip entries loaded");let i=null,s=null,a=null;for(let t of e)switch(t.fileName){case"score.gpif":i=st.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=t.data;break;case"PartConfiguration":a=t.data}if(!i)throw new ke("No score.gpif found in zip archive");Fe.debug(this.name,"Start Parsing score.gpif");let r=new bt;r.parseXml(i,this.settings),Fe.debug(this.name,"score.gpif parsed");let n=r.score;if(s){Fe.debug(this.name,"Start Parsing BinaryStylesheet"),new lt(s).apply(n),Fe.debug(this.name,"BinaryStylesheet parsed")}if(a){Fe.debug(this.name,"Start Parsing Part Configuration"),new _t(a).apply(n),Fe.debug(this.name,"Part Configuration parsed")}return n}}class Lt extends ce{constructor(){super(e.AlphaTabErrorType.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Lt.prototype)}}class Mt{constructor(e){this._currentByte=0,this._position=Mt.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=255&this.readByte();return t}readBits(e){let t=0,i=e-1;for(;i>=0;)t|=this.readBit()<<i,i--;return t}readBitsReversed(e){let t=0;for(let i=0;i<e;i++)t|=this.readBit()<<i;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new Lt;this._position=0}const e=this._currentByte>>Mt.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=ot.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof Lt))throw e}return e.toArray()}}Mt.ByteSize=8;class It{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Dt{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Mt(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let i,s=ot.empty(),a=this.getInteger(e.readBytes(4),0);try{for(;s.length<a;){if(1===e.readBits(1)){let t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=s.length-a,o=Math.min(a,r);i=s.getBuffer(),s.write(i,n,o)}else{let t=e.readBitsReversed(2);for(let i=0;i<t;i++)s.writeByte(e.readByte())}}}catch(e){if(!(e instanceof Lt))throw e}i=s.getBuffer();let r=t?4:0,n=s.length-r,o=new Uint8Array(n),h=n;return o.set(i.subarray(r,r+h),0),o}readBlock(e){let t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new ke("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){let t=4096,i=t;for(;i+3<e.length;){if(2===this.getInteger(e,i)){let s=new It;s.fileName=this.getString(e,i+4,127),s.fileSize=this.getInteger(e,i+140);let a=!this.fileFilter||this.fileFilter(s.fileName);a&&this.files.push(s);let r=i+148,n=0,o=0,h=a?ot.withCapacity(s.fileSize):null;for(;0!==(n=this.getInteger(e,r+4*o++));)i=n*t,a&&h.write(e,i,t);if(a){s.data=new Uint8Array(Math.min(s.fileSize,h.length));let e=h.toArray();s.data.set(e.subarray(0,0+s.data.length),0)}}i+=t}}getString(e,t,i){let s="";for(let a=0;a<i;a++){let i=255&e[t+a];if(0===i)break;s+=String.fromCharCode(i)}return s}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}Dt.HeaderBcFs="BCFS",Dt.HeaderBcFz="BCFZ",Dt.ScoreGpif="score.gpif",Dt.BinaryStylesheet="BinaryStylesheet",Dt.PartConfiguration="PartConfiguration";class At extends Te{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){Fe.debug(this.name,"Loading GPX filesystem");let e=new Dt;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),Fe.debug(this.name,"GPX filesystem loaded");let t=null,i=null,s=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=st.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=a.data;break;case"PartConfiguration":s=a.data}if(!t)throw new ke("No score.gpif found in GPX");Fe.debug(this.name,"Start Parsing score.gpif");let a=new bt;a.parseXml(t,this.settings),Fe.debug(this.name,"score.gpif parsed");let r=a.score;if(i){Fe.debug(this.name,"Start Parsing BinaryStylesheet"),new lt(i).apply(r),Fe.debug(this.name,"BinaryStylesheet parsed")}if(s){Fe.debug(this.name,"Start Parsing Part Configuration"),new _t(s).apply(r),Fe.debug(this.name,"Part Configuration parsed")}return r}}class Rt extends Te{constructor(){super(),this._currentPartGroup=null,this._trackFirstMeasureNumber=0,this._maxVoices=0,this._currentDirection=null,this._currentChord=null,this._divisionsPerQuarterNote=0,this._voiceOfStaff=new Map,this._isBeamContinue=!1,this._previousBeatWasPulled=!1,this._previousBeat=null}get name(){return"MusicXML"}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=st.toString(this.data.readAll(),this.settings.importer.encoding),t=new ft;try{t.parse(e)}catch(e){throw new ke("Unsupported format")}return this._score=new qe,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let i=1;i<e.length;i++){let s=e[i];for(let e of s.staves)t.addStaff(e);let a=this._score.tracks.indexOf(s);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new ke("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new ke("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"work":this.parseWork(t);break;case"movement-title":this._score.title=t.innerText;break;case"identification":this.parseIdentification(t);break;case"part-list":this.parsePartList(t);break;case"part":this.parsePart(t)}}parseWork(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"work-title":this._score.title=t.innerText}}parsePart(e){let t=e.getAttribute("id");if(!this._trackById.has(t)){if(1!==this._trackById.size)return;for(const[e,i]of this._trackById)0!==i.staves.length&&0!==i.staves[0].bars.length||(t=e);if(!this._trackById.has(t))return}let i=this._trackById.get(t),s=!0;this._maxVoices=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"measure":this.parseMeasure(t,i,s)&&(s=!1)}for(let e of i.staves)for(let t of e.bars)this.ensureVoices(t)}parseMeasure(e,t,i){if("yes"===e.getAttribute("implicit")&&0===e.getElementsByTagName("note",!1).length)return!1;let s=0;if(i)this._divisionsPerQuarterNote=0,this._trackFirstMeasureNumber=parseInt(e.getAttribute("number")),this._trackFirstMeasureNumber||(this._trackFirstMeasureNumber=0),s=0;else{if(s=parseInt(e.getAttribute("number")),!s)return!1;s-=this._trackFirstMeasureNumber}if(i){let i=e.getElementsByTagName("attributes",!1);if(i.length>0){let e=i[0].getElementsByTagName("staves",!1);if(e.length>0){let i=parseInt(e[0].innerText);t.ensureStaveCount(i)}}}let a=new Array(t.staves.length),r=null;for(let e=t.staves[0].bars.length;e<=s;e++)for(let e=0;e<t.staves.length;e++){let i=a[e]=new Ne;if(t.staves[e].bars.length>0){let s=t.staves[e].bars[t.staves[e].bars.length-1];i.clef=s.clef}r=this.getOrCreateMasterBar(s),t.staves[e].addBar(i),this.ensureVoices(i)}let n=!1;for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"note":this.parseNoteBeat(i,a);break;case"forward":this.parseForward(i,a);break;case"direction":this.parseDirection(i,r);break;case"attributes":n||(this.parseAttributes(i,a,r,t),n=!0);break;case"harmony":this.parseHarmony(i,t);break;case"sound":break;case"barline":this.parseBarline(i,r)}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new Ze;e.addVoice(t);let i=new He;i.isEmpty=!0,i.chordId=this._currentChord,t.addBeat(i)}}getOrCreateBeat(e,t,i){let s=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(s=parseInt(a[0].innerText)-1);let r=this._previousBeatWasPulled;this._previousBeatWasPulled=!1;let n,o,h=e.getElementsByTagName("staff",!1),l=1;if(h.length>0){l=parseInt(h[0].innerText),(this._isBeamContinue||r)&&this._previousBeat.voice.bar.staff.index!==l-1&&(l=this._previousBeat.voice.bar.staff.index+1,this._previousBeatWasPulled=!0);let e=t[0].staff.track.index+"-"+l;this._voiceOfStaff.has(e)||this._voiceOfStaff.set(e,s)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let c=this.getOrCreateVoice(n,s);return i&&c.beats.length>0||1===c.beats.length&&c.isEmpty?o=c.beats[c.beats.length-1]:(o=new He,o.isEmpty=!1,c.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let i=this.getOrCreateBeat(e,t,!1),s=parseInt(e.findChildElement("duration").innerText)*S.Quarter/this._divisionsPerQuarterNote,a=[S.SixtyFourth,S.ThirtySecond,S.Sixteenth,S.Eighth,S.Quarter,S.Half,S.Whole];for(let e of a)if(s>=e){i.duration=e,s-=e;break}i.isEmpty=!1}parseStaffDetails(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"staff-lines":for(let e of t.staves)e.stringTuning.tunings=new Array(parseInt(i.innerText)).fill(0);break;case"staff-tuning":this.parseStaffTuning(i,t)}for(let e of t.staves)this.isEmptyTuning(e.tuning)&&(e.stringTuning.tunings=[])}parseStaffTuning(e,t){let i=parseInt(e.getAttribute("line")),s="C",a="",r=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"tuning-step":s=t.innerText;break;case"tuning-alter":r=parseInt(t.innerText);break;case"tuning-octave":a=t.innerText}let n=fe.getTuningForText(s+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-i]=n}parseHarmony(e,t){let i=null,s="";for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"root":for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"root-step":i=e.innerText;break;case"root-alter":switch(parseInt(t.innerText)){case-2:s=" bb";break;case-1:s=" b";break;case 0:s="";break;case 1:s=" #";break;case 2:s=" ##"}}}let a=new We;a.name=i+s,this._currentChord=fe.newGuid();for(let e of t.staves)e.addChord(this._currentChord,a)}parseBarline(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"repeat":this.parseRepeat(i,t);break;case"ending":this.parseEnding(i,t)}}parseEnding(e,t){let i=parseInt(e.getAttribute("number"));i>0&&(--i,t.alternateEndings|=1<<i&255)}parseRepeat(e,t){let i=e.getAttribute("direction"),s=parseInt(e.getAttribute("times"));(s<0||isNaN(s))&&(s=2),"backward"===i?t.repeatCount=s:"forward"===i&&(t.isRepeatStart=!0)}parseNoteBeat(e,t){let i=e.getElementsByTagName("chord",!1).length>0,s=this.getOrCreateBeat(e,t,i);!s.chordId&&this._currentChord&&(s.chordId=this._currentChord,this._currentChord=null),this._currentDirection&&(s.text=this._currentDirection,this._currentDirection=null);let a=new Ie;s.voice.isEmpty=!1,s.isEmpty=!1,s.addNote(a),s.dots=0;let r=!1;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"grace":s.graceType=_.BeforeBeat,s.duration=S.ThirtySecond;break;case"duration":if(s.isRest&&!r){switch(parseInt(t.innerText)){case 1:s.duration=S.Whole;break;case 2:s.duration=S.Half;break;case 4:s.duration=S.Quarter;break;case 8:s.duration=S.Eighth;break;case 16:s.duration=S.Sixteenth;break;case 32:s.duration=S.ThirtySecond;break;case 64:s.duration=S.SixtyFourth;break;default:s.duration=S.Quarter}}break;case"tie":this.parseTied(t,a);break;case"cue":case"instrument":break;case"type":s.duration=this.getDuration(t.innerText),s.graceType!==_.None&&s.duration<S.Sixteenth&&(s.duration=S.Eighth);break;case"dot":s.dots++;break;case"accidental":this.parseAccidental(t,a);break;case"time-modification":this.parseTimeModification(t,s);break;case"stem":break;case"notehead":"yes"===t.getAttribute("parentheses")&&(a.isGhost=!0);break;case"beam":"continue"===t.innerText&&(this._isBeamContinue=!0);break;case"notations":this.parseNotations(t,s,a);break;case"lyric":this.parseLyric(t,s);break;case"pitch":this.parsePitch(t,a);break;case"unpitched":this.parseUnpitched(t,a);break;case"rest":r="yes"===t.getAttribute("measure"),s.isEmpty=!1,s.notes=[],s.duration=S.Whole}if(a.isStringed)for(let e=0;e<s.notes.length;e++)if(s.notes[e].string===a.string&&s.notes[e]!==a){s.removeNote(a);break}}getDuration(e){switch(e){case"256th":case"128th":case"64th":return S.SixtyFourth;case"32nd":return S.ThirtySecond;case"16th":return S.Sixteenth;case"eighth":return S.Eighth;case"quarter":return S.Quarter;case"half":return S.Half;case"long":case"breve":case"whole":return S.Whole}return S.Quarter}parseLyric(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"text":t.text?t.text+=" "+i.innerText:t.text=i.innerText}}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=T.ForceSharp;break;case"natural":t.accidentalMode=T.ForceNatural;break;case"flat":t.accidentalMode=T.ForceFlat}}parseTied(e,t){"start"===e.getAttribute("type")?this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t)):"stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination&&(t.isTieDestination=!0,t.tieOriginNoteId=this._tieStarts[0].id,this._tieStarts.splice(0,1),this._tieStartIds.delete(t.id))}parseNotations(e,t,i){for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"articulations":this.parseArticulations(s,i);break;case"tied":this.parseTied(s,i);break;case"slide":case"glissando":"start"===s.getAttribute("type")&&(i.slideOutType=v.Shift);break;case"dynamics":this.parseDynamics(s,t);break;case"technical":this.parseTechnical(s,i);break;case"ornaments":this.parseOrnaments(s,i);break;case"slur":let e=s.getAttribute("number");switch(e||(e="1"),s.getAttribute("type")){case"start":this._slurStarts.set(e,i);break;case"stop":if(this._slurStarts.has(e)){i.isSlurDestination=!0,this._slurStarts.get(e).slurDestinationNoteId=i.id,i.slurOriginNoteId=i.id}}}}parseOrnaments(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"tremolo":switch(parseInt(i.innerText)){case 1:t.beat.tremoloSpeed=S.Eighth;break;case 2:t.beat.tremoloSpeed=S.Sixteenth;break;case 3:t.beat.tremoloSpeed=S.ThirtySecond}}}parseTechnical(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"string":t.string=parseInt(i.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(i.innerText);break;case"down-bow":t.beat.pickStroke=P.Down;break;case"up-bow":t.beat.pickStroke=P.Up}-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseArticulations(e,t){for(let i of e.childNodes)switch(i.localName){case"accent":t.accentuated=c.Normal;break;case"strong-accent":t.accentuated=c.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"p":t.dynamics=w.P;break;case"pp":t.dynamics=w.PP;break;case"ppp":t.dynamics=w.PPP;break;case"f":t.dynamics=w.F;break;case"ff":t.dynamics=w.FF;break;case"fff":t.dynamics=w.FFF;break;case"mp":t.dynamics=w.MP;break;case"mf":t.dynamics=w.MF}}parseTimeModification(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"actual-notes":t.tupletNumerator=parseInt(i.innerText);break;case"normal-notes":t.tupletDenominator=parseInt(i.innerText)}}parseUnpitched(e,t){let i="",s=0,a=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"display-step":i=t.innerText;break;case"display-alter":s=parseInt(t.innerText);break;case"display-octave":a=parseInt(t.innerText)}let r=12*a+fe.getToneForText(i)+s;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let i="",s=0,a=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"step":i=t.innerText;break;case"alter":s=parseFloat(t.innerText),isNaN(s)&&(s=0);break;case"octave":a=parseInt(t.innerText)+1}let r=12*a+fe.getToneForText(i)+(0|s);t.octave=r/12|0,t.tone=r-12*t.octave}getOrCreateVoice(e,t){if(t<e.voices.length)return e.voices[t];for(let i=e.voices.length;i<=t;i++)e.addVoice(new Ze);return this._maxVoices=Math.max(this._maxVoices,e.voices.length),e.voices[t]}parseDirection(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"sound":let e=i.getAttribute("tempo");if(e){let i=new ve;i.isLinear=!0,i.type=d.Tempo,i.value=parseInt(e),t.tempoAutomation=i}break;case"direction-type":let s=i.firstElement;switch(s.localName){case"words":this._currentDirection=s.innerText;break;case"metronome":this.parseMetronome(s,t)}}}parseMetronome(e,t){let i=S.Quarter,s=120;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"beat-unit":i=this.getDuration(t.innerText);break;case"per-minute":s=parseInt(t.innerText)}let a=t.tempoAutomation=new ve;a.type=d.Tempo,a.value=s*(i/4|0)}parseAttributes(e,t,i,s){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===H.Element)switch(n.localName){case"divisions":this._divisionsPerQuarterNote=parseInt(n.innerText);break;case"key":this.parseKey(n,i);break;case"time":this.parseTime(n,i),r=!0;break;case"clef":a=parseInt(n.getAttribute("number")),isNaN(a)&&(a=1),this.parseClef(n,t[a-1]);break;case"staff-details":this.parseStaffDetails(n,s);break;case"transpose":this.parseTranspose(n,s)}r||(i.timeSignatureCommon=!0)}parseTranspose(e,t){let i=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"chromatic":i+=parseInt(t.innerText);break;case"octave-change":i+=12*parseInt(t.innerText)}for(let e of t.staves)e.transpositionPitch=i}parseClef(e,t){let i="s",s=0;for(let a of e.childNodes)if(a.nodeType===H.Element)switch(a.localName){case"sign":i=a.innerText.toLowerCase();break;case"line":s=parseInt(a.innerText);break;case"clef-octave-change":switch(parseInt(a.innerText)){case-2:t.clefOttava=p._15mb;break;case-1:t.clefOttava=p._8vb;break;case 1:t.clefOttava=p._8va;break;case 2:t.clefOttava=p._15mb}}switch(i){case"g":t.clef=u.G2;break;case"f":t.clef=u.F4;break;case"c":t.clef=3===s?u.C3:u.C4;break;case"percussion":t.clef=u.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=u.G2,t.staff.showTablature=!0;break;default:t.clef=u.G2}}parseTime(e,t){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let i=!1,s=!1;for(let a of e.childNodes)if(a.nodeType===H.Element){let e=a.innerText;switch(a.localName){case"beats":i||(-1===e.indexOf("+")?t.timeSignatureNumerator=parseInt(e):t.timeSignatureNumerator=4,i=!0);break;case"beat-type":s||(-1===e.indexOf("+")?t.timeSignatureDenominator=parseInt(e):t.timeSignatureDenominator=4,s=!0)}}}parseKey(e,t){let i=-2147483648,s="";for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"fifths":i=parseInt(t.innerText);break;case"key-step":case"key-alter":break;case"mode":s=t.innerText}t.keySignature=-7<=i&&i<=7?i:D.C,t.keySignatureType="minor"===s?A.Minor:A.Major}getOrCreateMasterBar(e){if(e<this._score.masterBars.length)return this._score.masterBars[e];for(let t=this._score.masterBars.length;t<=e;t++){let e=new ze;if(this._score.masterBars.length>0){let t=this._score.masterBars[this._score.masterBars.length-1];e.timeSignatureDenominator=t.timeSignatureDenominator,e.timeSignatureNumerator=t.timeSignatureNumerator,e.keySignature=t.keySignature,e.keySignatureType=t.keySignatureType}this._score.addMasterBar(e)}return this._score.masterBars[e]}parseIdentification(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"creator":"composer"===t.getAttribute("type")&&(this._score.music=t.innerText);break;case"rights":this._score.copyright&&(this._score.copyright+="\n"),this._score.copyright+=t.innerText}}parsePartList(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"part-group":this.parsePartGroup(t);break;case"score-part":this.parseScorePart(t)}}parsePartGroup(e){switch(e.getAttribute("type")){case"start":this._currentPartGroup=e.getAttribute("number"),this._partGroups.set(this._currentPartGroup,[]);break;case"stop":this._currentPartGroup=null}}parseScorePart(e){let t=e.getAttribute("id"),i=new $e;i.ensureStaveCount(1),i.staves[0].showStandardNotation=!0,this._trackById.set(t,i),this._score.addTrack(i),this._currentPartGroup&&this._partGroups.get(this._currentPartGroup).push(i);for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"part-name":i.name=t.innerText;break;case"part-abbreviation":i.shortName=t.innerText;break;case"midi-instrument":this.parseMidiInstrument(t,i)}this.isEmptyTuning(i.staves[0].tuning)&&(i.staves[0].stringTuning.tunings=[])}isEmptyTuning(e){if(!e)return!0;for(let t=0;t<e.length;t++)if(0!==e[t])return!1;return!0}parseMidiInstrument(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(i.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(i.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(i.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(i.innerText)+90)/180*16)))}}}!function(e){e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.NoteOff=128]="NoteOff",e[e.NoteOn=144]="NoteOn",e[e.NoteAftertouch=160]="NoteAftertouch",e[e.Controller=176]="Controller",e[e.ProgramChange=192]="ProgramChange",e[e.ChannelAftertouch=208]="ChannelAftertouch",e[e.PitchBend=224]="PitchBend",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(X||(X={}));class Ot{constructor(e,t,i,s,a){this.track=e,this.tick=t,this.message=i|s<<8|a<<16}get channel(){return 15&this.message}get command(){return 240&this.message}get data1(){return(65280&this.message)>>8}set data1(e){this.message&=-65281,this.message|=e<<8}get data2(){return(16711680&this.message)>>16}set data2(e){this.message&=-16711681,this.message|=e<<16}writeTo(e){let t=new Uint8Array([this.message>>24&255,this.message>>16&255,this.message>>8&255,255&this.message]);e.write(t,0,t.length)}}!function(e){e[e.SequenceNumber=0]="SequenceNumber",e[e.TextEvent=1]="TextEvent",e[e.CopyrightNotice=2]="CopyrightNotice",e[e.SequenceOrTrackName=3]="SequenceOrTrackName",e[e.InstrumentName=4]="InstrumentName",e[e.LyricText=5]="LyricText",e[e.MarkerText=6]="MarkerText",e[e.CuePoint=7]="CuePoint",e[e.PatchName=8]="PatchName",e[e.PortName=9]="PortName",e[e.MidiChannel=32]="MidiChannel",e[e.MidiPort=33]="MidiPort",e[e.EndOfTrack=47]="EndOfTrack",e[e.Tempo=81]="Tempo",e[e.SmpteOffset=84]="SmpteOffset",e[e.TimeSignature=88]="TimeSignature",e[e.KeySignature=89]="KeySignature",e[e.SequencerSpecific=127]="SequencerSpecific"}(Y||(Y={}));class Gt extends Ot{get channel(){return-1}get command(){return 255&this.message}get metaStatus(){return this.data1}constructor(e,t,i,s,a){super(e,t,i,s,a)}}!function(e){e[e.SystemExclusive=240]="SystemExclusive",e[e.MtcQuarterFrame=241]="MtcQuarterFrame",e[e.SongPosition=242]="SongPosition",e[e.SongSelect=243]="SongSelect",e[e.TuneRequest=246]="TuneRequest",e[e.SystemExclusive2=247]="SystemExclusive2"}(q||(q={}));class Vt extends Ot{get channel(){return-1}get command(){return 255&this.message}constructor(e,t,i,s,a){super(e,t,i,s,a)}}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(J||(J={}));class Ht extends Vt{constructor(e,t,i,s,a){super(e,t,i,255&s,s>>8&255),this.data=a}get isMetronome(){return this.manufacturerId==Ht.AlphaTabManufacturerId&&this.data[0]==J.MetronomeTick}get metronomeNumerator(){return this.isMetronome?this.data[1]:-1}get metronomeDurationInTicks(){return this.isMetronome?st.decodeUInt32LE(this.data,2):-1}get metronomeDurationInMilliseconds(){return this.isMetronome?st.decodeUInt32LE(this.data,6):-1}get isRest(){return this.manufacturerId==Ht.AlphaTabManufacturerId&&this.data[0]==J.Rest}get manufacturerId(){return this.message>>8}writeTo(e){e.writeByte(240);let t=this.data.length+2;e.writeByte(this.manufacturerId);let i=new Uint8Array([t>>24&255,t>>16&255,t>>8&255,255&t]);e.write(i,0,i.length),e.writeByte(247)}static encodeMetronome(e,t,i){const s=ot.withCapacity(10);return s.writeByte(J.MetronomeTick),s.writeByte(e),st.writeInt32LE(s,t),st.writeInt32LE(s,i),s.toArray()}}Ht.AlphaTabManufacturerId=125;class Wt{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event instanceof Ht&&this.event.isMetronome}static newMetronomeEvent(e,t,i,s,a){const r=new Ht(0,t,X.SystemExclusive2,Ht.AlphaTabManufacturerId,Ht.encodeMetronome(i,s,a));return new Wt(e,r)}}class Ut{}Ut.DefaultChannelCount=17,Ut.MetronomeChannel=Ut.DefaultChannelCount-1,Ut.AudioChannels=2,Ut.MinVolume=0,Ut.MinProgram=0,Ut.MaxProgram=127,Ut.MinPlaybackSpeed=.125,Ut.MaxPlaybackSpeed=8,Ut.MaxPitchWheel=16384,Ut.MaxPitchWheel20=4294967296,Ut.DefaultPitchWheel=Ut.MaxPitchWheel/2,Ut.MicroBufferCount=32,Ut.MicroBufferSize=64;class zt{constructor(e,t,i){this.bpm=e,this.ticks=t,this.time=i}}class Xt{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=0,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Yt{constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this._synthesizer=e,this._mainState=new Xt,this._currentState=this._mainState}get isPlayingOneTimeMidi(){return this._currentState==this._oneTimeState}get isPlayingCountIn(){return this._currentState==this._countInState}get playbackRange(){return this._currentState.playbackRange}set playbackRange(e){this._currentState.playbackRange=e,e&&(this._currentState.playbackRangeStartTime=this.tickPositionToTimePositionWithSpeed(e.startTick,1),this._currentState.playbackRangeEndTime=this.tickPositionToTimePositionWithSpeed(e.endTick,1))}get currentTime(){return this._currentState.currentTime}get endTick(){return this._currentState.endTick}get endTime(){return this._currentState.endTime/this.playbackSpeed}seek(e){if(e*=this.playbackSpeed,this.playbackRange&&(e<this._currentState.playbackRangeStartTime?e=this._currentState.playbackRangeStartTime:e>this._currentState.playbackRangeEndTime&&(e=this._currentState.playbackRangeEndTime)),e>this._currentState.currentTime)this.silentProcess(e-this._currentState.currentTime);else if(e<this._currentState.currentTime){this._currentState.currentTime=0,this._currentState.eventIndex=0;let t=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(t),this.silentProcess(e)}}silentProcess(e){if(e<=0)return;let t=Date.now(),i=this._currentState.currentTime+e;for(;this._currentState.currentTime<i;)this.fillMidiEventQueueLimited(i-this._currentState.currentTime)&&this._synthesizer.synthesizeSilent(Ut.MicroBufferSize);this._currentState.currentTime=i;let s=Date.now()-t;Fe.debug("Sequencer","Silent seek finished in "+s+"ms")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new Xt;t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let i=120,s=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(let d of e.events){let u=new Wt(t.synthData.length,d);t.synthData.push(u);let p=d.tick-c;if(s+=p,a+=p*(6e4/(i*e.division)),u.time=a,c=d.tick,n>0)for(;h<s;){let e=Wt.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.command===X.Meta&&d.data1===Y.Tempo){i=6e7/d.value,t.tempoChanges.push(new zt(i,s,a)),o=n*(6e4/(i*e.division))}else if(d.command===X.Meta&&d.data1===Y.TimeSignature){let s=d,a=Math.pow(2,s.data[1]);r=s.data[0],n=t.division*(4/a)|0,o=n*(6e4/(i*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=s.data[0],t.firstTimeSignatureDenominator=a)}else if(d.command===X.ProgramChange){let e=d.channel;t.firstProgramEventPerChannel.has(e)||t.firstProgramEventPerChannel.set(e,u)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=s,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Ut.MicroBufferSize/this._synthesizer.outSampleRate*1e3*this.playbackSpeed,i=this.internalEndTime;e>0&&(e<t&&(t=e),i=Math.min(this.internalEndTime,this._currentState.currentTime+e));let s=!1;for(this._currentState.currentTime+=t;this._currentState.eventIndex<this._currentState.synthData.length&&this._currentState.synthData[this._currentState.eventIndex].time<this._currentState.currentTime&&this._currentState.currentTime<i;)this._synthesizer.dispatchEvent(this._currentState.synthData[this._currentState.eventIndex]),this._currentState.eventIndex++,s=!0;return s}tickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(e,this.playbackSpeed)}timePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t){let i=0,s=120,a=0;for(const t of this._currentState.tempoChanges){if(e<t.ticks)break;i=t.time,s=t.bpm,a=t.ticks}return i+=(e-=a)*(6e4/(s*this._currentState.division)),i/t}timePositionToTickPositionWithSpeed(e,t){e*=t;let i=0,s=120,a=0;for(const t of this._currentState.tempoChanges){if(e<t.time)break;i=t.ticks,s=t.bpm,a=t.time}return i+=(e-=a)/(6e4/(s*this._currentState.division))|0,i+1}get internalEndTime(){return this.playbackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.playbackRange?this.playbackRange&&(this._currentState.currentTime=this.playbackRange.startTick,this._currentState.eventIndex=0):(this._currentState.currentTime=0,this._currentState.eventIndex=0)}resetOneTimeMidi(){this._oneTimeState=null,this._currentState=this._mainState}resetCountIn(){this._countInState=null,this._currentState=this._mainState}startCountIn(){this.generateCountInMidi(),this._currentState=this._countInState,this.stop(),this._synthesizer.noteOffAll(!0)}generateCountInMidi(){const e=new Xt;e.division=this._mainState.division;let t=120,i=4,s=4;0===this._mainState.eventIndex?(t=this._mainState.tempoChanges[0].bpm,i=this._mainState.firstTimeSignatureNumerator,s=this._mainState.firstTimeSignatureDenominator):(t=this._synthesizer.currentTempo,i=this._synthesizer.timeSignatureNumerator,s=this._synthesizer.timeSignatureDenominator),e.tempoChanges.push(new zt(t,0,0));let a=e.division*(4/s)|0,r=a*(6e4/(t*this._mainState.division)),n=0,o=0;for(let t=0;t<i;t++){let i=Wt.newMetronomeEvent(e.synthData.length,n,t,a,r);e.synthData.push(i),i.time=o,n+=a,o+=r}e.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),e.endTime=o,e.endTick=n,this._countInState=e}}!function(e){e[e.Paused=0]="Paused",e[e.Playing=1]="Playing"}(Q||(Q={}));class qt{constructor(e,t){this.state=e,this.stopped=t}}class Jt{constructor(e,t,i,s,a){this.currentTime=e,this.endTime=t,this.currentTick=i,this.endTick=s,this.isSeek=a}}class Qt{constructor(){this.id="",this.size=0}static load(e,t,i){if(e&&Qt.HeaderSize>e.size)return!1;if(i.position+Qt.HeaderSize>=i.length)return!1;if(t.id=st.read8BitStringLength(i,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=st.readUInt32LE(i),e&&Qt.HeaderSize+t.size>e.size)return!1;e&&(e.size-=Qt.HeaderSize+t.size);let s="RIFF"===t.id,a="LIST"===t.id;return(!s||!e)&&(!s&&!a||(t.id=st.read8BitStringLength(i,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}Qt.HeaderSize=8;class jt{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.fontSamples=new Float32Array(0)}load(e){const t=new Qt,i=new Qt;if(!Qt.load(null,t,e)||"sfbk"!==t.id)throw new de("Soundfont is not a valid Soundfont2 file");for(;Qt.load(t,i,e);){let t=new Qt;if("pdta"===i.id)for(;Qt.load(i,t,e);)switch(t.id){case"phdr":for(let i=0,s=t.size/si.SizeInFile|0;i<s;i++)this.phdrs.push(new si(e));break;case"pbag":for(let i=0,s=t.size/ti.SizeInFile|0;i<s;i++)this.pbags.push(new ti(e));break;case"pmod":for(let i=0,s=t.size/ai.SizeInFile|0;i<s;i++)this.pmods.push(new ai(e));break;case"pgen":for(let i=0,s=t.size/ii.SizeInFile|0;i<s;i++)this.pgens.push(new ii(e));break;case"inst":for(let i=0,s=t.size/ei.SizeInFile|0;i<s;i++)this.insts.push(new ei(e));break;case"ibag":for(let i=0,s=t.size/Kt.SizeInFile|0;i<s;i++)this.ibags.push(new Kt(e));break;case"imod":for(let i=0,s=t.size/$t.SizeInFile|0;i<s;i++)this.imods.push(new $t(e));break;case"igen":for(let i=0,s=t.size/Zt.SizeInFile|0;i<s;i++)this.igens.push(new Zt(e));break;case"shdr":for(let i=0,s=t.size/ri.SizeInFile|0;i<s;i++)this.sHdrs.push(new ri(e));break;default:e.position+=t.size}else if("sdta"===i.id)for(;Qt.load(i,t,e);)switch(t.id){case"smpl":this.fontSamples=jt.loadSamples(t,e);break;default:e.position+=t.size}else e.position+=i.size}}static loadSamples(e,t){let i=e.size/2|0;const s=new Float32Array(i);let a=0;const r=new Uint8Array(2048),n=new Int16Array(r.length/2|0);for(;i>0;){let e=Math.min(i,r.length/2|0);t.read(r,0,2*e);for(let t=0;t<e;t++)n[t]=r[2*t+1]<<8|r[2*t],s[a+t]=n[t]/32767;i-=e,a+=e}return s}}class Kt{constructor(e){this.instGenNdx=st.readUInt16LE(e),this.instModNdx=st.readUInt16LE(e)}}Kt.SizeInFile=4;class $t{constructor(e){this.modSrcOper=st.readUInt16LE(e),this.modDestOper=st.readUInt16LE(e),this.modAmount=st.readInt16LE(e),this.modAmtSrcOper=st.readUInt16LE(e),this.modTransOper=st.readUInt16LE(e)}}$t.SizeInFile=10;class Zt{constructor(e){this.genOper=st.readUInt16LE(e),this.genAmount=new ni(e)}}Zt.SizeInFile=4;class ei{constructor(e){this.instName=st.read8BitStringLength(e,20),this.instBagNdx=st.readUInt16LE(e)}}ei.SizeInFile=22;class ti{constructor(e){this.genNdx=st.readUInt16LE(e),this.modNdx=st.readUInt16LE(e)}}ti.SizeInFile=4;class ii{constructor(e){this.genOper=st.readUInt16LE(e),this.genAmount=new ni(e)}}ii.SizeInFile=4,ii.GenInstrument=41,ii.GenKeyRange=43,ii.GenVelRange=44,ii.GenSampleId=53;class si{constructor(e){this.presetName=st.read8BitStringLength(e,20),this.preset=st.readUInt16LE(e),this.bank=st.readUInt16LE(e),this.presetBagNdx=st.readUInt16LE(e),this.library=st.readUInt32LE(e),this.genre=st.readUInt32LE(e),this.morphology=st.readUInt32LE(e)}}si.SizeInFile=38;class ai{constructor(e){this.modSrcOper=st.readUInt16LE(e),this.modDestOper=st.readUInt16LE(e),this.modAmount=st.readUInt16LE(e),this.modAmtSrcOper=st.readUInt16LE(e),this.modTransOper=st.readUInt16LE(e)}}ai.SizeInFile=10;class ri{constructor(e){this.sampleName=st.read8BitStringLength(e,20),this.start=st.readUInt32LE(e),this.end=st.readUInt32LE(e),this.startLoop=st.readUInt32LE(e),this.endLoop=st.readUInt32LE(e),this.sampleRate=st.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=st.readSInt8(e),this.sampleLink=st.readUInt16LE(e),this.sampleType=st.readUInt16LE(e)}}ri.SizeInFile=46;class ni{constructor(e){this.wordAmount=st.readUInt16LE(e)}get shortAmount(){return it.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}}class oi{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 hi{constructor(){this.activeChannel=0,this.channelList=[]}setupVoice(e,t){const i=this.channelList[this.activeChannel],s=t.region.pan+i.panOffset;t.playingChannel=this.activeChannel,t.mixVolume=i.mixVolume,t.noteGainDb+=i.gainDb,t.updatePitchRatio(i,e.outSampleRate),s<=-.5?(t.panFactorLeft=1,t.panFactorRight=0):s>=.5?(t.panFactorLeft=0,t.panFactorRight=1):(t.panFactorLeft=Math.sqrt(.5-s),t.panFactorRight=Math.sqrt(.5+s))}}!function(e){e[e.None=0]="None",e[e.Continuous=1]="Continuous",e[e.Sustain=2]="Sustain"}(j||(j={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(K||(K={}));class li{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class ci{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}static clamp(e,t,i){return e<=t?t:e>=i?i:e}}class di{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:ci.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:ci.timecents2Secs(this.attack),this.release=this.release<-11950?0:ci.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:ci.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:ci.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?ci.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"}($||($={}));class ui{constructor(e){this.loopMode=j.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new di,this.modEnv=new di,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new di(e.ampEnv),this.modEnv=new di(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=0,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=this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=this.ampEnv.attack=this.ampEnv.hold=this.ampEnv.decay=this.ampEnv.release=-12e3,this.modEnv.delay=this.modEnv.attack=this.modEnv.hold=this.modEnv.decay=this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case $.StartAddrsOffset:this.offset+=it.int16ToUint32(t.shortAmount);break;case $.EndAddrsOffset:this.end+=it.int16ToUint32(t.shortAmount);break;case $.StartloopAddrsOffset:this.loopStart+=it.int16ToUint32(t.shortAmount);break;case $.EndloopAddrsOffset:this.loopEnd+=it.int16ToUint32(t.shortAmount);break;case $.StartAddrsCoarseOffset:this.offset+=32768*it.int16ToUint32(t.shortAmount);break;case $.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case $.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case $.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case $.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case $.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case $.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case $.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case $.EndAddrsCoarseOffset:this.end+=32768*it.int16ToUint32(t.shortAmount);break;case $.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case $.Pan:this.pan=t.shortAmount/1e3;break;case $.DelayModLFO:this.delayModLFO=t.shortAmount;break;case $.FreqModLFO:this.freqModLFO=t.shortAmount;break;case $.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case $.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case $.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case $.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case $.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case $.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case $.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case $.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case $.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case $.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case $.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case $.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case $.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case $.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case $.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case $.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case $.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case $.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case $.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case $.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case $.StartloopAddrsCoarseOffset:this.loopStart+=32768*it.int16ToUint32(t.shortAmount);break;case $.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case $.EndloopAddrsCoarseOffset:this.loopEnd+=32768*it.int16ToUint32(t.shortAmount);break;case $.CoarseTune:this.transpose+=t.shortAmount;break;case $.FineTune:this.tune+=t.shortAmount;break;case $.SampleModes:this.loopMode=3==(3&t.wordAmount)?j.Sustain:1==(3&t.wordAmount)?j.Continuous:j.None;break;case $.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case $.ExclusiveClass:this.group=t.wordAmount;break;case $.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}!function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(Z||(Z={}));class pi{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Z.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Z.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Z.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Z.Delay;break;case Z.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=Z.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Z.Attack;break;case Z.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Z.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Z.Hold;break;case Z.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Z.Decay,this.level=1,this.isAmpEnv){let e=-9.226/this.samplesUntilNextSegment;this.slope=Math.exp(e),this.segmentIsExponential=!0,this.parameters.sustain>0&&(this.samplesUntilNextSegment=Math.log(this.parameters.sustain)/e|0)}else this.slope=-1/this.samplesUntilNextSegment,this.samplesUntilNextSegment=this.parameters.decay*(1-this.parameters.sustain)*t|0,this.segmentIsExponential=!1;return}e=Z.Decay;break;case Z.Decay:return this.segment=Z.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Z.Sustain:if(this.segment=Z.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?pi.FastReleaseTime:this.parameters.release)*t|0,this.isAmpEnv){let e=-9.226/this.samplesUntilNextSegment;this.slope=Math.exp(e),this.segmentIsExponential=!0}else this.slope=-this.level/this.samplesUntilNextSegment,this.segmentIsExponential=!1;return;case Z.Release:default:return this.segment=Z.Done,this.segmentIsExponential=!1,this.level=this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,i,s,a){this.parameters=new di(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:ci.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:ci.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|i,this.isAmpEnv=s,this.nextSegment(Z.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)<=0&&this.nextSegment(this.segment,t)}}pi.FastReleaseTime=.01;class gi{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,i){this.samplesUntil=e*i|0,this.delta=4*ci.cents2Hertz(t)/i,this.level=0}process(e){this.samplesUntil>e?this.samplesUntil-=e:(this.level+=this.delta*e,this.level>1?(this.delta=-this.delta,this.level=2-this.level):this.level<-1&&(this.delta=-this.delta,this.level=-2-this.level))}}class fi{constructor(e){this.qInv=0,this.a0=0,this.a1=0,this.b1=0,this.b2=0,this.z1=0,this.z2=0,this.active=!1,e&&(this.qInv=e.qInv,this.a0=e.a0,this.a1=e.a1,this.b1=e.b1,this.b2=e.b2,this.z1=e.z1,this.z2=e.z2,this.active=e.active)}setup(e){let t=Math.tan(Math.PI*e),i=t*t,s=1/(1+t*this.qInv+i);this.a0=i*s,this.a1=2*this.a0,this.b1=2*(i-1)*s,this.b2=(1-t*this.qInv+i)*s}process(e){let t=e*this.a0+this.z1;return this.z1=e*this.a1+this.z2-this.b1*t,this.z2=e*this.a0-this.b2*t,t}}class mi{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 pi,this.modEnv=new pi,this.lowPass=new fi,this.modLfo=new gi,this.vibLfo=new gi,this.mixVolume=0,this.mute=!1}updatePitchRatio(e,t){let i=e.pitchWheel;e.perNotePitchWheel.has(this.playingKey)&&(i+=e.perNotePitchWheel.get(this.playingKey)-8192);const s=8192===i?e.tuning:i/16383*e.pitchRange*2-e.pitchRange+e.tuning;this.calcPitchRatio(s,t)}calcPitchRatio(e,t){if(!this.region)return;const i=this.playingKey+this.region.transpose+this.region.tune/100;let s=this.region.pitchKeyCenter+(i-this.region.pitchKeyCenter)*(this.region.pitchKeyTrack/100);0!==e&&(s+=e),this.pitchInputTimecents=100*s,this.pitchOutputFactor=this.region.sampleRate/(ci.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Z.Sustain,e),this.modEnv.nextSegment(Z.Sustain,e),this.region.loopMode===j.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Z.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Z.Sustain,e)}render(e,t,i,s,a){if(!this.region)return;let r=this.region;let n=e.presets[this.playingPreset].fontSamples,o=0,h=e.outputMode===K.StereoUnweaved?s:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,f=r.end,m=g+1,y=this.sourceSamplePosition,b=new fi(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,w=0,_=0,B=0,T=0,k=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,v=0,N=0,x=0,P=0,E=0!==r.modLfoToVolume,C=0,F=0;for(S?(w=e.outSampleRate,_=r.initialFilterFc,B=r.modLfoToFilterFc,T=r.modEnvToFilterFc):(w=0,_=0,B=0,T=0),k?(v=0,N=r.modLfoToPitch,x=r.vibLfoToPitch,P=r.modEnvToPitch):(v=ci.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,N=0,x=0,P=0),E?F=.1*r.modLfoToVolume:(C=ci.decibelsToGain(this.noteGainDb),F=0);s>0;){let r,L,M=0,I=s>mi.RenderEffectSampleBlock?mi.RenderEffectSampleBlock:s;if(s-=I,S){let e=_+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(ci.cents2Hertz(e)/w)}switch(k&&(v=ci.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*N+this.vibLfo.level*x+this.modEnv.level*P))*this.pitchOutputFactor),E&&(C=ci.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(I,e.outSampleRate),l&&this.modEnv.process(I,e.outSampleRate),c&&this.modLfo.process(I),d&&this.vibLfo.process(I),e.outputMode){case K.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[s]*a;b.active&&(r=b.process(r)),t[i+o]+=r*L,o++,t[i+o]+=r*M,o++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case K.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[s]*a;b.active&&(r=b.process(r)),t[i+o]+=r*L,o++,t[i+h]+=r*M,h++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case K.Mono:for(;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,h=n[e]*(1-a)+n[s]*a;b.active&&(h=b.process(h)),t[i+o]=h*r,o++,y+=v,y>=m&&u&&(y-=g-p+1)}}if(y>=f||this.ampEnv.segment===Z.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}mi.RenderEffectSampleBlock=Ut.MicroBufferSize;class yi{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0==this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}class bi{constructor(e){this._midiEventQueue=new yi,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=K.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,i){return this.fillWorkingBuffer(e,t,i)}synthesizeSilent(e){this.fillWorkingBuffer(null,0,e)}channelGetMixVolume(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].mixVolume:1}channelSetMixVolume(e,t){let i=this.channelInit(e);for(let i of this._voices)i.playingChannel===e&&-1!==i.playingPreset&&(i.mixVolume=t);i.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,i){const s=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){let e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Ut.MetronomeChannel,33),this.channelNoteOn(Ut.MetronomeChannel,33,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||s&&r!=Ut.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,i,n):a.kill()}return a}processMidiMessage(e){Fe.debug("Midi","Processing midi "+e.command);const t=e.command,i=e.channel,s=e.data1,a=e.data2;switch(t){case X.NoteOff:this.channelNoteOff(i,s);break;case X.NoteOn:this.channelNoteOn(i,s,a/127);break;case X.NoteAftertouch:break;case X.Controller:this.channelMidiControl(i,s,a);break;case X.ProgramChange:this.channelSetPresetNumber(i,s,9===i);break;case X.ChannelAftertouch:break;case X.PitchBend:this.channelSetPitchWheel(i,s|a<<7);break;case X.PerNotePitchBend:const t=e;let r=t.pitch;r=r*Ut.MaxPitchWheel/Ut.MaxPitchWheel20,this.channelSetPerNotePitchWheel(i,t.noteKey,r);break;case X.Meta:switch(e.data1){case Y.Tempo:this.currentTempo=6e7/e.value;break;case Y.TimeSignature:this.timeSignatureNumerator=e.data[0],this.timeSignatureDenominator=Math.pow(2,e.data[1])}}}get metronomeVolume(){return this.channelGetMixVolume(Ut.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Ut.MetronomeChannel,e),e>0&&(this.channelSetVolume(Ut.MetronomeChannel,1),this.channelSetPresetNumber(Ut.MetronomeChannel,0,!0))}get masterVolume(){return ci.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=ci.gainToDecibels(e);const i=t-this.globalGainDb;if(0!==i){for(const e of this._voices)-1!==e.playingPreset&&(e.noteGainDb+=i);this.globalGainDb=t}}resetSoft(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Z.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=e.bank=0,e.pitchWheel=e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){var e,t;return null!==(t=null===(e=this.presets)||void 0===e?void 0:e.length)&&void 0!==t?t:0}reset(){for(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Z.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);this._channels=null}setOutput(e,t,i){this.outputMode=e,this.outSampleRate=t>=1?t:44100,this.globalGainDb=i}noteOn(e,t,i){if(!this.presets)return;const s=127*i|0;if(e<0||e>=this.presets.length)return;if(i<=0)return void this.noteOff(e,t);const a=this._voicePlayIndex++;for(const r of this.presets[e].regions){if(t<r.loKey||t>r.hiKey||s<r.loVel||s>r.hiVel)continue;let n=null;if(0!==r.group)for(const t of this._voices)t.playingPreset===e&&t.region.group===r.group?t.endQuick(this.outSampleRate):-1!==t.playingPreset||n||(n=t);else for(let e of this._voices)-1===e.playingPreset&&(n=e);if(!n){for(let e=0;e<4;e++){const e=new mi;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-ci.gainToDecibels(1/i),this._channels?this._channels.setupVoice(this,n):(n.calcPitchRatio(0,this.outSampleRate),n.panFactorLeft=Math.sqrt(.5-r.pan),n.panFactorRight=Math.sqrt(.5+r.pan)),n.sourceSamplePosition=r.offset;const o=r.loopMode!==j.None&&r.loopStart<r.loopEnd;n.loopStart=o?r.loopStart:0,n.loopEnd=o?r.loopEnd:0,n.ampEnv.setup(r.ampEnv,t,s,!0,this.outSampleRate),n.modEnv.setup(r.modEnv,t,s,!1,this.outSampleRate);const h=r.initialFilterQ/10;n.lowPass.qInv=1/Math.pow(10,h/20),n.lowPass.z1=n.lowPass.z2=0,n.lowPass.active=r.initialFilterFc<=13500,n.lowPass.active&&n.lowPass.setup(ci.cents2Hertz(r.initialFilterFc)/this.outSampleRate),n.modLfo.setup(r.delayModLFO,r.freqModLFO,this.outSampleRate),n.vibLfo.setup(r.delayVibLFO,r.freqVibLFO,this.outSampleRate)}}bankNoteOn(e,t,i,s){let a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,i,s),!0)}noteOff(e,t){let i=null,s=null,a=[];for(let r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Z.Release||(!i||r.playIndex<i.playIndex?(i=r,s=r,a.push(r)):r.playIndex===i.playIndex&&(s=r,a.push(r)));if(i)for(const r of a)r!==i&&r!==s&&(r.playIndex!==i.playIndex||r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Z.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,i){const s=this.getPresetIndex(e,t);return-1!==s&&(this.noteOff(s,i),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&t.ampEnv.segment<Z.Release&&(e?t.endQuick(this.outSampleRate):t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new hi);for(let t=this._channels.channelList.length;t<=e;t++){let e=new oi;e.presetIndex=e.bank=0,e.pitchWheel=e.midiPan=8192,e.midiVolume=e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0,e.mixVolume=1,this._channels.channelList.push(e)}return this._channels.channelList[e]}getPresetIndex(e,t){if(!this.presets)return-1;for(let i=this.presets.length-1;i>=0;i--){let s=this.presets[i];if(s.presetNumber===t&&s.bank===e)return i}return-1}getPresetName(e){return this.presets?e<0||e>=this.presets.length?null:this.presets[e].name:null}bankGetPresetName(e,t){return this.getPresetName(this.getPresetIndex(e,t))}channelNoteOn(e,t,i){!this._channels||e>this._channels.channelList.length||(this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,i))}channelNoteOff(e,t){const i=[];let s=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Z.Release||(!s||r.playIndex<s.playIndex?(s=a=r,i.push(r)):r.playIndex===s.playIndex&&(a=r,i.push(r)));if(this.channelInit(e).perNotePitchWheel.delete(t),s)for(const r of i)r!==s&&r!==a&&(r.playIndex!==s.playIndex||-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Z.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<Z.Release&&t.end(this.outSampleRate)}channelSoundsOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(let t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&(t.ampEnv.segment<Z.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=it.int32ToUint16(t)}channelSetPresetNumber(e,t,i=!1){const s=this.channelInit(e);let a=0;return i?(a=this.getPresetIndex(128|32767&s.bank,t),-1===a&&(a=this.getPresetIndex(128,t)),-1===a&&(a=this.getPresetIndex(128,0)),-1===a&&(a=this.getPresetIndex(2047&s.bank,t))):a=this.getPresetIndex(2047&s.bank,t),s.presetIndex=a,-1!==a}channelSetBank(e,t){this.channelInit(e).bank=it.int32ToUint16(t)}channelSetBankPreset(e,t,i){const s=this.channelInit(e),a=this.getPresetIndex(t,i);return-1!==a&&(s.presetIndex=it.int32ToUint16(a),s.bank=it.int32ToUint16(t),!0)}channelSetPan(e,t){for(const i of this._voices)if(i.playingChannel===e&&-1!==i.playingPreset){let e=i.region.pan+t-.5;e<=-.5?(i.panFactorLeft=1,i.panFactorRight=0):e>=.5?(i.panFactorLeft=0,i.panFactorRight=1):(i.panFactorLeft=Math.sqrt(.5-e),i.panFactorRight=Math.sqrt(.5+e))}this.channelInit(e).panOffset=t-.5}channelSetVolume(e,t){const i=this.channelInit(e),s=ci.gainToDecibels(t),a=s-i.gainDb;if(0!==a){for(const t of this._voices)t.playingChannel===e&&-1!==t.playingPreset&&(t.noteGainDb+=a);i.gainDb=s}}channelSetPitchWheel(e,t){const i=this.channelInit(e);i.pitchWheel!==t&&(i.pitchWheel=it.int32ToUint16(t),this.channelApplyPitch(e,i))}channelSetPerNotePitchWheel(e,t,i){const s=this.channelInit(e);s.perNotePitchWheel.has(t)&&s.perNotePitchWheel.get(t)===i||(s.perNotePitchWheel.set(t,i),this.channelApplyPitch(e,s,t))}channelApplyPitch(e,t,i=-1){for(const s of this._voices)s.playingChannel!==e||-1===s.playingPreset||-1!=i&&s.playingKey!==i||s.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const i=this.channelInit(e);i.pitchRange!==t&&(i.pitchRange=t,8192!==i.pitchWheel&&this.channelApplyPitch(e,i))}channelSetTuning(e,t){const i=this.channelInit(e);i.tuning!==t&&(i.tuning=t,this.channelApplyPitch(e,i))}channelMidiControl(e,t,i){let s=this.channelInit(e);switch(t){case 5:case 96:case 97:case 64:case 65:case 66:case 122:case 124:case 125:case 126:case 127:return;case 38:return s.midiData=it.int32ToUint16(16256&s.midiData|i),void(0===s.midiRpn?this.channelSetPitchRange(e,(s.midiData>>7)+.01*(127&s.midiData)):1===s.midiRpn?this.channelSetTuning(e,(0|s.tuning)+(s.midiData-8192)/8192):2===s.midiRpn&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case 7:return s.midiVolume=it.int32ToUint16(127&s.midiVolume|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 39:return s.midiVolume=it.int32ToUint16(16256&s.midiVolume|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 11:return s.midiExpression=it.int32ToUint16(127&s.midiExpression|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 43:return s.midiExpression=it.int32ToUint16(16256&s.midiExpression|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 10:return s.midiPan=it.int32ToUint16(127&s.midiPan|i<<7),void this.channelSetPan(e,s.midiPan/16383);case 42:return s.midiPan=it.int32ToUint16(16256&s.midiPan|i),void this.channelSetPan(e,s.midiPan/16383);case 6:return s.midiData=it.int32ToUint16(127&s.midiData|i<<7),void(0===s.midiRpn?this.channelSetPitchRange(e,(s.midiData>>7)+.01*(127&s.midiData)):1===s.midiRpn?this.channelSetTuning(e,(0|s.tuning)+(s.midiData-8192)/8192):2===s.midiRpn&&6===t&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case 0:return void(s.bank=it.int32ToUint16(32768|i));case 32:return void(s.bank=it.int32ToUint16((0!=(32768&s.bank)?(127&s.bank)<<7:0)|i));case 101:return void(s.midiRpn=it.int32ToUint16(127&(65535===s.midiRpn?0:s.midiRpn)|i<<7));case 100:return void(s.midiRpn=it.int32ToUint16(16256&(65535===s.midiRpn?0:s.midiRpn)|i));case 98:case 99:return void(s.midiRpn=65535);case 120:return void this.channelSoundsOffAll(e);case 123:return void this.channelNoteOffAll(e);case 121:return s.midiVolume=s.midiExpression=16383,s.midiPan=8192,s.bank=0,this.channelSetVolume(e,1),this.channelSetPan(e,.5),void this.channelSetPitchRange(e,2)}}channelGetPresetIndex(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].presetIndex:0}channelGetPresetBank(e){return this._channels&&e<this._channels.channelList.length?32767&this._channels.channelList[e].bank:0}channelGetPan(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].panOffset-.5:.5}channelGetVolume(e){return this._channels&&e<this._channels.channelList.length?ci.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t){const i=new Array(e.phdrs.length-1);for(let t=0;t<e.phdrs.length-1;t++){const s=e.phdrs[t];let a=0;const r=i[t]=new li;r.name=s.presetName,r.bank=s.bank,r.presetNumber=s.preset,r.fontSamples=e.fontSamples;let n=0;for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){let t=0,s=127,a=0,r=127;for(let o=e.pbags[i].genNdx;o<e.pbags[i+1].genNdx;o++){let i=e.pgens[o];if(i.genOper!==ii.GenKeyRange)if(i.genOper!==ii.GenVelRange){if(i.genOper===ii.GenInstrument&&!(i.genAmount.wordAmount>=e.insts.length))for(let o=e.insts[i.genAmount.wordAmount].instBagNdx;o<e.insts[i.genAmount.wordAmount+1].instBagNdx;o++){let i=0,h=127,l=0,c=127;for(let d=e.ibags[o].instGenNdx;d<e.ibags[o+1].instGenNdx;d++){let o=e.igens[d];o.genOper!==ii.GenKeyRange?o.genOper!==ii.GenVelRange?53===o.genOper&&h>=t&&i<=s&&c>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,c=o.genAmount.highByteAmount):(i=o.genAmount.lowByteAmount,h=o.genAmount.highByteAmount)}}}else a=i.genAmount.lowByteAmount,r=i.genAmount.highByteAmount;else t=i.genAmount.lowByteAmount,s=i.genAmount.highByteAmount}}r.regions=new Array(n);let o=new ui;o.clear(!0);for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){const t=e.pbags[i],n=new ui(o);let h=!1;for(let s=t.genNdx;s<e.pbags[i+1].genNdx;s++){const t=e.pgens[s];if(t.genOper===ii.GenInstrument){let i=t.genAmount.wordAmount;if(i>=e.insts.length)continue;let s=new ui;s.clear(!1);let o=e.insts[i];for(let t=o.instBagNdx;t<e.insts[i+1].instBagNdx;t++){let i=e.ibags[t],h=new ui(s),l=!1;for(let s=i.instGenNdx;s<e.ibags[t+1].instGenNdx;s++){let t=e.igens[s];if(t.genOper===ii.GenSampleId){if(h.hiKey<n.loKey||h.loKey>n.hiKey)continue;if(h.hiVel<n.loVel||h.loVel>n.hiVel)continue;n.loKey>h.loKey&&(h.loKey=n.loKey),n.hiKey<h.hiKey&&(h.hiKey=n.hiKey),n.loVel>h.loVel&&(h.loVel=n.loVel),n.hiVel<h.hiVel&&(h.hiVel=n.hiVel),h.offset+=n.offset,h.end+=n.end,h.loopStart+=n.loopStart,h.loopEnd+=n.loopEnd,h.transpose+=n.transpose,h.tune+=n.tune,h.pitchKeyTrack+=n.pitchKeyTrack,h.attenuation+=n.attenuation,h.pan+=n.pan,h.ampEnv.delay+=n.ampEnv.delay,h.ampEnv.attack+=n.ampEnv.attack,h.ampEnv.hold+=n.ampEnv.hold,h.ampEnv.decay+=n.ampEnv.decay,h.ampEnv.sustain+=n.ampEnv.sustain,h.ampEnv.release+=n.ampEnv.release,h.modEnv.delay+=n.modEnv.delay,h.modEnv.attack+=n.modEnv.attack,h.modEnv.hold+=n.modEnv.hold,h.modEnv.decay+=n.modEnv.decay,h.modEnv.sustain+=n.modEnv.sustain,h.modEnv.release+=n.modEnv.release,h.initialFilterQ+=n.initialFilterQ,h.initialFilterFc+=n.initialFilterFc,h.modEnvToPitch+=n.modEnvToPitch,h.modEnvToFilterFc+=n.modEnvToFilterFc,h.delayModLFO+=n.delayModLFO,h.freqModLFO+=n.freqModLFO,h.modLfoToPitch+=n.modLfoToPitch,h.modLfoToFilterFc+=n.modLfoToFilterFc,h.modLfoToVolume+=n.modLfoToVolume,h.delayVibLFO+=n.delayVibLFO,h.freqVibLFO+=n.freqVibLFO,h.vibLfoToPitch+=n.vibLfoToPitch,h.ampEnv.envToSecs(!0),h.modEnv.envToSecs(!1),h.delayModLFO=h.delayModLFO<-11950?0:ci.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:ci.timecents2Secs(h.delayVibLFO),h.pan<-.5?h.pan=-.5:h.pan>.5&&(h.pan=.5),(h.initialFilterQ<1500||h.initialFilterQ>13500)&&(h.initialFilterQ=0);let i=e.sHdrs[t.genAmount.wordAmount];h.offset+=i.start,h.end+=i.end,h.loopStart+=i.startLoop,h.loopEnd+=i.endLoop,i.endLoop>0&&(h.loopEnd-=1),-1===h.pitchKeyCenter&&(h.pitchKeyCenter=i.originalPitch),h.tune+=i.pitchCorrection,h.sampleRate=i.sampleRate,0!==h.end&&h.end<r.fontSamples.length?h.end++:h.end=r.fontSamples.length,r.regions[a]=new ui(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}i!==e.ibags[o.instBagNdx]||l||(s=new ui(h))}h=!0}else n.operator(t.genOper,t.genAmount)}t!==e.pbags[s.presetBagNdx]||h||(o=n)}}if(t&&this.presets)for(const e of i)this.presets.push(e);else this.presets=i}}class 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 wi{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(e){this.events=e}}class Bi{constructor(e){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new yi,this._midiEventsPlayedFilter=new Set,this.isReady=!1,this.state=Q.Paused,this.ready=new Si,this.readyForPlayback=new Si,this.finished=new Si,this.soundFontLoaded=new Si,this.soundFontLoadFailed=new wi,this.midiLoaded=new wi,this.midiLoadFailed=new wi,this.stateChanged=new wi,this.positionChanged=new wi,this.midiEventsPlayed=new wi,Fe.debug("AlphaSynth","Initializing player"),this.state=Q.Paused,Fe.debug("AlphaSynth","Creating output"),this.output=e,this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{let e=new Float32Array(Ut.MicroBufferSize*Ut.MicroBufferCount*Ut.AudioChannels),t=0;for(let i=0;i<Ut.MicroBufferCount;i++){this._sequencer.fillMidiEventQueue();const i=this._synthesizer.synthesize(e,t,Ut.MicroBufferSize);t+=Ut.MicroBufferSize*Ut.AudioChannels;for(const e of i)this._midiEventsPlayedFilter.has(e.event.command)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this.output.addSamples(e)})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),Fe.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new bi(this.output.sampleRate),this._sequencer=new Yt(this._synthesizer),Fe.debug("AlphaSynth","Opening output"),this.output.open()}get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return Fe.logLevel}set logLevel(e){Fe.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Ut.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ut.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ut.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=ci.clamp(e,Ut.MinPlaybackSpeed,Ut.MaxPlaybackSpeed);let t=this._sequencer.playbackSpeed;this._sequencer.playbackSpeed=e,this.updateTimePosition(this._timePosition*(t/e),!0)}get tickPosition(){return this._tickPosition}set tickPosition(e){this.timePosition=this._sequencer.tickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){Fe.debug("AlphaSynth",`Seeking to position ${e}ms`),this._sequencer.seek(e),this.updateTimePosition(e,!0),this.output.resetSamples()}get playbackRange(){return this._sequencer.playbackRange}set playbackRange(e){this._sequencer.playbackRange=e,e&&(this.tickPosition=e.startTick)}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){Fe.debug("AlphaSynth","Destroying player"),this.stop()}play(){return!(this.state!==Q.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(Fe.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.tickPosition=0),this.output.play(),!0)}playInternal(){Fe.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=Q.Playing,this.stateChanged.trigger(new qt(this.state,!1))}pause(){this.state!==Q.Paused&&this._isMidiLoaded&&(Fe.debug("AlphaSynth","Pausing playback"),this.state=Q.Paused,this.stateChanged.trigger(new qt(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Q.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(Fe.debug("AlphaSynth","Stopping playback"),this.state=Q.Paused,this.output.pause(),this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.playbackRange?this._sequencer.playbackRange.startTick:0,this.stateChanged.trigger(new qt(this.state,!0)))}playOneTimeMidiFile(e){this.pause(),this._sequencer.loadOneTimeMidi(e),this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=0,this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let i=ot.fromBuffer(e);try{Fe.debug("AlphaSynth","Loading soundfont from bytes");let e=new jt;e.load(i),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),Fe.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){Fe.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){this.isReadyForPlayback&&(this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.readyForPlayback.trigger())}loadMidiFile(e){this.stop();try{Fe.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new Jt(0,this._sequencer.endTime,0,this._sequencer.endTick,!1)),Fe.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){Fe.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Ut.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){let t=e/this._synthesizer.outSampleRate*1e3;this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.endTick,this._tickPosition>=t&&(Fe.debug("AlphaSynth","Finished playback"),this._sequencer.isPlayingCountIn?(this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal()):this._sequencer.isPlayingOneTimeMidi?(this._sequencer.resetOneTimeMidi(),this.state=Q.Paused,this.output.pause(),this._synthesizer.noteOffAll(!1)):(this.finished.trigger(),this.isLooping?this.tickPosition=e:this.stop()))}updateTimePosition(e,t){const i=this._timePosition=e,s=this._tickPosition=this._sequencer.timePositionToTickPosition(i),a=this._sequencer.endTime,r=this._sequencer.endTick;if(this._sequencer.isPlayingOneTimeMidi||this._sequencer.isPlayingCountIn||(Fe.debug("AlphaSynth",`Position changed: (time: ${i}/${a}, tick: ${s}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount}`),this.positionChanged.trigger(new Jt(i,a,s,r,t))),t)this._playedEventsQueue.clear();else{const e=new yi;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<i;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new _i(e.toArray()))}}}class Ti{constructor(){this.division=xe.QuarterTime,this.events=[]}addEvent(e){if(0===this.events.length)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}toBinary(){let e=ot.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),t=new Uint8Array([0,0,0,6]),e.write(t,0,t.length),t=new Uint8Array([0,0]),e.write(t,0,t.length);let i=1;t=new Uint8Array([i>>8&255,255&i]),e.write(t,0,t.length),i=this.division,t=new Uint8Array([i>>8&255,255&i]),e.write(t,0,t.length);let s=ot.empty(),a=0;for(let e of this.events){let t=e.tick-a;Ti.writeVariableInt(s,t),e.writeTo(s),a=e.tick}t=new Uint8Array([77,84,114,107]),e.write(t,0,t.length);let r=s.toArray(),n=r.length;t=new Uint8Array([n>>24&255,n>>16&255,n>>8&255,255&n]),e.write(t,0,t.length),e.write(r,0,r.length)}static writeVariableInt(e,t){let i=new Uint8Array(4),s=0;do{i[s++]=127&t,t>>=7}while(t>0);for(;s>0;)s--,s>0?e.writeByte(128|i[s]):e.writeByte(i[s])}}class ki extends Gt{constructor(e,t,i,s,a){super(e,t,i,s,0),this.data=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus);let t=this.data.length;Ti.writeVariableInt(e,t),e.write(this.data,0,this.data.length)}}class vi extends Gt{constructor(e,t,i,s,a){super(e,t,i,s,0),this.value=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus),Ti.writeVariableInt(e,3);let t=new Uint8Array([this.value>>16&255,this.value>>8&255,255&this.value]);e.write(t,0,t.length)}}class Ni{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}(ee=e.ScrollMode||(e.ScrollMode={}))[ee.Off=0]="Off",ee[ee.Continuous=1]="Continuous",ee[ee.OffScreen=2]="OffScreen";class xi{constructor(){this.noteWideLength=480,this.noteWideAmplitude=2,this.noteSlightLength=480,this.noteSlightAmplitude=2,this.beatWideLength=240,this.beatWideAmplitude=3,this.beatSlightLength=240,this.beatSlightAmplitude=3}}class Pi{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}class Ei{constructor(){this.soundFont=null,this.scrollElement="html,body",this.enablePlayer=!1,this.enableCursor=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=e.ScrollMode.Continuous,this.scrollSpeed=300,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new xi,this.slide=new Pi,this.playTripletFeel=!0}}class Ci{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scriptFile",e.scriptFile),t.set("fontDirectory",e.fontDirectory),t.set("file",e.file),t.set("tex",e.tex),t.set("tracks",e.tracks),t.set("enableLazyLoading",e.enableLazyLoading),t.set("engine",e.engine),t.set("logLevel",e.logLevel),t.set("useWorkers",e.useWorkers),t.set("includeNoteBounds",e.includeNoteBounds),t}static setProperty(t,i,s){switch(i){case"scriptfile":return t.scriptFile=s,!0;case"fontdirectory":return t.fontDirectory=s,!0;case"file":return t.file=s,!0;case"tex":return t.tex=s,!0;case"tracks":return t.tracks=s,!0;case"enablelazyloading":return t.enableLazyLoading=s,!0;case"engine":return t.engine=s,!0;case"loglevel":return t.logLevel=ye.parseEnum(s,e.LogLevel),!0;case"useworkers":return t.useWorkers=s,!0;case"includenotebounds":return t.includeNoteBounds=s,!0}return!1}}class Fi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightFont",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("fretboardNumberFont",we.toJson(e.fretboardNumberFont)),t.set("tablatureFont",we.toJson(e.tablatureFont)),t.set("graceFont",we.toJson(e.graceFont)),t.set("staffLineColor",me.toJson(e.staffLineColor)),t.set("barSeparatorColor",me.toJson(e.barSeparatorColor)),t.set("barNumberFont",we.toJson(e.barNumberFont)),t.set("barNumberColor",me.toJson(e.barNumberColor)),t.set("fingeringFont",we.toJson(e.fingeringFont)),t.set("markerFont",we.toJson(e.markerFont)),t.set("mainGlyphColor",me.toJson(e.mainGlyphColor)),t.set("secondaryGlyphColor",me.toJson(e.secondaryGlyphColor)),t.set("scoreInfoColor",me.toJson(e.scoreInfoColor)),t}static setProperty(e,t,i){switch(t){case"copyrightfont":return e.copyrightFont=we.fromJson(i),!0;case"titlefont":return e.titleFont=we.fromJson(i),!0;case"subtitlefont":return e.subTitleFont=we.fromJson(i),!0;case"wordsfont":return e.wordsFont=we.fromJson(i),!0;case"effectfont":return e.effectFont=we.fromJson(i),!0;case"fretboardnumberfont":return e.fretboardNumberFont=we.fromJson(i),!0;case"tablaturefont":return e.tablatureFont=we.fromJson(i),!0;case"gracefont":return e.graceFont=we.fromJson(i),!0;case"stafflinecolor":return e.staffLineColor=me.fromJson(i),!0;case"barseparatorcolor":return e.barSeparatorColor=me.fromJson(i),!0;case"barnumberfont":return e.barNumberFont=we.fromJson(i),!0;case"barnumbercolor":return e.barNumberColor=me.fromJson(i),!0;case"fingeringfont":return e.fingeringFont=we.fromJson(i),!0;case"markerfont":return e.markerFont=we.fromJson(i),!0;case"mainglyphcolor":return e.mainGlyphColor=me.fromJson(i),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=me.fromJson(i),!0;case"scoreinfocolor":return e.scoreInfoColor=me.fromJson(i),!0}return!1}}class Li{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scale",e.scale),t.set("stretchForce",e.stretchForce),t.set("layoutMode",e.layoutMode),t.set("staveProfile",e.staveProfile),t.set("barsPerRow",e.barsPerRow),t.set("startBar",e.startBar),t.set("barCount",e.barCount),t.set("barCountPerPartial",e.barCountPerPartial),t.set("resources",Fi.toJson(e.resources)),t.set("padding",e.padding),t}static setProperty(t,i,s){switch(i){case"scale":return t.scale=s,!0;case"stretchforce":return t.stretchForce=s,!0;case"layoutmode":return t.layoutMode=ye.parseEnum(s,e.LayoutMode),!0;case"staveprofile":return t.staveProfile=ye.parseEnum(s,e.StaveProfile),!0;case"barsperrow":return t.barsPerRow=s,!0;case"startbar":return t.startBar=s,!0;case"barcount":return t.barCount=s,!0;case"barcountperpartial":return t.barCountPerPartial=s,!0;case"padding":return t.padding=s,!0}if(["resources"].indexOf(i)>=0)return Fi.fromJson(t.resources,s),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Fi.setProperty(t.resources,i.substring(e.length),s))return!0;return!1}}class Mi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notationMode",e.notationMode),t.set("fingeringMode",e.fingeringMode);{const i=new Map;t.set("elements",i);for(const[t,s]of e.elements)i.set(t.toString(),s)}return t.set("rhythmMode",e.rhythmMode),t.set("rhythmHeight",e.rhythmHeight),t.set("transpositionPitches",e.transpositionPitches),t.set("displayTranspositionPitches",e.displayTranspositionPitches),t.set("smallGraceTabNotes",e.smallGraceTabNotes),t.set("extendBendArrowsOnTiedNotes",e.extendBendArrowsOnTiedNotes),t.set("extendLineEffectsToBeatEnd",e.extendLineEffectsToBeatEnd),t.set("slurHeight",e.slurHeight),t}static setProperty(t,i,s){switch(i){case"notationmode":return t.notationMode=ye.parseEnum(s,e.NotationMode),!0;case"fingeringmode":return t.fingeringMode=ye.parseEnum(s,e.FingeringMode),!0;case"elements":return t.elements=new Map,ye.forEach(s,((e,i)=>{t.elements.set(ye.parseEnum(i,n),e)})),!0;case"rhythmmode":return t.rhythmMode=ye.parseEnum(s,e.TabRhythmMode),!0;case"rhythmheight":return t.rhythmHeight=s,!0;case"transpositionpitches":return t.transpositionPitches=s,!0;case"displaytranspositionpitches":return t.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return t.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return t.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return t.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return t.slurHeight=s,!0}return!1}}class Ii{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("encoding",e.encoding),t.set("mergePartGroupsInMusicXml",e.mergePartGroupsInMusicXml),t.set("beatTextAsLyrics",e.beatTextAsLyrics),t}static setProperty(e,t,i){switch(t){case"encoding":return e.encoding=i,!0;case"mergepartgroupsinmusicxml":return e.mergePartGroupsInMusicXml=i,!0;case"beattextaslyrics":return e.beatTextAsLyrics=i,!0}return!1}}class Di{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("noteWideLength",e.noteWideLength),t.set("noteWideAmplitude",e.noteWideAmplitude),t.set("noteSlightLength",e.noteSlightLength),t.set("noteSlightAmplitude",e.noteSlightAmplitude),t.set("beatWideLength",e.beatWideLength),t.set("beatWideAmplitude",e.beatWideAmplitude),t.set("beatSlightLength",e.beatSlightLength),t.set("beatSlightAmplitude",e.beatSlightAmplitude),t}static setProperty(e,t,i){switch(t){case"notewidelength":return e.noteWideLength=i,!0;case"notewideamplitude":return e.noteWideAmplitude=i,!0;case"noteslightlength":return e.noteSlightLength=i,!0;case"noteslightamplitude":return e.noteSlightAmplitude=i,!0;case"beatwidelength":return e.beatWideLength=i,!0;case"beatwideamplitude":return e.beatWideAmplitude=i,!0;case"beatslightlength":return e.beatSlightLength=i,!0;case"beatslightamplitude":return e.beatSlightAmplitude=i,!0}return!1}}class Ai{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("simpleSlidePitchOffset",e.simpleSlidePitchOffset),t.set("simpleSlideDurationRatio",e.simpleSlideDurationRatio),t.set("shiftSlideDurationRatio",e.shiftSlideDurationRatio),t}static setProperty(e,t,i){switch(t){case"simpleslidepitchoffset":return e.simpleSlidePitchOffset=i,!0;case"simpleslidedurationratio":return e.simpleSlideDurationRatio=i,!0;case"shiftslidedurationratio":return e.shiftSlideDurationRatio=i,!0}return!1}}class Ri{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("soundFont",e.soundFont),t.set("scrollElement",e.scrollElement),t.set("enablePlayer",e.enablePlayer),t.set("enableCursor",e.enableCursor),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("songBookBendDuration",e.songBookBendDuration),t.set("songBookDipDuration",e.songBookDipDuration),t.set("vibrato",Di.toJson(e.vibrato)),t.set("slide",Ai.toJson(e.slide)),t.set("playTripletFeel",e.playTripletFeel),t}static setProperty(t,i,s){switch(i){case"soundfont":return t.soundFont=s,!0;case"scrollelement":return t.scrollElement=s,!0;case"enableplayer":return t.enablePlayer=s,!0;case"enablecursor":return t.enableCursor=s,!0;case"enableuserinteraction":return t.enableUserInteraction=s,!0;case"scrolloffsetx":return t.scrollOffsetX=s,!0;case"scrolloffsety":return t.scrollOffsetY=s,!0;case"scrollmode":return t.scrollMode=ye.parseEnum(s,e.ScrollMode),!0;case"scrollspeed":return t.scrollSpeed=s,!0;case"songbookbendduration":return t.songBookBendDuration=s,!0;case"songbookdipduration":return t.songBookDipDuration=s,!0;case"playtripletfeel":return t.playTripletFeel=s,!0}if(["vibrato"].indexOf(i)>=0)return Di.fromJson(t.vibrato,s),!0;for(const e of["vibrato"])if(0===i.indexOf(e)&&Di.setProperty(t.vibrato,i.substring(e.length),s))return!0;if(["slide"].indexOf(i)>=0)return Ai.fromJson(t.slide,s),!0;for(const e of["slide"])if(0===i.indexOf(e)&&Ai.setProperty(t.slide,i.substring(e.length),s))return!0;return!1}}class Oi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",Ci.toJson(e.core)),t.set("display",Li.toJson(e.display)),t.set("notation",Mi.toJson(e.notation)),t.set("importer",Ii.toJson(e.importer)),t.set("player",Ri.toJson(e.player)),t}static setProperty(e,t,i){if(["core",""].indexOf(t)>=0)return Ci.fromJson(e.core,i),!0;for(const s of["core",""])if(0===t.indexOf(s)&&Ci.setProperty(e.core,t.substring(s.length),i))return!0;if(["display",""].indexOf(t)>=0)return Li.fromJson(e.display,i),!0;for(const s of["display",""])if(0===t.indexOf(s)&&Li.setProperty(e.display,t.substring(s.length),i))return!0;if(["notation"].indexOf(t)>=0)return Mi.fromJson(e.notation,i),!0;for(const s of["notation"])if(0===t.indexOf(s)&&Mi.setProperty(e.notation,t.substring(s.length),i))return!0;if(["importer"].indexOf(t)>=0)return Ii.fromJson(e.importer,i),!0;for(const s of["importer"])if(0===t.indexOf(s)&&Ii.setProperty(e.importer,t.substring(s.length),i))return!0;if(["player"].indexOf(t)>=0)return Ri.fromJson(e.player,i),!0;for(const s of["player"])if(0===t.indexOf(s)&&Ri.setProperty(e.player,t.substring(s.length),i))return!0;return!1}}class Gi{constructor(){this.core=new io,this.display=new Be,this.notation=new pe,this.importer=new Ni,this.player=new Ei}setSongBookModeSettings(){this.notation.notationMode=e.NotationMode.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=e.FingeringMode.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(n.ParenthesisOnTiedBends,!1),this.notation.elements.set(n.TabNotesOnTiedBends,!1),this.notation.elements.set(n.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Gi;return e.setSongBookModeSettings(),e}fillFromJson(e){Oi.fromJson(this,e)}}class Vi extends Ot{constructor(e,t,i,s,a){super(e,t,i,0,0),this.noteKey=s,this.pitch=a}writeTo(e){let t=new Uint8Array([64,255&this.message,255&this.noteKey,0,this.pitch>>24&255,this.pitch>>16&255,this.pitch>>8&255,255&this.pitch]);e.write(t,0,t.length)}}class Hi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("marker",e.marker),t.set("text",e.text),t}static setProperty(e,t,i){switch(t){case"marker":return e.marker=i,!0;case"text":return e.text=i,!0}return!1}}class Wi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("isLinear",e.isLinear),t.set("type",e.type),t.set("value",e.value),t.set("ratioPosition",e.ratioPosition),t.set("text",e.text),t}static setProperty(e,t,i){switch(t){case"islinear":return e.isLinear=i,!0;case"type":return e.type=ye.parseEnum(i,d),!0;case"value":return e.value=i,!0;case"ratioposition":return e.ratioPosition=i,!0;case"text":return e.text=i,!0}return!1}}class Ui{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("type",e.type),t.set("length",e.length),t}static setProperty(e,t,i){switch(t){case"type":return e.type=ye.parseEnum(i,V),!0;case"length":return e.length=i,!0}return!1}}class zi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("alternateEndings",e.alternateEndings),t.set("keySignature",e.keySignature),t.set("keySignatureType",e.keySignatureType),t.set("isDoubleBar",e.isDoubleBar),t.set("isRepeatStart",e.isRepeatStart),t.set("repeatCount",e.repeatCount),t.set("timeSignatureNumerator",e.timeSignatureNumerator),t.set("timeSignatureDenominator",e.timeSignatureDenominator),t.set("timeSignatureCommon",e.timeSignatureCommon),t.set("tripletFeel",e.tripletFeel),t.set("section",Hi.toJson(e.section)),t.set("tempoAutomation",Wi.toJson(e.tempoAutomation));{const i=new Map;t.set("fermata",i);for(const[t,s]of e.fermata)i.set(t.toString(),Ui.toJson(s))}return t.set("start",e.start),t.set("isAnacrusis",e.isAnacrusis),t}static setProperty(e,t,i){switch(t){case"alternateendings":return e.alternateEndings=i,!0;case"keysignature":return e.keySignature=ye.parseEnum(i,D),!0;case"keysignaturetype":return e.keySignatureType=ye.parseEnum(i,A),!0;case"isdoublebar":return e.isDoubleBar=i,!0;case"isrepeatstart":return e.isRepeatStart=i,!0;case"repeatcount":return e.repeatCount=i,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=i,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=i,!0;case"timesignaturecommon":return e.timeSignatureCommon=i,!0;case"tripletfeel":return e.tripletFeel=ye.parseEnum(i,R),!0;case"fermata":return e.fermata=new Map,ye.forEach(i,((t,i)=>{const s=new ct;Ui.fromJson(s,t),e.fermata.set(parseInt(i),s)})),!0;case"start":return e.start=i,!0;case"isanacrusis":return e.isAnacrusis=i,!0}return["section"].indexOf(t)>=0?(i?(e.section=new Je,Hi.fromJson(e.section,i)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(i?(e.tempoAutomation=new ve,Wi.fromJson(e.tempoAutomation,i)):e.tempoAutomation=null,!0)}}class Xi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("offset",e.offset),t.set("value",e.value),t}static setProperty(e,t,i){switch(t){case"offset":return e.offset=i,!0;case"value":return e.value=i,!0}return!1}}class Yi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),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),t.set("bendPoints",e.bendPoints.map((e=>Xi.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionArticulation",e.percussionArticulation),t.set("isVisible",e.isVisible),t.set("isLeftHandTapped",e.isLeftHandTapped),t.set("isHammerPullOrigin",e.isHammerPullOrigin),t.set("hammerPullOriginNoteId",e.hammerPullOriginNoteId),t.set("hammerPullDestinationNoteId",e.hammerPullDestinationNoteId),t.set("isSlurDestination",e.isSlurDestination),t.set("slurOriginNoteId",e.slurOriginNoteId),t.set("slurDestinationNoteId",e.slurDestinationNoteId),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("tieOriginNoteId",e.tieOriginNoteId),t.set("tieDestinationNoteId",e.tieDestinationNoteId),t.set("isTieDestination",e.isTieDestination),t.set("leftHandFinger",e.leftHandFinger),t.set("rightHandFinger",e.rightHandFinger),t.set("isFingering",e.isFingering),t.set("trillValue",e.trillValue),t.set("trillSpeed",e.trillSpeed),t.set("durationPercent",e.durationPercent),t.set("accidentalMode",e.accidentalMode),t.set("dynamics",e.dynamics),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=ye.parseEnum(s,c),!0;case"bendtype":return e.bendType=ye.parseEnum(s,m),!0;case"bendstyle":return e.bendStyle=ye.parseEnum(s,f),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":e.bendPoints=[];for(const t of s){const i=new Pe;Xi.fromJson(i,t),e.addBendPoint(i)}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"hammerpulloriginnoteid":return e.hammerPullOriginNoteId=s,!0;case"hammerpulldestinationnoteid":return e.hammerPullDestinationNoteId=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"sluroriginnoteid":return e.slurOriginNoteId=s,!0;case"slurdestinationnoteid":return e.slurDestinationNoteId=s,!0;case"harmonictype":return e.harmonicType=ye.parseEnum(s,B),!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=ye.parseEnum(s,k),!0;case"slideouttype":return e.slideOutType=ye.parseEnum(s,v),!0;case"vibrato":return e.vibrato=ye.parseEnum(s,N),!0;case"tieoriginnoteid":return e.tieOriginNoteId=s,!0;case"tiedestinationnoteid":return e.tieDestinationNoteId=s,!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=ye.parseEnum(s,i),!0;case"righthandfinger":return e.rightHandFinger=ye.parseEnum(s,i),!0;case"isfingering":return e.isFingering=s,!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=ye.parseEnum(s,S),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=ye.parseEnum(s,T),!0;case"dynamics":return e.dynamics=ye.parseEnum(s,w),!0}return!1}}class qi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),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=>Yi.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=>Wi.toJson(e)))),t.set("dots",e.dots),t.set("fadeIn",e.fadeIn),t.set("lyrics",e.lyrics),t.set("hasRasgueado",e.hasRasgueado),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("brushType",e.brushType),t.set("brushDuration",e.brushDuration),t.set("tupletDenominator",e.tupletDenominator),t.set("tupletNumerator",e.tupletNumerator),t.set("isContinuedWhammy",e.isContinuedWhammy),t.set("whammyBarType",e.whammyBarType),t.set("whammyBarPoints",e.whammyBarPoints.map((e=>Xi.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordId",e.chordId),t.set("graceType",e.graceType),t.set("pickStroke",e.pickStroke),t.set("tremoloSpeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displayStart",e.displayStart),t.set("playbackStart",e.playbackStart),t.set("displayDuration",e.displayDuration),t.set("playbackDuration",e.playbackDuration),t.set("dynamics",e.dynamics),t.set("invertBeamDirection",e.invertBeamDirection),t.set("preferredBeamDirection",e.preferredBeamDirection),t.set("beamingMode",e.beamingMode),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"notes":e.notes=[];for(const t of i){const i=new Ie;Yi.fromJson(i,t),e.addNote(i)}return!0;case"isempty":return e.isEmpty=i,!0;case"whammystyle":return e.whammyStyle=ye.parseEnum(i,f),!0;case"ottava":return e.ottava=ye.parseEnum(i,p),!0;case"islegatoorigin":return e.isLegatoOrigin=i,!0;case"duration":return e.duration=ye.parseEnum(i,S),!0;case"automations":e.automations=[];for(const t of i){const i=new ve;Wi.fromJson(i,t),e.automations.push(i)}return!0;case"dots":return e.dots=i,!0;case"fadein":return e.fadeIn=i,!0;case"lyrics":return e.lyrics=i,!0;case"hasrasgueado":return e.hasRasgueado=i,!0;case"pop":return e.pop=i,!0;case"slap":return e.slap=i,!0;case"tap":return e.tap=i,!0;case"text":return e.text=i,!0;case"brushtype":return e.brushType=ye.parseEnum(i,y),!0;case"brushduration":return e.brushDuration=i,!0;case"tupletdenominator":return e.tupletDenominator=i,!0;case"tupletnumerator":return e.tupletNumerator=i,!0;case"iscontinuedwhammy":return e.isContinuedWhammy=i,!0;case"whammybartype":return e.whammyBarType=ye.parseEnum(i,L),!0;case"whammybarpoints":e.whammyBarPoints=[];for(const t of i){const i=new Pe;Xi.fromJson(i,t),e.addWhammyBarPoint(i)}return!0;case"vibrato":return e.vibrato=ye.parseEnum(i,N),!0;case"chordid":return e.chordId=i,!0;case"gracetype":return e.graceType=ye.parseEnum(i,_),!0;case"pickstroke":return e.pickStroke=ye.parseEnum(i,P),!0;case"tremolospeed":return e.tremoloSpeed=ye.parseEnum(i,S),!0;case"crescendo":return e.crescendo=ye.parseEnum(i,b),!0;case"displaystart":return e.displayStart=i,!0;case"playbackstart":return e.playbackStart=i,!0;case"displayduration":return e.displayDuration=i,!0;case"playbackduration":return e.playbackDuration=i,!0;case"dynamics":return e.dynamics=ye.parseEnum(i,w),!0;case"invertbeamdirection":return e.invertBeamDirection=i,!0;case"preferredbeamdirection":return e.preferredBeamDirection=ye.parseEnum(i,U),!0;case"beamingmode":return e.beamingMode=ye.parseEnum(i,M),!0}return!1}}class Ji{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("beats",e.beats.map((e=>qi.toJson(e)))),t.set("isEmpty",e.isEmpty),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"beats":e.beats=[];for(const t of i){const i=new He;qi.fromJson(i,t),e.addBeat(i)}return!0;case"isempty":return e.isEmpty=i,!0}return!1}}class Qi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),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=>Ji.toJson(e)))),t.set("simileMark",e.simileMark),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"clef":return e.clef=ye.parseEnum(i,u),!0;case"clefottava":return e.clefOttava=ye.parseEnum(i,p),!0;case"voices":e.voices=[];for(const t of i){const i=new Ze;Ji.fromJson(i,t),e.addVoice(i)}return!0;case"similemark":return e.simileMark=ye.parseEnum(i,g),!0}return!1}}class ji{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("name",e.name),t.set("firstFret",e.firstFret),t.set("strings",e.strings),t.set("barreFrets",e.barreFrets),t.set("showName",e.showName),t.set("showDiagram",e.showDiagram),t.set("showFingering",e.showFingering),t}static setProperty(e,t,i){switch(t){case"name":return e.name=i,!0;case"firstfret":return e.firstFret=i,!0;case"strings":return e.strings=i,!0;case"barrefrets":return e.barreFrets=i,!0;case"showname":return e.showName=i,!0;case"showdiagram":return e.showDiagram=i,!0;case"showfingering":return e.showFingering=i,!0}return!1}}class Ki{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("isStandard",e.isStandard),t.set("name",e.name),t.set("tunings",e.tunings),t}static setProperty(e,t,i){switch(t){case"isstandard":return e.isStandard=i,!0;case"name":return e.name=i,!0;case"tunings":return e.tunings=i,!0}return!1}}class $i{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("bars",e.bars.map((e=>Qi.toJson(e))));{const i=new Map;t.set("chords",i);for(const[t,s]of e.chords)i.set(t.toString(),ji.toJson(s))}return t.set("capo",e.capo),t.set("transpositionPitch",e.transpositionPitch),t.set("displayTranspositionPitch",e.displayTranspositionPitch),t.set("stringTuning",Ki.toJson(e.stringTuning)),t.set("showTablature",e.showTablature),t.set("showStandardNotation",e.showStandardNotation),t.set("isPercussion",e.isPercussion),t.set("standardNotationLineCount",e.standardNotationLineCount),t}static setProperty(e,t,i){switch(t){case"bars":e.bars=[];for(const t of i){const i=new Ne;Qi.fromJson(i,t),e.addBar(i)}return!0;case"chords":return e.chords=new Map,ye.forEach(i,((t,i)=>{const s=new We;ji.fromJson(s,t),e.addChord(i,s)})),!0;case"capo":return e.capo=i,!0;case"transpositionpitch":return e.transpositionPitch=i,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=i,!0;case"showtablature":return e.showTablature=i,!0;case"showstandardnotation":return e.showStandardNotation=i,!0;case"ispercussion":return e.isPercussion=i,!0;case"standardnotationlinecount":return e.standardNotationLineCount=i,!0}return["stringtuning"].indexOf(t)>=0&&(Ki.fromJson(e.stringTuning,i),!0)}}class Zi{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("volume",e.volume),t.set("balance",e.balance),t.set("port",e.port),t.set("program",e.program),t.set("primaryChannel",e.primaryChannel),t.set("secondaryChannel",e.secondaryChannel),t.set("isMute",e.isMute),t.set("isSolo",e.isSolo),t}static setProperty(e,t,i){switch(t){case"volume":return e.volume=i,!0;case"balance":return e.balance=i,!0;case"port":return e.port=i,!0;case"program":return e.program=i,!0;case"primarychannel":return e.primaryChannel=i,!0;case"secondarychannel":return e.secondaryChannel=i,!0;case"ismute":return e.isMute=i,!0;case"issolo":return e.isSolo=i,!0}return!1}}class es{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("elementType",e.elementType),t.set("staffLine",e.staffLine),t.set("noteHeadDefault",e.noteHeadDefault),t.set("noteHeadHalf",e.noteHeadHalf),t.set("noteHeadWhole",e.noteHeadWhole),t.set("techniqueSymbol",e.techniqueSymbol),t.set("techniqueSymbolPlacement",e.techniqueSymbolPlacement),t.set("outputMidiNumber",e.outputMidiNumber),t}static setProperty(e,t,i){switch(t){case"elementtype":return e.elementType=i,!0;case"staffline":return e.staffLine=i,!0;case"noteheaddefault":return e.noteHeadDefault=ye.parseEnum(i,E),!0;case"noteheadhalf":return e.noteHeadHalf=ye.parseEnum(i,E),!0;case"noteheadwhole":return e.noteHeadWhole=ye.parseEnum(i,E),!0;case"techniquesymbol":return e.techniqueSymbol=ye.parseEnum(i,E),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=ye.parseEnum(i,F),!0;case"outputmidinumber":return e.outputMidiNumber=i,!0}return!1}}class ts{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("staves",e.staves.map((e=>$i.toJson(e)))),t.set("playbackInfo",Zi.toJson(e.playbackInfo)),t.set("color",me.toJson(e.color)),t.set("name",e.name),t.set("shortName",e.shortName),t.set("percussionArticulations",e.percussionArticulations.map((e=>es.toJson(e)))),t}static setProperty(e,t,i){switch(t){case"staves":e.staves=[];for(const t of i){const i=new Ke;$i.fromJson(i,t),e.addStaff(i)}return!0;case"color":return e.color=me.fromJson(i),!0;case"name":return e.name=i,!0;case"shortname":return e.shortName=i,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of i){const i=new Le;es.fromJson(i,t),e.percussionArticulations.push(i)}return!0}return["playbackinfo"].indexOf(t)>=0&&(Zi.fromJson(e.playbackInfo,i),!0)}}class is{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("hideDynamics",e.hideDynamics),t}static setProperty(e,t,i){switch(t){case"hidedynamics":return e.hideDynamics=i,!0}return!1}}class ss{static fromJson(e,t){t&&ye.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),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=>zi.toJson(e)))),t.set("tracks",e.tracks.map((e=>ts.toJson(e)))),t.set("stylesheet",is.toJson(e.stylesheet)),t}static setProperty(e,t,i){switch(t){case"album":return e.album=i,!0;case"artist":return e.artist=i,!0;case"copyright":return e.copyright=i,!0;case"instructions":return e.instructions=i,!0;case"music":return e.music=i,!0;case"notices":return e.notices=i,!0;case"subtitle":return e.subTitle=i,!0;case"title":return e.title=i,!0;case"words":return e.words=i,!0;case"tab":return e.tab=i,!0;case"tempo":return e.tempo=i,!0;case"tempolabel":return e.tempoLabel=i,!0;case"masterbars":e.masterBars=[];for(const t of i){const i=new ze;zi.fromJson(i,t),e.addMasterBar(i)}return!0;case"tracks":e.tracks=[];for(const t of i){const i=new $e;ts.fromJson(i,t),e.addTrack(i)}return!0}return["stylesheet"].indexOf(t)>=0&&(is.fromJson(e.stylesheet,i),!0)}}class as{static jsonReplacer(e,t){if(t instanceof Map){if("fromEntries"in Object)return Object.fromEntries(t);{const e={};for(const[i,s]of t)e[i]=s;return e}}return ArrayBuffer.isView(t)?Array.apply([],[t]):t}static scoreToJson(e){let t=as.scoreToJsObject(e);return JSON.stringify(t,as.jsonReplacer)}static jsonToScore(e,t){return as.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ss.toJson(e)}static jsObjectToScore(e,t){let i=new qe;return ss.fromJson(i,e),i.finish(null!=t?t:new Gi),i}static settingsToJson(e){let t=as.settingsToJsObject(e);return JSON.stringify(t,as.jsonReplacer)}static jsonToSettings(e){return as.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Oi.toJson(e)}static jsObjectToSettings(e){let t=new Gi;return Oi.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new Ti;t.division=e.division;let i=e.events;for(let e of i){let i=as.jsObjectToMidiEvent(e);t.events.push(i)}return t}static jsObjectToMidiEvent(e){let t,i=e.track,s=e.tick,a=e.message;switch(e.type){case"SystemExclusiveEvent":t=new Ht(i,s,0,0,e.data),t.message=a;break;case"MetaDataEvent":t=new ki(i,s,0,0,e.data),t.message=a;break;case"MetaNumberEvent":t=new vi(i,s,0,0,e.value),t.message=a;break;case"Midi20PerNotePitchBendEvent":t=new Vi(i,s,0,e.noteKey,e.pitch),t.message=a;break;default:t=new Ot(i,s,0,0,0),t.message=a}return t}static midiFileToJsObject(e){let t={};t.division=e.division;let i=[];t.events=i;for(let t of e.events)i.push(as.midiEventToJsObject(t));return t}static midiEventToJsObject(e){let t={};return t.track=e.track,t.tick=e.tick,t.message=e.message,e instanceof Ht?(t.type="SystemExclusiveEvent",t.data=e.data):e instanceof ki?(t.type="MetaDataEvent",t.data=e.data):e instanceof vi?(t.type="MetaNumberEvent",t.value=e.value):e instanceof Vi&&(t.type="Midi20PerNotePitchBendEvent",t.noteKey=e.noteKey,t.pitch=e.pitch),t}}class rs{constructor(){this.ready=new Si,this.samplesPlayed=new wi,this.sampleRequest=new Si}get sampleRate(){return rs.preferredSampleRate}open(){Fe.debug("AlphaSynth","Initializing webworker worker"),this._worker=to.globalThis,this._worker.addEventListener("message",this.handleMessage.bind(this)),this.ready.trigger()}handleMessage(e){let t=e.data;switch(t.cmd){case rs.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case rs.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(){}}rs.CmdOutputPrefix="alphaSynth.output.",rs.CmdOutputAddSamples=rs.CmdOutputPrefix+"addSamples",rs.CmdOutputPlay=rs.CmdOutputPrefix+"play",rs.CmdOutputPause=rs.CmdOutputPrefix+"pause",rs.CmdOutputResetSamples=rs.CmdOutputPrefix+"resetSamples",rs.CmdOutputSampleRequest=rs.CmdOutputPrefix+"sampleRequest",rs.CmdOutputSamplesPlayed=rs.CmdOutputPrefix+"samplesPlayed",rs.preferredSampleRate=0;class ns{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Bi(new rs),this._player.positionChanged.on(this.onPositionChanged.bind(this)),this._player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this._player.finished.on(this.onFinished.bind(this)),this._player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.midiLoaded.on(this.onMidiLoaded.bind(this)),this._player.midiLoadFailed.on(this.onMidiLoadFailed.bind(this)),this._player.readyForPlayback.on(this.onReadyForPlayback.bind(this)),this._player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this._main.postMessage({cmd:"alphaSynth.ready"})}static init(){let e=to.globalThis;e.addEventListener("message",(t=>{let i=t.data;switch(i.cmd){case"alphaSynth.initialize":rs.preferredSampleRate=i.sampleRate,Fe.logLevel=i.logLevel,to.globalThis.alphaSynthWebWorker=new ns(e)}}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":Fe.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(as.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(as.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates()}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){let t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map(as.midiEventToJsObject)})}}class os{static generateFontLookup(e){if(!os.FontSizeLookupTables.has(e))if(to.isRunningInWorker)os.FontSizeLookupTables.set(e,new Uint8Array([8]));else{let t=document.createElement("canvas").getContext("2d");t.font="11px "+e;let i=[];for(let e=32;e<255;e++){let s=String.fromCharCode(e);i.push(t.measureText(s).width)}let s=new Uint8Array(i);os.FontSizeLookupTables.set(e,s)}}static measureString(e,t,i,s){let a;os.FontSizeLookupTables.has(t)||os.generateFontLookup(t),a=os.FontSizeLookupTables.get(t);let r=1;0!=(s&o.Italic)&&(r*=1.2),0!=(s&o.Bold)&&(r*=1.2);let n=0;for(let t=0;t<e.length;t++){let s=Math.min(a.length-1,e.charCodeAt(t)-32);s>=0&&(n+=a[s]*i/11)}return n*r}}os.Georgia=new Uint8Array([3,4,5,7,7,9,8,2,4,4,5,7,3,4,3,5,7,5,6,6,6,6,6,6,7,6,3,3,7,7,7,5,10,7,7,7,8,7,7,8,9,4,6,8,7,10,8,8,7,8,8,6,7,8,7,11,8,7,7,4,5,4,7,7,6,6,6,5,6,5,4,6,6,3,3,6,3,10,6,6,6,6,5,5,4,6,5,8,6,5,5,5,4,5,7,6,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,4,6,7,6,7,4,6,6,10,6,6,7,0,10,7,5,7,6,6,6,6,6,3,6,6,6,6,12,12,12,5,7,7,7,7,7,7,11,7,7,7,7,7,4,4,4,4,8,8,8,8,8,8,8,7,8,8,8,8,8,7,7,6,6,6,6,6,6,6,8,5,5,5,5,5,3,3,3,3,6,6,6,6,6,6,6,7,6,6,6,6,6,5,6]),os.Arial=new Uint8Array([3,3,4,6,6,10,7,2,4,4,4,6,3,4,3,3,6,6,6,6,6,6,6,6,6,6,3,3,6,6,6,6,11,7,7,8,8,7,7,9,8,3,6,7,6,9,8,9,7,9,8,7,7,8,7,10,7,7,7,3,3,3,5,6,4,6,6,6,6,6,3,6,6,2,2,6,2,9,6,6,6,6,4,6,3,6,6,8,6,6,6,4,3,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,6,6,6,6,3,6,4,8,4,6,6,0,8,6,4,6,4,4,4,6,6,4,4,4,4,6,9,9,9,7,7,7,7,7,7,7,11,8,7,7,7,7,3,3,3,3,8,8,9,9,9,9,9,6,9,8,8,8,8,7,7,7,6,6,6,6,6,6,10,6,6,6,6,6,3,3,3,3,6,6,6,6,6,6,6,6,7,6,6,6,6,6,6]),os.FontSizeLookupTables=new Map([["Arial",os.Arial],["'Arial'",os.Arial],['"Arial"',os.Arial],["Georgia",os.Georgia],["'Georgia'",os.Georgia],['"Georgia"',os.Georgia]]),os.ControlChars=32;class hs{constructor(){this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=0,this.lastMasterBarIndex=0,this.renderResult=null}}class ls{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(let i of this.beats)if(!t||i.realBounds.x<e)t=i;else if(i.realBounds.x>e)break;return t}}class cs{constructor(){this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){if(!this.notes)return null;for(let i of this.notes){let s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x>=e&&i.noteHeadBounds.y>=t&&e<=a&&t<=s)return i.note}return null}}class ds{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[]}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let i=null;for(let t of this.bars){let s=t.findBeatAtPos(e);s&&(!i||i.realBounds.x<s.realBounds.x)&&(i=s)}return i?i.beat:null}finish(){this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0))}addBeat(e){this.staveGroupBounds.boundsLookup.addBeat(e)}}class us{}class ps{constructor(){this.index=0,this.bars=[]}finish(){for(let e of this.bars)e.finish()}addBar(e){this.boundsLookup.addMasterBar(e),e.staveGroupBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(let i of this.bars)if(!t||i.realBounds.x<e)t=i;else if(e>i.realBounds.x+i.realBounds.w)break;return t}}class gs{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaveGroup=null,this.staveGroups=[],this.isFinished=!1}toJson(){let e={},t=[];e.staveGroups=t;for(let e of this.staveGroups){let i={};i.visualBounds=this.boundsToJson(e.visualBounds),i.realBounds=this.boundsToJson(e.realBounds),i.bars=[];for(let t of e.bars){let e={};e.lineAlignedBounds=this.boundsToJson(t.lineAlignedBounds),e.visualBounds=this.boundsToJson(t.visualBounds),e.realBounds=this.boundsToJson(t.realBounds),e.index=t.index,e.bars=[];for(let i of t.bars){let t={};t.visualBounds=this.boundsToJson(i.visualBounds),t.realBounds=this.boundsToJson(i.realBounds),t.beats=[];for(let e of i.beats){let i={};i.visualBounds=this.boundsToJson(e.visualBounds),i.realBounds=this.boundsToJson(e.realBounds);let s=i;if(s.beatIndex=e.beat.index,s.voiceIndex=e.beat.voice.index,s.barIndex=e.beat.voice.bar.index,s.staffIndex=e.beat.voice.bar.staff.index,s.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){let t=i.notes=[];for(let i of e.notes){let e={};e.index=i.note.index,e.noteHeadBounds=this.boundsToJson(i.noteHeadBounds),t.push(e)}}t.beats.push(i)}e.bars.push(t)}i.bars.push(e)}t.push(i)}return e}static fromJson(e,t){let i=new gs,s=e.staveGroups;for(let e of s){let s=new ps;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds,i.addStaveGroup(s);for(let i of e.bars){let e=new ds;e.index=i.index,e.isFirstOfLine=i.isFirstOfLine,e.lineAlignedBounds=i.lineAlignedBounds,e.visualBounds=i.visualBounds,e.realBounds=i.realBounds,s.addBar(e);for(let s of i.bars){let i=new ls;i.visualBounds=s.visualBounds,i.realBounds=s.realBounds,e.addBar(i);for(let e of s.beats){let s=new cs;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds;let a=e;if(s.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){s.notes=[];for(let t of e.notes){let e=new us,i=t;e.note=s.beat.notes[i.index],e.noteHeadBounds=t.noteHeadBounds,s.addNote(e)}}i.addBeat(s)}}}}return i}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(){for(let e of this.staveGroups)e.finish();this.isFinished=!0}addNote(e){this.findBeat(e.note.beat).addNote(e)}addStaveGroup(e){e.index=this.staveGroups.length,e.boundsLookup=this,this.staveGroups.push(e),this._currentStaveGroup=e}addMasterBar(e){e.staveGroupBounds?this._masterBarLookup.set(e.index,e):(e.staveGroupBounds=this._currentStaveGroup,this._masterBarLookup.set(e.index,e),this._currentStaveGroup.addBar(e))}addBeat(e){this._beatLookup.set(e.beat.id,e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){let t=e.index;return this._masterBarLookup.has(t)?this._masterBarLookup.get(t):null}findBeat(e){let t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let i=0,s=this.staveGroups.length-1,a=-1;for(;i<=s;){let e=(s+i)/2|0,r=this.staveGroups[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?s=e-1:i=e+1}if(-1===a)return null;let r=this.staveGroups[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,i){let s=this.findBeat(e);return s?s.findNoteAtPos(t,i):null}}class fs{constructor(t){this._currentLayoutMode=e.LayoutMode.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new wi,this.renderFinished=new wi,this.partialRenderFinished=new wi,this.postRenderFinished=new Si,this.error=new wi,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas=to.getRenderEngineFactory(this.settings).createCanvas(),this._currentRenderEngine=this.settings.core.engine,!0)}recreateLayout(){return(!this.layout||this._currentLayoutMode!==this.settings.display.layoutMode)&&(this.layout=to.getLayoutEngineFactory(this.settings).createLayout(this),this._currentLayoutMode=this.settings.display.layoutMode,!0)}renderScore(e,t){try{let i;if(this.score=e,t){i=[];for(let s of t)s>=0&&s<e.tracks.length&&i.push(e.tracks[s])}else i=e.tracks.slice(0);0===i.length&&e.tracks.length>0&&i.push(e.tracks[0]),this.tracks=i,this.render()}catch(e){this.error.trigger(e)}}renderTracks(e){0===e.length?this.score=null:this.score=e[0].score,this.tracks=e,this.render()}updateSettings(e){this.settings=e}render(){if(0!==this.width){if(this.boundsLookup=new gs,this.tracks&&0!==this.tracks.length){this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,Fe.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];Fe.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),this._renderedTracks=this.tracks,Fe.debug("Rendering","Rendering finished")}}else Fe.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(Fe.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(Fe.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new gs,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.layout.renderAnnotation(),this.onRenderFinished(),this.postRenderFinished.trigger()):Fe.warning("Rendering","Current layout does not support dynamic resizing, nothing was done",null),Fe.debug("Rendering","Resize finished")}layoutAndRender(){Fe.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this.layout.renderAnnotation(),this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){const e=new hs;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class ms{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){to.globalThis.alphaTabWebWorker=new ms(to.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=as.jsObjectToSettings(t.settings);Fe.logLevel=e.core.logLevel,this._renderer=new fs(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{var e,t;this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:null!==(t=null===(e=this._renderer.boundsLookup)||void 0===e?void 0:e.toJson())&&void 0!==t?t:null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);let i=as.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(i,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){os.FontSizeLookupTables||(os.FontSizeLookupTables=new Map);for(let t in e)os.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){Oi.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){Fe.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class ys{constructor(){this._canvas=null,this._color=new me(0,0,0,255),this._font=new we("Arial",10,o.Plain),this._lineWidth=0;let e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);let t=window.getComputedStyle(e),i=t.fontFamily;(i.startsWith('"')||i.startsWith("'"))&&(i=i.substr(1,i.length-2)),this._musicFont=new we(i,parseFloat(t.fontSize),o.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}onRenderFinished(){return null}beginRender(e,t){this._canvas=document.createElement("canvas"),this._canvas.width=e*to.HighDpiFactor|0,this._canvas.height=t*to.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(to.HighDpiFactor,to.HighDpiFactor),this._context.lineWidth=this._lineWidth}endRender(){let e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,i,s){i>0&&this._context.fillRect(0|e,0|t,i,s)}strokeRect(e,t,i,s){this._context.strokeRect(0|e,0|t,i,s)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,i,s){this._context.quadraticCurveTo(e,t,i,s)}bezierCurveTo(e,t,i,s,a,r){this._context.bezierCurveTo(e,t,i,s,a,r)}fillCircle(e,t,i){this._context.beginPath(),this._context.arc(e,t,i,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,i){this._context.beginPath(),this._context.arc(e,t,i,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill()}stroke(){this._context.stroke()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(this.settings.display.scale)),this._measureContext.font=e.toCssString(this.settings.display.scale)}get textAlign(){switch(this._context.textAlign){case"left":return C.Left;case"center":return C.Center;case"right":return C.Right;default:return C.Left}}set textAlign(e){switch(e){case C.Left:this._context.textAlign="left";break;case C.Center:this._context.textAlign="center";break;case C.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":return F.Top;case"middle":return F.Middle;case"bottom":return F.Bottom;default:return F.Top}}set textBaseline(e){switch(e){case F.Top:this._context.textBaseline="hanging";break;case F.Middle:this._context.textBaseline="middle";break;case F.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,i){this._context.fillText(e,t,i)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,i,s,a=!1){s!==E.None&&this.fillMusicFontSymbolText(e,t,i,String.fromCharCode(s),a)}fillMusicFontSymbols(e,t,i,s,a=!1){let r="";for(let e of s)e!==E.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a=!1){let r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(i),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(s,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,i){this._context.save(),this._context.translate(e,t),this._context.rotate(i*Math.PI/180)}endRotate(){this._context.restore()}}class bs{constructor(e){this._midiFile=e}addTimeSignature(e,t,i){let s=0;for(;(i>>=1)>0;)s++;const a=new ki(0,e,255,Y.TimeSignature,new Uint8Array([255&t,255&s,48,8]));this._midiFile.addEvent(a)}addRest(e,t,i){const s=new Ht(e,t,q.SystemExclusive,Ht.AlphaTabManufacturerId,new Uint8Array([J.Rest]));this._midiFile.addEvent(s)}addNote(e,t,i,s,a,r){const n=xe.dynamicToVelocity(a),o=new Ot(e,t,this.makeCommand(X.NoteOn,r),bs.fixValue(s),bs.fixValue(n));this._midiFile.addEvent(o);const h=new Ot(e,t+i,this.makeCommand(X.NoteOff,r),bs.fixValue(s),bs.fixValue(n));this._midiFile.addEvent(h)}makeCommand(e,t){return 240&e|15&t}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,i,s,a){const r=new Ot(e,t,this.makeCommand(X.Controller,i),bs.fixValue(s),bs.fixValue(a));this._midiFile.addEvent(r)}addProgramChange(e,t,i,s){const a=new Ot(e,t,this.makeCommand(X.ProgramChange,i),bs.fixValue(s),0);this._midiFile.addEvent(a)}addTempo(e,t){const i=6e7/t|0,s=new vi(0,e,255,Y.Tempo,i);this._midiFile.addEvent(s)}addBend(e,t,i,s){s=s>=Ut.MaxPitchWheel?Ut.MaxPitchWheel:Math.floor(s);const a=new Ot(e,t,this.makeCommand(X.PitchBend,i),127&s,s>>7&127);this._midiFile.addEvent(a)}addNoteBend(e,t,i,s,a){a=(a=a>=Ut.MaxPitchWheel?Ut.MaxPitchWheel:Math.floor(a))*Ut.MaxPitchWheel20/Ut.MaxPitchWheel;const r=new Vi(e,t,this.makeCommand(X.PerNotePitchBend,i),s,a);this._midiFile.addEvent(r)}finishTrack(e,t){const i=new ki(e,t,255,Y.EndOfTrack,new Uint8Array(0));this._midiFile.addEvent(i)}}class Ss{constructor(){this._highlightedBeats=new Map,this.start=0,this.end=0,this.isEmptyBar=!1,this.beatsToHighlight=[]}highlightBeat(e){this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.beatsToHighlight.push(e))}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(te||(te={}));class ws{constructor(e){this._repeatStartIndex=0,this._repeatNumber=0,this._repeatOpen=!1,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}get finished(){return this.index>=this._score.masterBars.length}processCurrent(){const e=this._score.masterBars[this.index],t=e.alternateEndings;e.repeatGroup.isClosed||e.repeatGroup.openings[e.repeatGroup.openings.length-1]!==e||(this._repeatNumber=0,this._repeatOpen=!1),!e.isRepeatStart&&0!==e.index||0!==this._repeatNumber?e.isRepeatStart&&(this.shouldPlay=!0):(this._repeatStartIndex=this.index,this._repeatOpen=!0),this._repeatOpen&&t>0&&(0==(t&1<<this._repeatNumber)?this.shouldPlay=!1:this.shouldPlay=!0),this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){const e=this._score.masterBars[this.index].repeatCount-1;this._repeatOpen&&e>0?this._repeatNumber<e?(this.index=this._repeatStartIndex,this._repeatNumber++):(this._repeatNumber=0,this._repeatOpen=!1,this.shouldPlay=!0,this.index++):this.index++}}class _s{constructor(){this.start=0,this.end=0,this.tempo=0,this.beats=[],this.nextMasterBar=null}finish(){this.beats.sort(((e,t)=>e.start-t.start))}addBeat(e){this.beats.push(e)}}class Bs{constructor(){this.nextBeat=null,this.duration=0}}class Ts{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}finish(){let e=null,t=[];for(let i of this.masterBars){i.finish(),e&&(e.nextMasterBar=i);for(const e of i.beats){const i=[];for(let s of t)s.end>e.start&&(i.push(s),e.highlightBeat(s.beat),e.start<=s.start&&s.highlightBeat(e.beat));i.push(e),t=i}e=i}}findBeat(e,t){const i=this.findMasterBar(t);if(!i)return null;const s=new Map;for(const t of e)s.set(t.index,!0);let a=null,r=0,n=i.beats;for(let e=0;e<n.length;e++){let i=n[e];if(s.has(i.beat.voice.bar.staff.track.index))if(i.start<=t&&t<i.end)(!a||a.start<i.start)&&(a=n[e],r=e);else if(i.end>t)break}if(!a)return null;let o=null;for(let e=r+1;e<n.length;e++){const t=n[e];if(t.start>a.start&&s.has(t.beat.voice.bar.staff.track.index)){o=t;break}}if(!o&&i.nextMasterBar){n=i.nextMasterBar.beats;for(let e=0;e<n.length;e++){const t=n[e];if(s.has(t.beat.voice.bar.staff.track.index)){o=t;break}}}const h=new Bs;return h.currentBeat=a.beat,h.nextBeat=o?o.beat:null,h.duration=o?xe.ticksToMillis(o.start-a.start,i.tempo):xe.ticksToMillis(a.end-a.start,i.tempo),h.beatsToHighlight=a.beatsToHighlight,h}findMasterBar(e){const t=this.masterBars;let i=0,s=t.length-1;for(;i<=s;){const a=(s+i)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?s=a-1:i=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new _s;return t.masterBar=e,t}return this.masterBarLookup.get(e.index)}getMasterBarStart(e){return this.masterBarLookup.has(e.index)?this.masterBarLookup.get(e.index).start:0}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e){var t;null===(t=this._currentMasterBar)||void 0===t||t.addBeat(e)}}class ks{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class vs{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Ns{constructor(e,t,i){this._currentTempo=0,this._currentBarRepeatLookup=null,this._programsPerChannel=new Map,this.tickLookup=new Ts,this._currentTripletFeel=null,this._score=e,this._settings=t||new Gi,this._currentTempo=this._score.tempo,this._handler=i}generate(){for(const e of this._score.tracks)this.generateTrack(e);Fe.debug("Midi","Begin midi generation");const e=new ws(this._score);let t=null;for(;!e.finished;){const i=e.index,s=this._score.masterBars[i],a=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(s,t,a);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],a)}e.moveNext(),t=s}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);this.tickLookup.finish(),Fe.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,i,s){this._programsPerChannel.has(i)&&this._programsPerChannel.get(i)===s||(this._handler.addProgramChange(e.index,t,i,s),this._programsPerChannel.set(i,s))}generateChannel(e,t,i){let s=Ns.toChannelShort(i.volume),a=Ns.toChannelShort(i.balance);this._handler.addControlChange(e.index,0,t,te.VolumeCoarse,s),this._handler.addControlChange(e.index,0,t,te.PanCoarse,a),this._handler.addControlChange(e.index,0,t,te.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,te.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,te.DataEntryCoarse,Ns.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,i.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(i,e.timeSignatureNumerator,e.timeSignatureDenominator),t?e.tempoAutomation&&(this._handler.addTempo(i,e.tempoAutomation.value),this._currentTempo=e.tempoAutomation.value):(this._handler.addTempo(i,e.score.tempo),this._currentTempo=e.score.tempo);const s=new _s;s.masterBar=e,s.start=i,s.tempo=this._currentTempo,s.end=s.start+e.calculateDuration(),this.tickLookup.addMasterBar(s)}generateBar(e,t){let i=this.getPlaybackBar(e);this._currentBarRepeatLookup=null;for(const s of i.voices)this.generateVoice(s,t,e)}getPlaybackBar(e){switch(e.simileMark){case g.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case g.FirstOfDouble:case g.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,i){if(!e.isEmpty||e.bar.isEmpty&&0===e.index)for(const s of e.beats)this.generateBeat(s,t,i)}generateBeat(e,t,i){let s=e.playbackStart,a=e.playbackDuration;e.voice.bar.isEmpty?a=e.voice.bar.masterBar.calculateDuration():e.voice.bar.masterBar.tripletFeel!==R.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(s-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Ns.calculateTripletFeelInfo(s,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration)));const r=new Ss;r.start=t+s;const n=e.nextBeat?e.nextBeat.absolutePlaybackStart-e.absolutePlaybackStart:a;r.end=t+s,r.highlightBeat(e),r.end+=n>a?n:a,i===e.voice.bar?(r.beat=e,this.tickLookup.addBeat(r)):(r.isEmptyBar=!0,r.beat=i.voices[0].beats[0],this._currentBarRepeatLookup?this._currentBarRepeatLookup.end=r.end:(this._currentBarRepeatLookup=r,this.tickLookup.addBeat(this._currentBarRepeatLookup)));const o=e.voice.bar.staff.track;for(const i of e.automations)this.generateAutomation(e,i,t);if(e.isRest)this._handler.addRest(o.index,t+s,o.playbackInfo.primaryChannel);else{let i=this.getBrushInfo(e);for(const r of e.notes)this.generateNote(r,t+s,a,i)}if(e.vibrato!==N.None){let i=240,a=3;switch(e.vibrato){case N.Slight:i=this._settings.player.vibrato.beatSlightLength,a=this._settings.player.vibrato.beatSlightAmplitude;break;case N.Wide:i=this._settings.player.vibrato.beatWideLength,a=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+s,e.playbackDuration,i,a,((t,i)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,i)}))}}static calculateTripletFeelInfo(e,t,i){let s;switch(i.voice.bar.masterBar.tripletFeel){case R.Triplet8th:case R.Dotted8th:case R.Scottish8th:s=S.Eighth;break;case R.Triplet16th:case R.Dotted16th:case R.Scottish16th:s=S.Sixteenth;break;default:return null}const a=xe.toTicks(s);if(t!==a)return null;if(e%a!=0)return null;if(!i.nextBeat||i.nextBeat.voice!==i.voice||i.playbackDuration!==a)return null;const r=new vs;switch(i.voice.bar.masterBar.tripletFeel){case R.Triplet8th:r.firstBeatDuration=xe.applyTuplet(xe.toTicks(S.Quarter),3,2),r.secondBeatDuration=xe.applyTuplet(xe.toTicks(S.Eighth),3,2);break;case R.Dotted8th:r.firstBeatDuration=xe.applyDot(xe.toTicks(S.Eighth),!1),r.secondBeatDuration=xe.toTicks(S.Sixteenth);break;case R.Scottish8th:r.firstBeatDuration=xe.toTicks(S.Sixteenth),r.secondBeatDuration=xe.applyDot(xe.toTicks(S.Eighth),!1);break;case R.Triplet16th:r.firstBeatDuration=xe.applyTuplet(xe.toTicks(S.Eighth),3,2),r.secondBeatDuration=xe.applyTuplet(xe.toTicks(S.Sixteenth),3,2);break;case R.Dotted16th:r.firstBeatDuration=xe.applyDot(xe.toTicks(S.Sixteenth),!1),r.secondBeatDuration=xe.toTicks(S.ThirtySecond);break;case R.Scottish16th:r.firstBeatDuration=xe.toTicks(S.ThirtySecond),r.secondBeatDuration=xe.applyDot(xe.toTicks(S.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,i,s){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.realValue;if(e.isPercussion){const t=Me.getArticulation(e);t&&(n=t.outputMidiNumber)}const o=e.isStringed&&e.string<=s.length?s[e.string-1]:0,h=t+o,l=this.getNoteDuration(e,i);l.untilTieOrSlideEnd-=o,l.noteOnly-=o,l.letRingEnd-=o;const c=Ns.getDynamicValue(e),d=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==N.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Ns.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Ns.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===v.Legato?-1:Ns.getPitchWheel(0),u>=0&&this._handler.addNoteBend(a.index,h,d,n,u),e.beat.fadeIn&&this.generateFadeIn(e,h,l),!e.isTrill||r.isPercussion){if(e.beat.isTremolo)this.generateTremoloPicking(e,h,l,n,c,d);else if(e.hasBend?this.generateBend(e,h,l,n,d):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,h,l,d):e.slideInType!==k.None||e.slideOutType!==v.None?this.generateSlide(e,h,l,n,c,d):e.vibrato!==N.None&&this.generateVibrato(e,h,l,n,d),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===v.Legato)){let e=Math.max(l.untilTieOrSlideEnd,l.letRingEnd);this._handler.addNote(a.index,h,e,n,c,d)}}else this.generateTrill(e,h,l,n,c,d)}getNoteDuration(t,i){const s=new ks;if(s.noteOnly=i,s.untilTieOrSlideEnd=i,s.letRingEnd=i,t.isDead)return s.noteOnly=this.applyStaticDuration(Ns.DefaultDurationDead,i),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isPalmMute)return s.noteOnly=this.applyStaticDuration(Ns.DefaultDurationPalmMute,i),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isStaccato)return s.noteOnly=i/2|0,s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isTieOrigin){const e=t.tieDestination;if(e)if(t.isTieDestination){const t=this.getNoteDuration(e,e.beat.playbackDuration);s.untilTieOrSlideEnd=i+t.untilTieOrSlideEnd}else{const i=t.beat.absolutePlaybackStart,a=this.getNoteDuration(e,e.beat.playbackDuration),r=e.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}else if(t.slideOutType===v.Legato){const e=t.slideTarget;if(e){const i=t.beat.absolutePlaybackStart,a=this.getNoteDuration(e,e.beat.playbackDuration),r=e.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}if(t.isLetRing&&this._settings.notation.notationMode===e.NotationMode.GuitarPro){let e=t.beat,a=0;const r=t.beat.voice.bar.masterBar.calculateDuration();for(;e.nextBeat;){let i=e.nextBeat;if(i.isRest)break;if(t.isStringed&&i.hasNoteOnString(t.string))break;if(e=e.nextBeat,a=e.absolutePlaybackStart-t.beat.absolutePlaybackStart+e.playbackDuration,a>r){a=r;break}}e===t.beat?s.letRingEnd=i:s.letRingEnd=a}else s.letRingEnd=s.untilTieOrSlideEnd;return s}applyStaticDuration(e,t){const i=this._currentTempo*e/Pe.MaxPosition|0;return Math.min(i,t)}static getDynamicValue(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case c.Normal:t++;break;case c.Heavy:t+=2}return t}generateFadeIn(e,t,i){const s=e.beat.voice.bar.staff.track,a=Ns.toChannelShort(s.playbackInfo.volume)/i.noteOnly,r=i.noteOnly/120|0,n=t+i.noteOnly;for(let e=r-1;e>=0;e--){const i=n-120*e,o=(i-t)*a;e===r-1&&(this._handler.addControlChange(s.index,t,s.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(s.index,t,s.playbackInfo.secondaryChannel,te.VolumeCoarse,o)),this._handler.addControlChange(s.index,i,s.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(s.index,i,s.playbackInfo.secondaryChannel,te.VolumeCoarse,o)}}generateVibrato(e,t,i,s,a){let r=0,n=0;switch(e.vibrato){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;this.generateVibratorWithParams(t,i.noteOnly,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,s,t)}))}generateVibratorWithParams(e,t,i,s,a){const r=i/2|0,n=(e+=i)+t;for(;e<n;){let t=0;const o=e+i<n?i:n-e;for(;t<o;){let i=s*Math.sin(t*Math.PI/r);a(e+t|0,Ns.getPitchWheel(i)),t+=16}e+=i}}static getPitchWheel(e){return Ut.DefaultPitchWheel+e/2*Ns.PitchValuePerSemitone}generateSlide(e,t,i,s,a,r){let n=e.slideOutType===v.Legato?i.noteOnly:i.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,c=Math.floor(Pe.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),d=Math.floor(Pe.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case k.IntoFromAbove:o.push(new Pe(0,l)),o.push(new Pe(c,0));break;case k.IntoFromBelow:o.push(new Pe(0,-l)),o.push(new Pe(c,0))}switch(e.slideOutType){case v.Legato:case v.Shift:o.push(new Pe(d,0));const t=2*(e.slideTarget.realValue-e.realValue);o.push(new Pe(Pe.MaxPosition,t));break;case v.OutDown:o.push(new Pe(Pe.MaxPosition-c,0)),o.push(new Pe(Pe.MaxPosition,-l));break;case v.OutUp:o.push(new Pe(Pe.MaxPosition-c,0)),o.push(new Pe(Pe.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,((e,t)=>{this._handler.addNoteBend(h.index,e,r,s,t)}))}generateBend(e,t,i,s,a){let r=e.bendPoints,n=e.beat.voice.bar.staff.track;const o=(e,t)=>{this._handler.addNoteBend(n.index,e,a,s,t)};let h,l=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;h=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==_.None){switch(e.tieDestination.bendType){case m.Bend:case m.BendRelease:case m.PrebendBend:l=e.tieDestination.bendPoints[1].value;break;case m.Prebend:case m.PrebendRelease:l=e.tieDestination.bendPoints[0].value}h=Math.max(i.noteOnly,xe.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else h=i.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const c=Math.min(h,xe.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let d=[];switch(e.bendType){case m.Custom:d=r;break;case m.Bend:case m.Release:switch(e.bendStyle){case f.Default:d=r;break;case f.Gradual:d.push(new Pe(0,e.bendPoints[0].value)),(!l||l<e.bendPoints[1].value)&&(l=e.bendPoints[1].value),d.push(new Pe(Pe.MaxPosition,l));break;case f.Fast:return(!l||l<e.bendPoints[1].value)&&(l=e.bendPoints[1].value),void(e.beat.graceType===_.BendGrace?this.generateSongBookWhammyOrBend(t,h,!0,[e.bendPoints[0].value,l],c,o):this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,l],c,o))}break;case m.BendRelease:switch(e.bendStyle){case f.Default:d=r;break;case f.Gradual:d.push(new Pe(0,e.bendPoints[0].value)),d.push(new Pe(Pe.MaxPosition/2|0,e.bendPoints[1].value)),d.push(new Pe(Pe.MaxPosition,e.bendPoints[2].value));break;case f.Fast:return void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],c,o)}break;case m.Hold:case m.Prebend:d=r;break;case m.PrebendBend:switch(e.bendStyle){case f.Default:d=r;break;case f.Gradual:d.push(new Pe(0,e.bendPoints[0].value)),d.push(new Pe(Pe.MaxPosition,e.bendPoints[1].value));break;case f.Fast:return o(t,0|Ns.getPitchWheel(e.bendPoints[0].value)),(!l||l<e.bendPoints[1].value)&&(l=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,l],c,o)}break;case m.PrebendRelease:switch(e.bendStyle){case f.Default:d=r;break;case f.Gradual:d.push(new Pe(0,e.bendPoints[0].value)),d.push(new Pe(Pe.MaxPosition,e.bendPoints[1].value));break;case f.Fast:return o(t,0|Ns.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,e.bendPoints[1].value],c,o)}}this.generateWhammyOrBend(t,h,d,o)}generateSongBookWhammyOrBend(e,t,i,s,a,r){const n=i?e:e+t-a,o=a/(s.length-1);for(let e=0;e<s.length-1;e++){const t=Ns.getPitchWheel(s[e]),i=Ns.getPitchWheel(s[e+1]),a=n+o*e;this.generateBendValues(a,o,t,i,r)}}generateWhammy(e,t,i,s){const a=e.whammyBarPoints,r=e.voice.bar.staff.track,n=i.noteOnly;a[0].value>0&&!e.isContinuedWhammy&&t--;const o=(e,t)=>{this._handler.addBend(r.index,e,s,t)};let h=[];switch(e.whammyBarType){case L.Custom:h=a;break;case L.Dive:switch(e.whammyStyle){case f.Default:h=a;break;case f.Gradual:h.push(new Pe(0,a[0].value)),h.push(new Pe(Pe.MaxPosition,a[1].value));break;case f.Fast:const e=Math.min(n,xe.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case L.Dip:switch(e.whammyStyle){case f.Default:h=a;break;case f.Gradual:h.push(new Pe(0,a[0].value)),h.push(new Pe(Pe.MaxPosition/2|0,a[1].value)),h.push(new Pe(Pe.MaxPosition,a[2].value));break;case f.Fast:const e=Math.min(n,xe.millisToTicks(this._settings.player.songBookDipDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!0,[a[0].value,a[1].value,a[2].value],e,o)}break;case L.Hold:case L.Predive:h=a;break;case L.PrediveDive:switch(e.whammyStyle){case f.Default:h=a;break;case f.Gradual:h.push(new Pe(0,a[0].value)),h.push(new Pe(Pe.MaxPosition/2|0,a[0].value)),h.push(new Pe(Pe.MaxPosition,a[1].value));break;case f.Fast:const e=Ns.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,s,0|e);const i=Math.min(n,xe.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],i,o)}}this.generateWhammyOrBend(t,n,h,o)}generateWhammyOrBend(e,t,i,s){const a=t/Pe.MaxPosition;for(let t=0;t<i.length-1;t++){const r=i[t],n=i[t+1],o=Ns.getPitchWheel(r.value),h=Ns.getPitchWheel(n.value),l=a*(n.offset-r.offset),c=e+a*r.offset;this.generateBendValues(c,l,o,h,s)}}generateBendValues(e,t,i,s,a){const r=xe.ticksToMillis(t,this._currentTempo),n=Math.abs(s-i)/Ns.PitchValuePerSemitone,o=Math.max(Ns.MinBreakpointsPerSemitone*n,r/Ns.MillisecondsPerBreakpoint),h=t/o,l=(s-i)/o;for(let t=0;t<o;t++)a(0|e,Math.round(i)),i+=l,e+=h;i<s&&a(0|e,s)}generateTrill(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=xe.toTicks(e.trillSpeed),l=!0,c=t,d=t+i.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:s,a,r),l=!l,c+=h}generateTremoloPicking(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track;let o=xe.toTicks(e.beat.tremoloSpeed),h=t;const l=t+i.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,s,a,r),h+=o}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType!==y.None){let i=0,s=0;for(const t of e.notes)t.isTieDestination||(i|=1<<t.string-1,s++);if(e.notes.length>0){let a=0;const r=e.brushDuration/(s-1)|0;for(let s=0;s<e.voice.bar.staff.tuning.length;s++){let n=e.brushType===y.ArpeggioDown||e.brushType===y.BrushDown?s:t.length-1-s;0!=(i&1<<n)&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,i){switch(t.type){case d.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&(0|t.value)),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&(0|t.value));break;case d.Balance:let s=Ns.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.PanCoarse,s),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.PanCoarse,s);break;case d.Volume:let a=Ns.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.VolumeCoarse,a)}}prepareSingleBeat(e){let t=-1,i=-1,s=e;for(;s&&(-1===t||-1===i);){for(const s of e.automations)switch(s.type){case d.Instrument:i=s.value;break;case d.Tempo:t=s.value}s=s.previousBeat}const a=e.voice.bar.staff.track,r=e.voice.bar.masterBar;-1===t&&(t=r.score.tempo),-1===i&&(i=a.playbackInfo.program);const n=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,r.timeSignatureNumerator,r.timeSignatureDenominator),this._handler.addTempo(0,t);let o=Ns.toChannelShort(n);this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,te.VolumeCoarse,o)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,-e.beat.playbackStart,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Ns.DefaultDurationDead=30,Ns.DefaultDurationPalmMute=80,Ns.PitchBendRangeInSemitones=16,Ns.PitchValuePerSemitone=Ut.DefaultPitchWheel/Ns.PitchBendRangeInSemitones,Ns.MinBreakpointsPerSemitone=6,Ns.MillisecondsPerBreakpoint=150;class xs{constructor(){this.startTick=0,this.endTick=0}}class Ps{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}get scale(){return this.renderer.scale}doLayout(){}paint(e,t,i){}}class Es extends Ps{constructor(e=0,t=0){super(e,t),this.nextGlyph=null,this.previousGlyph=null}}class Cs extends Es{constructor(e,t,i,s){super(e,t),this.glyphScale=0,this.glyphScale=i,this.symbol=s}paint(e,t,i){i.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale*this.scale,this.symbol,!1)}}class Fs extends Cs{constructor(e,t,i,s){super(e,t,s?Fs.GraceScale:1,Fs.getSymbol(i)),this._isGrace=s,this._duration=i}paint(e,t,i){let s=this._isGrace?this.scale:0;i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this.symbol,!1)}doLayout(){let e=(this._isGrace?Fs.GraceScale:1)*this.scale;switch(this._duration){case S.QuadrupleWhole:this.width=14*e;break;case S.DoubleWhole:case S.Whole:this.width=14*(this._isGrace?Fs.GraceScale:1)*this.scale;break;default:this.width=Fs.QuarterNoteHeadWidth*(this._isGrace?Fs.GraceScale:1)*this.scale}this.height=Fs.NoteHeadHeight*e}static getSymbol(e){switch(e){case S.QuadrupleWhole:return E.NoteheadDoubleWholeSquare;case S.DoubleWhole:return E.NoteheadDoubleWhole;case S.Whole:return E.NoteheadWhole;case S.Half:return E.NoteheadHalf;default:return E.NoteheadBlack}}}Fs.GraceScale=.75,Fs.NoteHeadHeight=8,Fs.QuarterNoteHeadWidth=9;class Ls extends Cs{constructor(e,t,i,s,a){super(e,t,a?Fs.GraceScale:1,Ls.getSymbol(i,s,a))}doLayout(){this.width=0}static getSymbol(e,t,i){if(i&&(e=S.Eighth),t===U.Up)switch(e){case S.Eighth:return E.FlagEighthUp;case S.Sixteenth:return E.FlagSixteenthUp;case S.ThirtySecond:return E.FlagThirtySecondUp;case S.SixtyFourth:return E.FlagSixtyFourthUp;case S.OneHundredTwentyEighth:return E.FlagOneHundredTwentyEighthUp;case S.TwoHundredFiftySixth:return E.FlagTwoHundredFiftySixthUp;default:return E.FlagEighthUp}switch(e){case S.Eighth:return E.FlagEighthDown;case S.Sixteenth:return E.FlagSixteenthDown;case S.ThirtySecond:return E.FlagThirtySecondDown;case S.SixtyFourth:return E.FlagSixtyFourthDown;case S.OneHundredTwentyEighth:case S.TwoHundredFiftySixth:return E.FlagOneHundredTwentyEighthDown;default:return E.FlagEighthDown}}}Ls.FlagWidth=11;class Ms extends Ps{constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}get onTimeX(){return this.onNotes.x+this.onNotes.centerX}registerLayoutingInfo(e){let t=this.onTimeX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Ms.GraceBeatPadding*this.renderer.scale);let i=this.onNotes.width-this.onNotes.centerX;const s=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(s&&s.hasFlag||this.beat.graceType!==_.None)&&(i+=Ls.FlagWidth*this.scale*(this.beat.graceType!==_.None?Fs.GraceScale:1));for(const e of this.ties)i+=e.width;this.beat.graceType!==_.None&&(i+=Ms.GraceBeatPadding*this.renderer.scale),e.addBeatSpring(this.beat,t,i),e.setPreBeatSize(this.beat,this.preNotes.width),e.setOnBeatSize(this.beat,this.onNotes.width),e.setBeatCenterX(this.beat,this.onNotes.centerX)}applyLayoutingInfo(e){let t=e.getBeatCenterX(this.beat)-this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Ms.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=S.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case S.OneHundredTwentyEighth:case S.TwoHundredFiftySixth:this.minWidth+=10*this.scale}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){for(let e of this.ties)e.doLayout();this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return"b"+e.id}paint(e,t,i){if(this.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;i.beginGroup(Ms.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,i),this.onNotes.paint(e+this.x,t+this.y,i);let s=e-this.voiceContainer.x-this.renderer.x,a=t-this.voiceContainer.y-this.renderer.y;for(let e=0,t=this.ties.length;e<t;e++){let t=this.ties[e];t.renderer=this.renderer,t.paint(s,a,i)}i.endGroup()}buildBoundingsLookup(e,t,i,s){let a=new cs;a.beat=this.beat,a.visualBounds=new ht,a.visualBounds.x=t+this.x+this.onNotes.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.onNotes.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new ht,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,s&&(a.visualBounds.x=t+this.x,a.realBounds.x=a.visualBounds.x),e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,i+this.y)}}Ms.GraceBeatPadding=3;class Is{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new io}causeIssue(){return this.settings=null,!0}}class Ds{constructor(e){this.bounds=null,this.beat=e}}class As extends ce{constructor(t,i){super(e.AlphaTabErrorType.General,t),this.xhr=i,Object.setPrototypeOf(this,As.prototype)}}class Rs{static loadScoreAsync(e,t,i,s){let a=new XMLHttpRequest;a.open("GET",e,!0,null,null),a.responseType="arraybuffer",a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){let e=a.response;if(200===a.status||0===a.status&&e)try{let e=a.response,i=new Uint8Array(e),r=Rs.loadScoreFromBytes(i,s);t(r)}catch(e){i(e)}else 0===a.status?i(new As("You are offline!!\n Please Check Your Network.",a)):404===a.status?i(new As("Requested URL not found.",a)):500===a.status?i(new As("Internel Server Error.",a)):"parsererror"===a.statusText?i(new As("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?i(new As("Request Time out.",a)):i(new As("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Gi);let i=to.buildImporters();Fe.debug("ScoreLoader","Loading score from "+e.length+" bytes using "+i.length+" importers",null);let s=null,a=ot.fromBuffer(e);for(let e of i){a.reset();try{Fe.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),s=e.readScore(),Fe.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof ke))throw Fe.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;Fe.debug("ScoreLoader",e.name+" does not support the file")}}if(s)return s;throw Fe.error("ScoreLoader","No compatible importer found for file"),new ke("No compatible importer found for file")}}class Os{constructor(e){this.mouseEvent=e}get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){let t=e.element,i=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-i}getY(e){let t=e.element,i=t.getBoundingClientRect().top+t.ownerDocument.defaultView.pageYOffset;return this.mouseEvent.pageY-i}preventDefault(){this.mouseEvent.preventDefault()}}class Gs{constructor(e){this._resizeListeners=0,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Os(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Os(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Os(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&Gs.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,Gs.resizeObserver.value.unobserve(this.element))}}}get top(){return parseFloat(this.element.style.top)}set top(e){this.element.style.top=e+"px"}get left(){return parseFloat(this.element.style.top)}set left(e){this.element.style.left=e+"px"}get width(){return this.element.offsetWidth}set width(e){this.element.style.width=e+"px"}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollTop=e}get scrollTop(){return this.element.scrollLeft}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?e+"px":"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}stopAnimation(){this.element.style.transition="none"}transitionToX(e,t){this.element.style.transition="all 0s linear",this.element.style.transitionDuration=e+"ms",this.element.style.left=t+"px"}appendChild(e){this.element.appendChild(e.element)}clear(){this.element.innerHTML=""}}Gs.resizeObserver=new Ee((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Vs{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new wi,this._family=e}checkForFontAvailability(){if(to.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{e++,Fe.warning("Rendering",`Could not load font '${this._family}' within ${5*e} seconds`,null)}),5e3);Fe.debug("Font","Start checking for font availablility: "+this._family),Fe.debug("Font",`[${this._family}] Font API available`);let i=()=>{document.fonts.load("1em "+this._family).then((()=>(Fe.debug("Font",`[${this._family}] Font API signaled loaded`),document.fonts.check("1em "+this._family)?(Fe.debug("Rendering",`[${this._family}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._family)):(Fe.debug("Font",`[${this._family}] Font API loaded reported, but font not available, checking later again`,null),window.setTimeout((()=>{i()}),250)),!0)))};i()}}class Hs{constructor(e){this._writePosition=0,this._readPosition=0,this.count=0,this._buffer=new Float32Array(e)}clear(){this._readPosition=0,this._writePosition=0,this.count=0,this._buffer=new Float32Array(this._buffer.length)}write(e,t,i){let s=0;i>this._buffer.length-this.count&&(i=this._buffer.length-this.count);const a=Math.min(this._buffer.length-this._writePosition,i);return this._buffer.set(e.subarray(t,t+a),this._writePosition),this._writePosition+=a,this._writePosition%=this._buffer.length,s+=a,s<i&&(this._buffer.set(e.subarray(t+s,t+s+i-s),this._writePosition),this._writePosition+=i-s,s=i),this.count+=s,s}read(e,t,i){i>this.count&&(i=this.count);let s=0;const a=Math.min(this._buffer.length-this._readPosition,i);return e.set(this._buffer.subarray(this._readPosition,this._readPosition+a),t),s+=a,this._readPosition+=a,this._readPosition%=this._buffer.length,s<i&&(e.set(this._buffer.subarray(this._readPosition,this._readPosition+i-s),t+s),this._readPosition+=i-s,s=i),this.count-=s,s}}class Ws{constructor(){this._context=null,this._buffer=null,this._source=null,this._audioNode=null,this._outputBuffer=new Float32Array(0),this.ready=new Si,this.samplesPlayed=new wi,this.sampleRequest=new Si}get sampleRate(){return this._context?this._context.sampleRate:Ws.PreferredSampleRate}open(){this.patchIosSampleRate(),this._circularBuffer=new Hs(Ws.BufferSize*Ws.BufferCount),this._context=this.createAudioContext();let e=this._context;if("suspended"===e.state){let t=()=>{e.resume(),window.setTimeout((()=>{"running"===e.state&&(document.body.removeEventListener("touchend",t,!1),document.body.removeEventListener("click",t,!1))}),0)};document.body.addEventListener("touchend",t,!1),document.body.addEventListener("click",t,!1)}this.ready.trigger()}activate(){this._context||(this._context=this.createAudioContext()),this._context.resume()}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||0!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,Ws.PreferredSampleRate),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),i.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in to.globalThis)return new AudioContext;if("webkitAudioContext"in to.globalThis)return new webkitAudioContext;throw new ce(e.AlphaTabErrorType.General,"AudioContext not found")}play(){let e=this._context;e&&("suspended"!==e.state&&"interrupted"!==e.state||e.resume(),this._buffer=e.createBuffer(2,4096,e.sampleRate),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(){this._source&&(this._source.stop(0),this._source.disconnect(0)),this._source=null,this._audioNode&&this._audioNode.disconnect(0),this._audioNode=null}addSamples(e){this._circularBuffer.write(e,0,e.length)}resetSamples(){this._circularBuffer.clear()}requestBuffers(){if(this._circularBuffer.count<20480&&this.sampleRequest)for(let e=0;e<5;e++)this.sampleRequest.trigger()}generateSound(e){let t=e.outputBuffer.getChannelData(0),i=e.outputBuffer.getChannelData(1),s=t.length+i.length,a=this._outputBuffer;a.length!=s&&(a=new Float32Array(s),this._outputBuffer=a),this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let r=0;for(let e=0;e<t.length;e++)t[e]=a[r++],i[e]=a[r++];this.samplesPlayed.trigger(t.length),this.requestBuffers()}}Ws.BufferSize=4096,Ws.BufferCount=10,Ws.PreferredSampleRate=44100;class Us{constructor(e,t,i){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Q.Paused,this._masterVolume=0,this._metronomeVolume=0,this._countInVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._midiEventsPlayedFilter=[],this.ready=new Si,this.readyForPlayback=new Si,this.finished=new Si,this.soundFontLoaded=new Si,this.soundFontLoadFailed=new wi,this.midiLoaded=new wi,this.midiLoadFailed=new wi,this.stateChanged=new wi,this.positionChanged=new wi,this.midiEventsPlayed=new wi,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Q.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open();try{let e=new Blob(["importScripts('"+t+"')"]);this._synth=new Worker(URL.createObjectURL(e))}catch(e){try{this._synth=new Worker(t)}catch(e){return void Fe.error("AlphaSynth","Failed to create WebWorker: "+e)}}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:i}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return Fe.logLevel}set logLevel(e){Fe.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Ut.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ut.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ut.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=ci.clamp(e,Ut.MinPlaybackSpeed,Ut.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}destroy(){this._synth.terminate()}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:as.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,i){Fe.debug("AlphaSynth","Start loading Soundfont from url "+e);let s=new XMLHttpRequest;s.open("GET",e,!0,null,null),s.responseType="arraybuffer",s.onload=e=>{let i=new Uint8Array(s.response);this.loadSoundFont(i,t)},s.onerror=e=>{Fe.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new As(e.message,s))},s.onprogress=e=>{Fe.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),i(new so(e.loaded,e.total))},s.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:as.midiFileToJsObject(e)})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Ut.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.ready":this._workerIsReady=!0,this.checkReady();break;case"alphaSynth.readyForPlayback":this._workerIsReadyForPlayback=!0,this.checkReadyForPlayback();break;case"alphaSynth.positionChanged":this._timePosition=t.currentTime,this._tickPosition=t.currentTick,this.positionChanged.trigger(new Jt(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new _i(t.events.map(as.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new qt(t.state,t.stopped));break;case"alphaSynth.finished":this.finished.trigger();break;case"alphaSynth.soundFontLoaded":this.soundFontLoaded.trigger();break;case"alphaSynth.soundFontLoadFailed":this.soundFontLoadFailed.trigger(t.error);break;case"alphaSynth.midiLoaded":this.checkReadyForPlayback(),this.midiLoaded.trigger(new Jt(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.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 zs{constructor(e,t){if(this._width=0,this.boundsLookup=null,this.preRender=new wi,this.partialRenderFinished=new wi,this.renderFinished=new wi,this.postRenderFinished=new Si,this.error=new wi,this._api=e,t.core.scriptFile){try{let e=`importScripts('${t.core.scriptFile}')`,i=new Blob([e]);this._worker=new Worker(URL.createObjectURL(i))}catch(e){try{this._worker=new Worker(t.core.scriptFile)}catch(t){return void Fe.error("Rendering","Failed to create WebWorker: "+e)}}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}else Fe.error("Rendering","Could not detect alphaTab script file, cannot initialize renderer")}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=as.settingsToJsObject(e);return t.delete("player"),t}render(){this._worker.postMessage({cmd:"alphaTab.render"})}resizeRender(){this._worker.postMessage({cmd:"alphaTab.resizeRender"})}get width(){return this._width}set width(e){this._width=e,this._worker.postMessage({cmd:"alphaTab.setWidth",width:e})}handleWorkerMessage(e){let t=e.data;switch(t.cmd){case"alphaTab.preRender":this.preRender.trigger(t.resize);break;case"alphaTab.partialRenderFinished":this.partialRenderFinished.trigger(t.result);break;case"alphaTab.renderFinished":this.renderFinished.trigger(t.result);break;case"alphaTab.postRenderFinished":this.boundsLookup=gs.fromJson(t.boundsLookup,this._api.score),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){let i=as.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:i,trackIndexes:t,fontSizes:os.FontSizeLookupTables})}}class Xs{constructor(e,t,i,s){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=i,this.selectionWrapper=s}}class Ys{constructor(e){this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this.rootContainerBecameVisible=new Si,this.canRenderChanged=new Si,e.classList.add("alphaTab"),this.rootContainer=new Gs(e),this.areWorkersSupported="Worker"in window,to.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(to.bravuraFontChecker.checkForFontAvailability(),!to.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(Fe.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){os.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}onElementVisibilityChanged(e){for(const t of e)if(t.isIntersecting){const e=t.target;e===this.rootContainer.element?(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element)):"svg"in e.dataset&&(this.replacePlaceholder(e,e.dataset.svg),this._intersectionObserver.unobserve(e))}}createWorkerRenderer(){return new zs(this._api,this._api.settings)}initialize(t,i){let s;this._api=t,s=i instanceof Gi?i:as.jsObjectToSettings(i);let a=this.getDataAttributes();Oi.fromJson(s,a),s.notation.notationMode===e.NotationMode.SongBook&&s.setSongBookModeSettings(),t.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";let r=t.container;s.core.tex&&(this._contents=r.element.innerHTML,r.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.family)){let t=new Vs(e.family);this._fontCheckers.set(e.family,t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){let e=document.createElement("div");return e.className="at-surface",e.style.fontSize="0",e.style.overflow="hidden",e.style.lineHeight="0",new Gs(e)}triggerEvent(e,t,i=null,s){let a=e.element;t="alphaTab."+t;let r=document.createEvent("CustomEvent"),n=s?s.mouseEvent:null;if(r.initCustomEvent(t,!1,!1,i),n&&(r.originalEvent=n),a.dispatchEvent(r),window&&"jQuery"in window){let e=window.jQuery,s=[];s.push(i),n&&s.push(n),e(a).trigger(t,s)}}load(e,t,i){if(e instanceof qe)return t(e),!0;if(e instanceof ArrayBuffer){let i=new Uint8Array(e);return t(Rs.loadScoreFromBytes(i,this._api.settings)),!0}return e instanceof Uint8Array?(t(Rs.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Rs.loadScoreAsync(e,t,i,this._api.settings),!0)}loadSoundFont(e,t){return!!this._api.player&&(e instanceof ArrayBuffer?(this._api.player.loadSoundFont(new Uint8Array(e),t),!0):e instanceof Uint8Array?(this._api.player.loadSoundFont(e,t),!0):"string"==typeof e&&(this._api.loadSoundFontFromUrl(e,t),!0))}initialRender(){this._api.renderer.preRender.on((e=>{this._totalResultCount=0}));const e=()=>{var e;this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,null!==(e=this._initialTrackIndexes)&&void 0!==e?e:void 0),this._initialTrackIndexes=null):this._file&&Rs.loadScoreAsync(this._file,(e=>{var t;this._api.renderScore(e,null!==(t=this._initialTrackIndexes)&&void 0!==t?t:void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){let t=this._api.container.element.ownerDocument;to.createStyleElement(t,e.core.fontDirectory)}parseTracks(e){if(!e)return[];let t=[];if("string"==typeof e)try{if("all"===e)return[-1];e=JSON.parse(e)}catch(t){e=[0]}if("number"==typeof e)t.push(e);else if("length"in e){let i=e.length,s=e;for(let e=0;e<i;e++){let i=s[e],a=0;a="number"==typeof i?i:"index"in i?i.index:parseInt(i.toString()),(a>=0||-1===a)&&t.push(a)}}else"index"in e&&t.push(e.index);return t}getDataAttributes(){let e=new Map,t=this._api.container.element;if(t.dataset)for(let i of Object.keys(t.dataset)){let s=t.dataset[i];try{let e=s;s=JSON.parse(e)}catch(e){""===s&&(s=null)}e.set(i,s)}else for(let i=0;i<t.attributes.length;i++){let s=t.attributes.item(i),a=s.nodeName;if(a.startsWith("data-")){let t=a.substr(5).split("-"),i=t[0];for(let e=1;e<t.length;e++)i+=t[e].substr(0,1).toUpperCase()+t[e].substr(1);let r=s.nodeValue;try{r=JSON.parse(r)}catch(e){""===r&&(r=null)}e.set(i,r)}}return e}beginAppendRenderResults(e){let t=this._api.canvasElement.element;if(e){let i=e.renderResult;if("string"==typeof i){let s;this._totalResultCount<t.childElementCount?s=t.childNodes.item(this._totalResultCount):(s=document.createElement("div"),t.appendChild(s)),s.style.width=e.width+"px",s.style.height=e.height+"px",s.style.display="inline-block",this._api.settings.core.enableLazyLoading?(s.dataset.svg=i,this._intersectionObserver.observe(s)):this.replacePlaceholder(s,i)}else this._totalResultCount<t.childElementCount?t.replaceChild(e.renderResult,t.childNodes.item(this._totalResultCount)):t.appendChild(e.renderResult);this._totalResultCount++}else for(;t.childElementCount>this._totalResultCount;)t.removeChild(t.lastChild)}replacePlaceholder(e,t){var i;if("string"==typeof e.outerHTML)e.outerHTML=t;else{const s=document.createElement("div");s.innerHTML=t,null===(i=e.parentNode)||void 0===i||i.replaceChild(s.firstChild,e)}}createWorkerPlayer(){let e="ScriptProcessorNode"in window,t=to.scriptFile;if(!t)return Fe.error("Player","alphaTab script file could not be detected, player cannot initialize"),null;let i=null;return e&&(Fe.debug("Player","Will use webworkers for synthesizing and web audio api for playback"),i=new Us(new Ws,t,this._api.settings.core.logLevel)),i?i.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):Fe.error("Player","Player requires webworkers and web audio api, browser unsupported",null),i}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e){let t=this._api.container.element.getElementsByClassName(e);for(let e=0;e<t.length;e++)t.item(e).classList.add("at-highlight")}removeHighlights(){let e=this._api.container.element.getElementsByClassName("at-highlight");for(;e.length>0;)e.item(0).classList.remove("at-highlight")}destroyCursors(){let e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){let e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");let i=document.createElement("div");i.classList.add("at-selection");let s=document.createElement("div");s.classList.add("at-cursor-bar");let a=document.createElement("div");return a.classList.add("at-cursor-beat"),e.style.position="relative",e.style.textAlign="left",t.style.position="absolute",t.style.zIndex="1000",t.style.display="inline",t.style.pointerEvents="none",i.style.position="absolute",s.style.position="absolute",a.style.position="absolute",a.style.transition="all 0s linear",e.insertBefore(t,e.firstChild),t.appendChild(i),t.appendChild(s),t.appendChild(a),new Xs(new Gs(t),new Gs(s),new Gs(a),new Gs(i))}getOffset(e,t){let i=t.element,s=i.getBoundingClientRect(),a=s.top+i.ownerDocument.defaultView.pageYOffset,r=s.left+i.ownerDocument.defaultView.pageXOffset;if(e){let t=e.element,i=t.nodeName.toLowerCase();if("html"!==i&&"body"!==i){let i=this.getOffset(null,e);a=a+t.scrollTop-i.y,r=r+t.scrollLeft-i.x}}let n=new ht;return n.x=r,n.y=a,n.w=s.width,n.h=s.height,n}getScrollContainer(){let e="string"==typeof this._api.settings.player.scrollElement?document.querySelector(this._api.settings.player.scrollElement):this._api.settings.player.scrollElement,t=e.nodeName.toLowerCase();if("html"===t||"body"===t)if("scrollingElement"in document)e=document.scrollingElement;else{e=-1!==navigator.userAgent.indexOf("WebKit")?document.body:document.documentElement}return new Gs(e)}createSelectionElement(){let e=document.createElement("div");return e.style.position="absolute",new Gs(e)}scrollToY(e,t,i){this.internalScrollToY(e.element,t,i)}scrollToX(e,t,i){this.internalScrollToX(e.element,t,i)}internalScrollToY(e,t,i){let s=e.scrollTop,a=t-s,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/i,1);e.scrollTop=s+a*h|0,o<i&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}internalScrollToX(e,t,i){let s=e.scrollLeft,a=t-s,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/i,1);e.scrollLeft=s+a*h|0,o<i&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}class qs extends class{constructor(e,t){this._startTime=0,this._trackIndexes=null,this.score=null,this.tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=Q.Paused,this._currentBeat=null,this._previousStateForCursor=Q.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new wi,this._beatMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new wi,this.beatMouseMove=new wi,this.beatMouseUp=new wi,this.scoreLoaded=new wi,this.resize=new wi,this.renderStarted=new wi,this.renderFinished=new wi,this.postRenderFinished=new Si,this.error=new wi,this.playerReady=new Si,this.playerFinished=new Si,this.soundFontLoaded=new Si,this.midiLoad=new wi,this.midiLoaded=new wi,this.playerStateChanged=new wi,this.playerPositionChanged=new wi,this.midiEventsPlayed=new wi,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),Fe.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.container.resize.on(to.throttle((()=>{this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle)),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&to.getRenderEngineFactory(this.settings).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new fs(this.settings);let i=new Is;i.oldWidth=this.renderer.width,i.newWidth=0|this.container.width,i.settings=this.settings,this.onResize(i),this.renderer.preRender.on(this.onRenderStarted.bind(this)),this.renderer.renderFinished.on((e=>{this.onRenderFinished(e)})),this.renderer.postRenderFinished.on((()=>{let e=Date.now()-this._startTime;Fe.debug("rendering","Rendering completed in "+e+"ms"),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialRenderFinished.on(this.appendRenderResult.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.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?this.setupPlayer():this.destroyPlayer()}load(e,t){try{return this.uiFacade.load(e,(e=>{this.renderScore(e,t)}),(e=>{this.onError(e)}))}catch(e){return this.onError(e),!1}}renderScore(e,t){let i=[];if(t)if(0===t.length)e.tracks.length>0&&i.push(e.tracks[0]);else if(1===t.length&&-1===t[0])for(let t of e.tracks)i.push(t);else for(let s of t)s>=0&&s<=e.tracks.length&&i.push(e.tracks[s]);else e.tracks.length>0&&i.push(e.tracks[0]);this.internalRenderTracks(e,i)}renderTracks(t){if(t.length>0){let i=t[0].score;for(let s of t)if(s.score!==i)return void this.onError(new ce(e.AlphaTabErrorType.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(i,t)}}internalRenderTracks(e,t){if(e!==this.score){fe.applyPitchOffsets(this.settings,e),this.score=e,this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.render()}}triggerResize(){if(this.container.isVisible){let e=new Is;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 Fe.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{Fe.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&&!e.renderResult||this.uiFacade.beginAppendRenderResults(e)}tex(e,t){try{let i=new tt,s=ot.fromString(e);i.init(s,this.settings);let a=i.readScore();this.renderScore(a,t)}catch(e){this.onError(e)}}loadSoundFont(e,t=!1){return!!this.player&&this.uiFacade.loadSoundFont(e,t)}resetSoundFonts(){this.player&&this.player.resetSoundFonts()}render(){this.renderer&&(this.uiFacade.canRender?(this.renderer.width=this.container.width,this.renderer.renderScore(this.score,this._trackIndexes)):this.uiFacade.canRenderChanged.on((()=>this.render())))}get isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Q.Paused}get masterVolume(){return this.player?this.player.masterVolume:0}set masterVolume(e){this.player&&(this.player.masterVolume=e)}get metronomeVolume(){return this.player?this.player.metronomeVolume:0}set metronomeVolume(e){this.player&&(this.player.metronomeVolume=e)}get countInVolume(){return this.player?this.player.countInVolume:0}set countInVolume(e){this.player&&(this.player.countInVolume=e)}get midiEventsPlayedFilter(){return this.player?this.player.midiEventsPlayedFilter:[]}set midiEventsPlayedFilter(e){this.player&&(this.player.midiEventsPlayedFilter=e)}get tickPosition(){return this.player?this.player.tickPosition:0}set tickPosition(e){this.player&&(this.player.tickPosition=e)}get timePosition(){return this.player?this.player.timePosition:0}set timePosition(e){this.player&&(this.player.timePosition=e)}get playbackRange(){return this.player?this.player.playbackRange:null}set playbackRange(e){this.player&&(this.player.playbackRange=e,this.settings.player.enableCursor&&this.updateSelectionCursor(e))}get playbackSpeed(){return this.player?this.player.playbackSpeed:0}set playbackSpeed(e){this.player&&(this.player.playbackSpeed=e)}get isLooping(){return!!this.player&&this.player.isLooping}set isLooping(e){this.player&&(this.player.isLooping=e)}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null,this.destroyCursors())}setupPlayer(){this.player||(this.player=this.uiFacade.createWorkerPlayer(),this.player&&(this.player.ready.on((()=>{this.loadMidiForScore()})),this.player.readyForPlayback.on((()=>{if(this.onPlayerReady(),this.tracks)for(let e of this.tracks){let t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.settings.player.enableCursor?this.setupCursors():this.destroyCursors()))}loadMidiForScore(){if(!this.player||!this.score||!this.player.isReady)return;Fe.debug("AlphaTab","Generating Midi");let e=new Ti,t=new bs(e),i=new Ns(this.score,this.settings,t);i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e)}changeTrackVolume(e,t){if(this.player)for(let i of e)this.player.setChannelVolume(i.playbackInfo.primaryChannel,t),this.player.setChannelVolume(i.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let i of e)this.player.setChannelSolo(i.playbackInfo.primaryChannel,t),this.player.setChannelSolo(i.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let i of e)this.player.setChannelMute(i.playbackInfo.primaryChannel,t),this.player.setChannelMute(i.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;let t=new Ti,i=new bs(t);new Ns(e.voice.bar.staff.track.score,this.settings,i).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new Ti,i=new bs(t);new Ns(e.beat.voice.bar.staff.track.score,this.settings,i).generateSingleNote(e),this.player.playOneTimeMidiFile(t)}destroyCursors(){this._cursorWrapper&&(this.uiFacade.destroyCursors(),this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=Q.Paused)}setupCursors(){let e=this.uiFacade.createCursors();e&&(this._cursorWrapper=e.cursorWrapper,this._barCursor=e.barCursor,this._beatCursor=e.beatCursor,this._selectionWrapper=e.selectionWrapper,this._previousTick=0,this._playerState=Q.Paused,this.renderer.postRenderFinished.on((()=>{this.cursorUpdateTick(this._previousTick,!1)})),this.player&&(this.player.positionChanged.on((e=>{this._previousTick=e.currentTick,this.uiFacade.beginInvoke((()=>{this.cursorUpdateTick(e.currentTick,!1)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===Q.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getMasterBarStart(e.voice.bar.masterBar)+e.playbackStart)}}))))}cursorUpdateTick(e,t=!1){this.uiFacade.beginInvoke((()=>{let i=this._tickCache;if(i){let s=this.tracks;if(s.length>0){let a=i.findBeat(s,e);a&&this.cursorUpdateBeat(a.currentBeat,a.nextBeat,a.duration,t,a.beatsToHighlight)}}}))}cursorUpdateBeat(t,i,s,a,r=null){if(!t)return;let n=this.renderer.boundsLookup;if(!n)return;let o=this._currentBeat,h=this._previousCursorCache,l=this._previousStateForCursor;if(this._currentBeat=t,this._previousCursorCache=n,this._previousStateForCursor=this._playerState,t===o&&n===h&&l===this._playerState)return;let c=this._barCursor,d=this._beatCursor,u=n.findBeat(t);if(!u)return;let p=u.barBounds.masterBarBounds,g=p.visualBounds;if(c&&(c.top=g.y,c.left=g.x,c.width=g.w,c.height=g.h),d&&(d.stopAnimation(),d.top=g.y,d.left=u.visualBounds.x,d.height=g.h),this.uiFacade.removeHighlights(),this._playerState===Q.Playing||a){if(s/=this.playbackSpeed,!a){if(r)for(let e of r){let t=Ms.getGroupId(e);this.uiFacade.highlightElements(t)}let e=p.visualBounds.x+p.visualBounds.w;if(i&&(i.voice.bar.index===t.voice.bar.index||i.voice.bar.index===t.voice.bar.index+1)){let t=n.findBeat(i);t&&t.barBounds.masterBarBounds.staveGroupBounds===p.staveGroupBounds&&(e=t.visualBounds.x)}d&&this.uiFacade.beginInvoke((()=>{d.transitionToX(s,e)}))}if(!this._beatMouseDown&&this.settings.player.scrollMode!==e.ScrollMode.Off){let t=this.uiFacade.getScrollContainer(),i=to.getLayoutEngineFactory(this.settings).vertical,s=this.settings.player.scrollMode,a=this.uiFacade.getOffset(t,this.container);if(i)switch(s){case e.ScrollMode.Continuous:let i=a.y+p.realBounds.y+this.settings.player.scrollOffsetY;i!==this._lastScroll&&(this._lastScroll=i,this.uiFacade.scrollToY(t,i,this.settings.player.scrollSpeed));break;case e.ScrollMode.OffScreen:let s=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(p.visualBounds.y+p.visualBounds.h>=s||p.visualBounds.y<t.scrollTop){let e=p.realBounds.y+this.settings.player.scrollOffsetY;this._lastScroll=p.visualBounds.x,this.uiFacade.scrollToY(t,e,this.settings.player.scrollSpeed)}}else switch(s){case e.ScrollMode.Continuous:if(p.visualBounds.x!==this._lastScroll){let e=p.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=p.visualBounds.x,this.uiFacade.scrollToX(t,e,this.settings.player.scrollSpeed)}break;case e.ScrollMode.OffScreen:let i=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(p.visualBounds.x+p.visualBounds.w>=i||p.visualBounds.x<t.scrollLeft){let e=p.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=p.visualBounds.x,this.uiFacade.scrollToX(t,e,this.settings.player.scrollSpeed)}}}this.onPlayedBeatChanged(t)}}onPlayedBeatChanged(e){this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e)}onBeatMouseDown(e,t){this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Ds(t),this._selectionEnd=null),this._beatMouseDown=!0,this.beatMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseDown",t,e)}onBeatMouseMove(e,t){this.settings.player.enableUserInteraction&&(this._selectionEnd&&this._selectionEnd.beat===t||(this._selectionEnd=new Ds(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e)}onBeatMouseUp(e,t){if(this.settings.player.enableUserInteraction){if(this._selectionEnd){let e=this._selectionStart.beat.absolutePlaybackStart;if(this._selectionStart.beat.absolutePlaybackStart<e){let e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){let e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Q.Paused&&this.cursorUpdateBeat(this._selectionStart.beat,null,0,!1,[this._selectionStart.beat]),this.tickPosition=t+this._selectionStart.beat.playbackStart,this._selectionEnd&&this._selectionStart.beat!==this._selectionEnd.beat){let i=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),s=new xs;s.startTick=t+this._selectionStart.beat.playbackStart,s.endTick=i+this._selectionEnd.beat.playbackStart+this._selectionEnd.beat.playbackDuration-50,this.playbackRange=s}else this._selectionStart=null,this.playbackRange=null,this.cursorSelectRange(this._selectionStart,this._selectionEnd)}}this.beatMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseUp",t,e),this._beatMouseDown=!1}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this.tracks,e.startTick),i=this._tickCache.findBeat(this.tracks,e.endTick);if(t&&i){const e=new Ds(t.currentBeat),s=new Ds(i.currentBeat);this.cursorSelectRange(e,s)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{var t,i;if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let s=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(s,a))&&void 0!==i?i:null;r&&this.onBeatMouseDown(e,r)})),this.canvasElement.mouseMove.on((e=>{var t,i;if(!this._beatMouseDown)return;let s=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(s,a))&&void 0!==i?i:null;r&&this.onBeatMouseMove(e,r)})),this.canvasElement.mouseUp.on((e=>{var t,i;if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let s=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(s,a))&&void 0!==i?i:null;this.onBeatMouseUp(e,r)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){let i=this.renderer.boundsLookup;if(!i)return;let s=this._selectionWrapper;if(!s)return;if(s.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=i.findBeat(e.beat)),t.bounds||(t.bounds=i.findBeat(t.beat));let a=e.beat.absolutePlaybackStart;if(t.beat.absolutePlaybackStart<a){let i=e;e=t,t=i}let r=e.bounds.realBounds.x,n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staveGroupBounds!==t.bounds.barBounds.masterBarBounds.staveGroupBounds){let a=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.top=e.bounds.barBounds.masterBarBounds.visualBounds.y,h.left=r,h.width=o-r,h.height=e.bounds.barBounds.masterBarBounds.visualBounds.h,s.appendChild(h);let l=e.bounds.barBounds.masterBarBounds.staveGroupBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staveGroupBounds.index;for(let e=l;e<c;e++){let t=i.staveGroups[e],r=this.uiFacade.createSelectionElement();r.top=t.visualBounds.y,r.left=a,r.width=o-a,r.height=t.visualBounds.h,s.appendChild(r)}let d=this.uiFacade.createSelectionElement();d.top=t.bounds.barBounds.masterBarBounds.visualBounds.y,d.left=a,d.width=n-a,d.height=t.bounds.barBounds.masterBarBounds.visualBounds.h,s.appendChild(d)}else{let t=this.uiFacade.createSelectionElement();t.top=e.bounds.barBounds.masterBarBounds.visualBounds.y,t.left=r,t.width=n-r,t.height=e.bounds.barBounds.masterBarBounds.visualBounds.h,s.appendChild(t)}}onScoreLoaded(e){this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e)}onResize(e){this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e)}onRenderStarted(e){this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e)}onRenderFinished(e){this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e)}onPostRenderFinished(){this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null)}onError(e){Fe.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e)}onPlayerReady(){this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null)}onPlayerFinished(){this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null)}onSoundFontLoaded(){this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null)}onMidiLoad(e){this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e)}onMidiLoaded(e){this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e)}onPlayerStateChanged(e){this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e)}onPlayerPositionChanged(e){this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e)}onMidiEventsPlayed(e){this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e)}}{constructor(e,t){super(new Ys(e),t),this.soundFontLoad=new wi}tex(e,t){let i=this.uiFacade;super.tex(e,i.parseTracks(t))}print(t,i=null){let s=window.open("","","width=0,height=0"),a=s.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.LayoutMode.Horizontal?a.style.width="297mm":a.style.width="210mm",s.document.write("<!DOCTYPE html><html></head><body></body></html>"),s.document.body.appendChild(a);let r=void 0!==window.screenLeft?window.screenLeft:window.left,n=void 0!==window.screenTop?window.screenTop:window.top,o="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,h="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,l=a.offsetWidth+50,c=window.innerHeight,d=(o/2|0)-(l/2|0)+r,u=(h/2|0)-(c/2|0)+n;s.resizeTo(l,c),s.moveTo(d,u),s.focus();let p=as.jsObjectToSettings(as.settingsToJsObject(this.settings));p.core.enableLazyLoading=!1,p.core.useWorkers=!1,p.display.scale=.8,p.display.stretchForce=.8,Oi.fromJson(p,i);let g=new qs(a,p);g.renderer.postRenderFinished.on((()=>{g.canvasElement.height=-1,s.print()})),g.renderTracks(this.tracks)}downloadMidi(){if(!this.score)return;let e=new Ti,t=new bs(e);new Ns(this.score,this.settings,t).generate();let i=e.toBinary(),s=this.score.title?this.score.title+".mid":"File.mid",a=document.createElement("a");a.download=s;let r=new Blob([i],{type:"audio/midi"}),n=URL.createObjectURL(r);a.href=n,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a)}changeTrackMute(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(i,t)}changeTrackSolo(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(i,t)}changeTrackVolume(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(i,t)}trackIndexesToTracks(e){if(!this.score)return[];let t=[];if(1===e.length&&-1===e[0])for(let e of this.score.tracks)t.push(e);else for(let i of e)i>=0&&i<this.score.tracks.length&&t.push(this.score.tracks[i]);return t}loadSoundFontFromUrl(e,t){this.player&&this.player.loadSoundFontFromUrl(e,t,(e=>{this.soundFontLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"soundFontLoad",e)}))}}class Js{constructor(){this._initListeners=[]}exec(e,t,i){if("string"!=typeof t&&(i=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;let s=new jQuery(e),a=s.data("alphaTab");if("destroy"===t&&!a)return null;if("init"!==t&&!a)throw new Error("alphaTab not initialized");let r=this[t];if(r){let e=[s,a].concat(i);return r.apply(this,e)}return Fe.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,i){if(!t){t=new qs(e[0],i),e.data("alphaTab",t);for(let s of this._initListeners)s(e,t,i)}}destroy(e,t){e.removeData("alphaTab"),t.destroy()}print(e,t,i,s){t.print(i,s)}load(e,t,i,s){return t.load(i,s)}render(e,t){t.render()}renderScore(e,t,i,s){t.renderScore(i,s)}renderTracks(e,t,i){t.renderTracks(i)}invalidate(e,t){t.render()}tex(e,t,i,s){t.tex(i,s)}muteTrack(e,t,i,s){t.changeTrackMute(i,s)}soloTrack(e,t,i,s){t.changeTrackSolo(i,s)}trackVolume(e,t,i,s){t.changeTrackVolume(i,s)}loadSoundFont(e,t,i,s){t.loadSoundFont(i,s)}resetSoundFonts(e,t){t.resetSoundFonts()}pause(e,t){t.pause()}play(e,t){return t.play()}playPause(e,t){t.playPause()}stop(e,t){t.stop()}api(e,t){return t}player(e,t){return t.player}isReadyForPlayback(e,t){return t.isReadyForPlayback}playerState(e,t){return t.playerState}masterVolume(e,t,i){return"number"==typeof i&&(t.masterVolume=i),t.masterVolume}metronomeVolume(e,t,i){return"number"==typeof i&&(t.metronomeVolume=i),t.metronomeVolume}countInVolume(e,t,i){return"number"==typeof i&&(t.countInVolume=i),t.countInVolume}midiEventsPlayedFilter(e,t,i){return Array.isArray(i)&&(t.midiEventsPlayedFilter=i),t.midiEventsPlayedFilter}playbackSpeed(e,t,i){return"number"==typeof i&&(t.playbackSpeed=i),t.playbackSpeed}tickPosition(e,t,i){return"number"==typeof i&&(t.tickPosition=i),t.tickPosition}timePosition(e,t,i){return"number"==typeof i&&(t.timePosition=i),t.timePosition}loop(e,t,i){return"boolean"==typeof i&&(t.isLooping=i),t.isLooping}renderer(e,t){return t.renderer}score(e,t){return t.score}settings(e,t){return t.settings}tracks(e,t){return t.tracks}_oninit(e){this._initListeners.push(e)}static restore(e){new jQuery(e).empty().removeData("alphaTab")}}class Qs{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new me(255,255,255,255),this.lineWidth=1,this.font=new we("Arial",10,o.Plain),this.textAlign=C.Left,this.textBaseline=F.Top}beginRender(e,t){this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=F.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,i,s){i>0&&(this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${i}" height="${s}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,i,s){this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${i}" height="${s}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e},${t}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e},${t}`}quadraticCurveTo(e,t,i,s){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e},${t},${i},${s}`}bezierCurveTo(e,t,i,s,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e},${t},${i},${s},${a},${r}`}fillCircle(e,t,i){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-i},${t} A1,1 0 0,0 ${e+i},${t} A1,1 0 0,0 ${e-i},${t} z`,this.fill()}strokeCircle(e,t,i){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-i},${t} A1,1 0 0,0 ${e+i},${t} A1,1 0 0,0 ${e-i},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1!==this.lineWidth&&(e+=` stroke-width="${this.lineWidth}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,i){if(""===e)return;let s=`<text x="${0|t}" y="${0|i}" style="stroke: none; font:${this.font.toCssString(this.settings.display.scale)}" ${this.getSvgBaseLine()}`;"#000000"!==this.color.rgba&&(s+=` fill="${this.color.rgba}"`),this.textAlign!==C.Left&&(s+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),s+=`>${Qs.escapeText(e)}</text>`,this.buffer+=s}static escapeText(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}getSvgTextAlignment(e){switch(e){case C.Left:return"start";case C.Center:return"middle";case C.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case F.Top:return'dominant-baseline="hanging"';case F.Bottom:return'dominant-baseline="bottom"';case F.Middle:default:return""}}measureText(e){return e?os.measureString(e,this.font.family,this.font.size,this.font.style):0}onRenderFinished(){return null}beginRotate(e,t,i){this.buffer+='<g transform="translate('+e+" ,"+t+") rotate( "+i+')">'}endRotate(){this.buffer+="</g>"}}class js extends Qs{constructor(){super()}fillMusicFontSymbol(e,t,i,s,a=!1){s!==E.None&&this.fillMusicFontSymbolText(e,t,i,`&#${s};`,a)}fillMusicFontSymbols(e,t,i,s,a=!1){let r="";for(let e of s)e!==E.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a=!1){this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`,this.buffer+=1!==i?` style="font-size: ${100*i}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(C.Center)+'"'),this.buffer+=`>${s}</text></g>`}}class Ks{constructor(){this.isInAccolade=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(ie||(ie={}));class $s extends Ps{constructor(e,t){super(e,t),this.glyphs=null}get isEmpty(){return!this.glyphs||0===this.glyphs.length}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.renderer=this.renderer,i.doLayout(),e=Math.max(e,i.width)}this.width=e}addGlyph(e){this.glyphs||(this.glyphs=[]),this.renderer&&(e.renderer=this.renderer),this.glyphs.push(e)}paint(e,t,i){let s=this.glyphs;if(s&&0!==s.length)for(let a of s)a.paint(e+this.x,t+this.y,i)}}class Zs extends $s{constructor(){super(0,0),this.glyphs=[]}addGlyph(e){e.x=0===this.glyphs.length?0:this.glyphs[this.glyphs.length-1].x+this.glyphs[this.glyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class ea extends $s{constructor(e,t,i){super(e,t),this.voice=i,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.scale;let i=this.renderer.layoutingInfo.spaceToForce(e/t);this.scaleToForce(i)}scaleToForce(e){const t=this.renderer.scale;this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e)*t;let i=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,a=s.length;e<a;e++){let r=s[e];switch(r.beat.graceType){case _.None:r.x=i.get(r.beat.absoluteDisplayStart)*t-r.onTimeX;break;default:const a=r.beat.graceGroup.beats[0].absoluteDisplayStart,n=r.beat.graceGroup.id;if(r.beat.graceGroup.isComplete&&i.has(a)){r.x=i.get(a)*t-r.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(n),s=this.renderer.layoutingInfo.springs.get(a).preBeatWidth;r.x-=s,r.x-=e[r.beat.graceIndex].postSpringWidth,r.x+=e[r.beat.graceIndex].graceBeatWidth;const o=e[r.beat.graceGroup.beats.length-1];r.x-=o.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(n);const i=t[r.beat.graceIndex].postSpringWidth-t[r.beat.graceIndex].preSpringWidth;e>0?0===r.beat.graceIndex?r.x=s[e-1].x+s[e-1].width:r.x=s[e-1].x+t[r.beat.graceIndex-1].postSpringWidth-t[r.beat.graceIndex-1].preSpringWidth-i:r.x=-i}}if(e>0){let t=r.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===a-1){let e=this.width-s[s.length-1].x;r.scaleToWidth(e)}}}registerLayoutingInfo(e){e.updateVoiceSize(this.width);let t=this.beatGlyphs;for(let i of t)i.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let i of t)i.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){let t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,i){i.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let s=0,a=this.beatGlyphs.length;s<a;s++)this.beatGlyphs[s].paint(e+this.x,t+this.y,i)}}ea.KeySizeBeat="Beat",function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(se||(se={}));class ta{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class ia{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){var i,s;return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:null!==(s=null===(i=Me.getArticulationByValue(t))||void 0===i?void 0:i.staffLine)&&void 0!==s?s:0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case T.ForceDoubleFlat:t+=2;break;case T.ForceDoubleSharp:t-=2;break;case T.ForceFlat:t+=1;break;case T.ForceSharp:t-=1}return t}applyAccidental(e){const t=ia.getNoteValue(e);let i=e.hasQuarterToneOffset;return this.getAccidental(t,i,e.beat,!1,e)}applyAccidentalForValue(e,t,i,s){return this.getAccidental(t,i,e,s,null)}static computeLineWithoutAccidentals(e,t){let i=0;const s=ia.getNoteValue(t);if(e.staff.isPercussion)i=ia.getPercussionLine(e,s);else{const a=t?t.accidentalMode:T.Default;i=ia.calculateNoteLine(e,s,a)}return i}getAccidental(e,t,i,s,a=null){let r=se.None,n=0;if(this._bar.staff.isPercussion)n=ia.getPercussionLine(this._bar,e);else{const i=a?a.accidentalMode:T.Default;n=ia.calculateNoteLine(this._bar,e,i);let s=this._bar.masterBar.keySignature+7,o=e%12,h=s<7?se.Flat:se.Sharp,l=ia.KeySignatureLookup[s][o],c=ia.AccidentalNotes[o];if(t)switch(r=c?h:se.Natural,r){case se.Natural:r=se.NaturalQuarterNoteUp;break;case se.Sharp:r=se.SharpQuarterNoteUp;break;case se.Flat:r=se.FlatQuarterNoteUp}else{switch(i){case T.ForceSharp:r=se.Sharp;break;case T.ForceDoubleSharp:r=se.DoubleSharp;break;case T.ForceFlat:r=se.Flat;break;case T.ForceDoubleFlat:r=se.DoubleFlat;break;default:c?r=h:l&&(r=se.Natural)}let e=!1;if(a&&a.isTieDestination&&0===a.beat.index){const t=this._barRenderer.previousRenderer;if(t){t.accidentalHelper.getNoteLine(a.tieOrigin)===n&&(e=!0)}}e?r=se.None:r!==se.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=se.None):l&&r===h&&(r=se.None),r!=se.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===se.Natural?r=se.None:(r=se.Natural,this._registeredAccidentals.set(n,r)):this._registeredAccidentals.delete(n)}}return a?(this._appliedScoreLines.set(a.id,n),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,n),(-1e3===this.minLine||this.minLine<n)&&(this.minLine=n,this.minLineBeat=i),(-1e3===this.maxLine||this.maxLine>n)&&(this.maxLine=n,this.maxLineBeat=i),s||this.registerLine(i,n),r}registerLine(e,t){let i;this._beatLines.has(e.id)?i=this._beatLines.get(e.id):(i=new ta,this._beatLines.set(e.id,i)),(-1e3===i.minLine||t<i.minLine)&&(i.minLine=t),(-1e3===i.minLine||t>i.maxLine)&&(i.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteLine(e,t,i){let s=t,a=e.masterBar.keySignature,r=e.clef,n=s%12,o=(s/12|0)-1,h=ia.OctaveSteps[r];return h-=o*ia.StepsPerOctave,h-=(fe.keySignatureIsSharp(a)||fe.keySignatureIsNatural(a)?ia.SharpNoteSteps:ia.FlatNoteSteps)[n],h}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}ia.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]],ia.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],ia.StepsPerOctave=7,ia.OctaveSteps=[38,32,30,26,38],ia.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],ia.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class sa{constructor(){this.staffId="",this.up=0,this.down=0}}class aa{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 ra{constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=S.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=U.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>S.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>S.Quarter||this.beats[0].graceType!==_.None)}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===U.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,i,s){let a=this.getOrCreateBeatPositions(t);a.staffId=e,a.up=i,a.down=s;for(const e of this.drawingInfos.values())e.startBeat==t?e.startX=this.getBeatLineX(t):e.endBeat==t&&(e.endX=this.getBeatLineX(t))}getOrCreateBeatPositions(e){return this._beatLineXPositions.has(e.index)||this._beatLineXPositions.set(e.index,new sa),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(U.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==_.None)&&(e=this.invert(U.Up)):e=U.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,ae.Center),i=this._renderer.getNoteY(this.lowestNoteInHelper,ae.Center);if(null===e){const s=(t+i)/2;e=this.invert(this._renderer.middleYPosition<s?U.Up:U.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(U.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case S.QuadrupleWhole:case S.DoubleWhole:return[2,2];case S.Whole:return[0,1];case S.Half:return[1,0];case S.Quarter:return[3,3];case S.Eighth:return[2,2];case S.Sixteenth:return[2,4];case S.ThirtySecond:return[4,4];case S.SixtyFourth:return[4,6];case S.OneHundredTwentyEighth:return[6,6];case S.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let i=t,s=t;const a=ra.computeLineHeightsForRest(e.duration);i-=a[0],s+=a[1],(null===this.minRestLine||this.minRestLine>i)&&(this.minRestLine=i,this.beatOfMinRestLine=e),(null===this.maxRestLine||this.maxRestLine<s)&&(this.maxRestLine=s,this.beatOfMaxRestLine=e)}invert(e){if(!this.invertBeamDirection)return e;switch(e){case U.Down:return U.Up;case U.Up:default:return U.Down}}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case M.Auto:t=ra.canJoin(this.beats[this.beats.length-1],e);break;case M.ForceSplitToNext:t=!1;break;case M.ForceMergeWithNext:t=!0}if(t){if(null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.isRest)0===this.beats.length&&this.beats.push(e);else{this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),e.graceType!==_.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let s=0;s<e.notes.length;s++){let a=e.notes[s];a.leftHandFinger===i.Unknown&&a.rightHandFinger===i.Unknown||t++}t>this.fingeringCount&&(this.fingeringCount=t),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e}e.hasTuplet&&(this.hasTuplet=!0)}return t}checkNote(e){if(!e)return;let t,i;this.voice&&e.isPercussion?(t=-ia.getPercussionLine(this.voice.bar,ia.getNoteValue(e)),i=t):(t=ia.getNoteValue(e),i=t,e.harmonicType!==B.None&&e.harmonicType!==B.Natural&&(i=e.realValue-this._staff.displayTranspositionPitch)),1===this.beats.length&&this.beats[0]===e.beat&&((-1===this._firstBeatLowestNoteCompareValue||t<this._firstBeatLowestNoteCompareValue)&&(this._firstBeatLowestNoteCompareValue=t),(-1===this._firstBeatHighestNoteCompareValue||i>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=i)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||i>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=i),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||i>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=i)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===_.BendGrace||t.graceType===_.BendGrace)return!1;if(e.graceType!==_.None&&t.graceType!==_.None)return!0;let i=e.voice.bar;if(i!==t.voice.bar)return!1;let s=e.playbackStart,a=t.playbackStart;if(!ra.canJoinDuration(e.duration)||!ra.canJoinDuration(t.duration))return s===a;if(e.tupletGroup!==t.tupletGroup)return!1;if(e.hasTuplet&&t.hasTuplet&&e.tupletGroup===t.tupletGroup&&e.tupletGroup.isFull)return!0;let r=xe.QuarterTime;switch(i.masterBar.timeSignatureDenominator){case 8:i.masterBar.timeSignatureNumerator%3==0&&(r+=xe.QuarterTime/2|0)}return(0|(r+s)/r)===(0|(r+a)/r)}static canJoinDuration(e){switch(e){case S.Whole:case S.Half:case S.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,i){return fe.getIndex(e.duration)-2-i>0&&fe.getIndex(t.duration)-2-i>0}get beatOfLowestNote(){return this.lowestNoteInHelper.beat}get beatOfHighestNote(){return this.highestNoteInHelper.beat}isPositionFrom(e,t){return!this._beatLineXPositions.has(t.index)||(this._beatLineXPositions.get(t.index).staffId===e||!this._beatLineXPositions.get(t.index).staffId)}}class na{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class oa{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new na(e,t)),-1e3===this.topY)this.topY=e,this.bottomY=t;else{const i=Math.min(e,t),s=Math.max(e,t);i<this.topY&&(this.topY=i),s>this.bottomY&&(this.bottomY=s)}}}class ha{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const i of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=i.topY,t=i.bottomY):(e>i.topY&&(e=i.topY),t<i.bottomY&&(t=i.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,i){t!=i&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new oa(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,i),e.isRest&&this.registerRest(e))}registerRest(e){this.restDurationsByDisplayTime.has(e.displayStart)||this.restDurationsByDisplayTime.set(e.displayStart,new Map),this.restDurationsByDisplayTime.get(e.displayStart).has(e.playbackDuration)||this.restDurationsByDisplayTime.get(e.displayStart).set(e.playbackDuration,e.id)}applyRestCollisionOffset(e,t,i){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const s=ra.computeLineHeightsForRest(e.duration).map((e=>e*i));let a=t-s[0],r=t+s[1],n=a;const o=this.reservedLayoutAreasByDisplayTime.get(e.playbackStart);let h=!1;for(const e of o.slots)if(a>=e.topY&&a<=e.bottomY||r>=e.topY&&r<=e.bottomY){h=!0;break}if(h){n=1==e.voice.index?o.topY-s[1]-s[0]:o.bottomY;let t=n+s[0]+s[1];const r=2*i;let h=Math.ceil(Math.abs(n-a)/r);return o.addSlot(n,t),n<a?h*-r:h*r}}return 0}}class la{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this._renderer=e,this.collisionHelper=new ha}initialize(){var e=this._renderer,t=this._renderer.bar;let i=null,s=null;for(let a=0,r=t.voices.length;a<r;a++){let r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){let n,o=r.beats[a];o.graceType!==_.None?n=s:(n=i,s=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new ra(t.staff,e),n.checkBeat(o),o.graceType!==_.None?s=n:i=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}i&&i.finish(),s&&s.finish(),i=null,s=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(ae||(ae={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(re||(re={}));class ca{constructor(e,t){this._preBeatGlyphs=new Zs,this._voiceContainers=new Map,this._postBeatGlyphs=new Zs,this.x=0,this.y=0,this.width=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this._wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new la(this))}get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.previousBar):null}get middleYPosition(){return 0}registerOverflowTop(e){e>this.topOverflow&&(this.topOverflow=e)}registerOverflowBottom(e){e>this.bottomOverflow&&(this.bottomOverflow=e)}scaleToWidth(e){let t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get scale(){return this.settings.display.scale}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){let e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e);let i=this._postBeatGlyphs.width;e.postBeatSize<i&&(e.postBeatSize=i)}applyLayoutingInfo(){if(this._appliedLayoutingInfo>=this.layoutingInfo.version)return!1;this._appliedLayoutingInfo=this.layoutingInfo.version,this._preBeatGlyphs.width=this.layoutingInfo.preBeatSize;let e=this._preBeatGlyphs.x+this._preBeatGlyphs.width;for(const t of this._voiceContainers.values()){t.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width,t.applyLayoutingInfo(this.layoutingInfo);let i=t.x+t.width;e<i&&(e=i)}return this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),!0}finalizeRenderer(){this.isFinalized=!0}doLayout(){if(this.bar){this.helpers.initialize(),this._preBeatGlyphs=new Zs,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new Zs,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];if(this.hasVoiceContainer(t)){let i=new ea(0,0,t);i.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,i)}}this.bar.simileMark===g.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.createBeatGlyphs(),this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish()}}hasVoiceContainer(e){return!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,i=t;for(const s of e.values()){s.x=t,s.doLayout();let e=s.x+s.width;i<e&&(i=e)}this._postBeatGlyphs.x=Math.floor(i),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height*this.scale}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.get(e.index)}getBeatContainer(e){var t;return null===(t=this.getVoiceContainer(e.voice))||void 0===t?void 0:t.beatGlyphs[e.index]}getPreNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.preNotes}getOnNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.onNotes}paint(e,t,i){this.paintBackground(e,t,i),i.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,i);for(const s of this._voiceContainers.values())i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.paint(e+this.x,t+this.y,i);i.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,i)}paintBackground(e,t,i){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,i)}buildBoundingsLookup(e,t,i){let s=new ls;s.bar=this.bar,s.visualBounds=new ht,s.visualBounds.x=t+this.x,s.visualBounds.y=i+this.y+this.topPadding,s.visualBounds.w=this.width,s.visualBounds.h=this.height-this.topPadding-this.bottomPadding,s.realBounds=new ht,s.realBounds.x=t+this.x,s.realBounds.y=i+this.y,s.realBounds.w=this.width,s.realBounds.h=this.height,e.addBar(s);for(const[e,a]of this._voiceContainers){let r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(s,t+this.x+a.x,i+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this._wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(this.bar.voices[e])}}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=ie.PreNotes){let i=this.getBeatContainer(e);if(i)switch(t){case ie.PreNotes:return i.voiceContainer.x+i.x;case ie.OnNotes:return i.voiceContainer.x+i.x+i.onNotes.x;case ie.MiddleNotes:return i.voiceContainer.x+i.x+i.onTimeX;case ie.Stem:const t=i.onNotes.beamingHelper?i.onNotes.beamingHelper.getBeatLineX(e):i.onNotes.x+i.onNotes.width/2;return i.voiceContainer.x+t;case ie.PostNotes:return i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.width;case ie.EndBeat:return i.voiceContainer.x+i.x+i.width}return 0}getNoteX(e,t){let i=this.getBeatContainer(e.beat);return i?i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.getNoteX(e,t):0}getNoteY(e,t){let i=this.getOnNotesGlyphForBeat(e.beat);return i?i.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&(this._preBeatGlyphs=new Zs,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,i){switch(this.bar.simileMark){case g.Simple:i.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,E.Repeat1Bar,!1);break;case g.SecondOfDouble:i.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,E.Repeat2Bars,!1)}}completeBeamingHelper(e){}}ca.LineSpacing=8,ca.StemWidth=.12*ca.LineSpacing,ca.StaffLineThickness=.13*ca.LineSpacing,ca.BeamThickness=.5*ca.LineSpacing,ca.BeamSpacing=.25*ca.LineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(ne||(ne={}));class da extends Ps{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case ne.SingleOnBeatToEnd:case ne.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height)}}createOrResizeGlyph(e,t){let i;switch(e){case ne.FullBar:return i=this.info.createNewGlyph(this.renderer,t),i.renderer=this.renderer,i.beat=t,i.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,i),this._uniqueEffectGlyphs[t.voice.index].push(i),i;case ne.SinglePreBeat:case ne.SingleOnBeat:case ne.SingleOnBeatToEnd:return i=this.info.createNewGlyph(this.renderer,t),i.renderer=this.renderer,i.beat=t,i.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,i),this._uniqueEffectGlyphs[t.voice.index].push(i),i;case ne.GroupedOnBeat:case ne.GroupedOnBeatToEnd:let s=e===ne.GroupedOnBeat?ne.SingleOnBeat:ne.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){let e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let i=null;if(t.index>0&&this._effectGlyphs[t.voice.index].has(e.index))i=this._effectGlyphs[t.voice.index].get(e.index);else if(this.renderer.index>0){let s=this.renderer.previousRenderer.getBand(this.voice,this.info.effectId)._effectGlyphs[t.voice.index];s.has(e.index)&&(i=s.get(e.index))}let a=this.createOrResizeGlyph(s,t);return i&&this.info.canExpand(e,t)&&(i.nextGlyph=a,a.previousGlyph=i,this.isLinkedToPrevious=!0),a}return this.createOrResizeGlyph(s,t)}return this.createOrResizeGlyph(s,t);default:return this.createOrResizeGlyph(ne.SingleOnBeat,t)}}paint(e,t,i){super.paint(e,t,i);for(let s=0,a=this._uniqueEffectGlyphs.length;s<a;s++){let a=this._uniqueEffectGlyphs[s];for(let s=0,r=a.length;s<r;s++){a[s].paint(e+this.x,t+this.y,i)}}}alignGlyphs(){for(let e=0;e<this._effectGlyphs.length;e++)for(const t of this._effectGlyphs[e].keys())this.alignGlyph(this.info.sizingMode,this.renderer.bar.voices[e].beats[t])}alignGlyph(e,t){let i,s=this._effectGlyphs[t.voice.index].get(t.index),a=this.renderer.getBeatContainer(t);switch(e){case ne.SinglePreBeat:i=a.preNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case ne.SingleOnBeat:case ne.GroupedOnBeat:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case ne.SingleOnBeatToEnd:case ne.GroupedOnBeatToEnd:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,a.beat.isLastOfVoice?s.width=this.renderer.width-s.x:s.width=a.width-a.preNotes.width-a.preNotes.x;break;case ne.FullBar:s.width=this.renderer.width}}}class ua{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class pa{constructor(){this.bands=[],this.shared=new ua}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 ga{constructor(){this.slots=[],this._effectSlot=new Map}getOrCreateSlot(e){if(this._effectSlot.has(e.info.effectId)){let t=this._effectSlot.get(e.info.effectId);if(t.canBeUsed(e))return t}for(let t of this.slots)if(t.canBeUsed(e))return t;let t=new pa;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class fa extends $s{constructor(){super(0,0)}doLayout(){let e=0;if(this.glyphs)for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.x=e,i.renderer=this.renderer,i.doLayout(),e+=i.width}this.width=e}noteLoop(e){for(let t=this.container.beat.notes.length-1;t>=0;t--)e(this.container.beat.notes[t])}}class ma extends fa{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,i){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class ya extends ca{constructor(e,t,i){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=i}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){super.finalizeRenderer(),this.updateHeight()}updateHeight(){if(!this.sizingInfo)return;let e=0;for(let t of this.sizingInfo.slots){t.shared.y=e;for(let i of t.bands)i.y=e,i.height=t.shared.height;e+=t.shared.height}this.height=e}applyLayoutingInfo(){if(!super.applyLayoutingInfo())return!1;if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new ga;for(let e of this._bands)e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),!0}scaleToWidth(e){super.scaleToWidth(e);for(let e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(let e of this.bar.voices)if(this.hasVoiceContainer(e))for(let t of this._infos){let i=new da(e,t);i.renderer=this,i.doLayout(),this._bands.push(i),this._bandLookup.set(e.index+"."+t.effectId,i)}for(let e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e);for(let e of this._bands)e.isLinkedToPrevious&&(this.isLinkedToPrevious=!0)}createVoiceGlyphs(e){for(let t of e.beats){let i=new Ms(t,this.getVoiceContainer(e));i.preNotes=new fa,i.onNotes=new ma,this.addBeatGlyph(i);for(let e of this._bands)e.createGlyph(t)}}paint(e,t,i){this.paintBackground(e,t,i);for(let s of this._bands)i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isEmpty||s.paint(e+this.x,t+this.y,i)}getBand(e,t){let i=e.index+"."+t;return this._bandLookup.has(i)?this._bandLookup.get(i):null}}class ba extends Ks{constructor(e,t){super(),this._infos=t,this._staffId=e,this.isInAccolade=!1,this.isRelevantForBoundsLookup=!1}get staffId(){return this._staffId}create(e,t){return new ya(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class Sa extends Es{constructor(e,t,i){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<ze.MaxAlternateEndings;e++)0!=(i&1<<e)&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(Sa.Padding*this.scale+2);let e="";for(let t=0,i=this._endings.length;t<i;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,i){super.paint(e,t,i);let s=i.textBaseline;if(i.textBaseline=F.Top,this._endings.length>0){let s=this.renderer.resources;i.font=s.wordsFont,i.moveTo(e+this.x,t+this.y+this.height),i.lineTo(e+this.x,t+this.y),i.lineTo(e+this.x+this.width,t+this.y),i.stroke(),i.fillText(this._endingsString,e+this.x+Sa.Padding*this.scale,t+this.y*this.scale)}i.textBaseline=s}}Sa.Padding=3;class wa{get effectId(){return this.notationElement.toString()}}class _a extends wa{get notationElement(){return n.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return ne.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new Sa(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class Ba extends Es{constructor(e,t,i,s,a=C.Left){super(e,t),this._lines=i.split("\n"),this.font=s,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,i){let s=i.color;i.color=s,i.font=this.font;let a=i.textAlign;i.textAlign=this.textAlign;let r=t+this.y;for(let t of this._lines)i.fillText(t,e+this.x,r),r+=this.font.size;i.textAlign=a}}class Ta extends wa{get notationElement(){return n.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Ba(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,C.Left)}canExpand(e,t){return!1}}class ka extends wa{get notationElement(){return n.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Ba(0,0,t.chord.name,e.resources.effectFont,C.Center)}canExpand(e,t){return!1}}class va extends Es{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}paint(e,t,i){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,i);let s;if(!this.isLinkedWithNext&&this.forceGroupedRendering)s=this;else for(s=this.nextGlyph;s.isLinkedWithNext;)s=s.nextGlyph;let a=s.renderer,r=s.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,i)}calculateEndX(e,t,i,s){return t?i+e.x+e.getBeatX(t,s):i+e.x+this.x+this.width}paintNonGrouped(e,t,i){let s=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,s,this.endPosition);this.paintGrouped(e,t,a,i)}}class Na extends va{constructor(e,t,i){super(ie.EndBeat),this._crescendo=b.None,this._crescendo=i,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17*this.scale}paintGrouped(e,t,i,s){let a=e+this.x,r=this.height*this.scale;s.beginPath(),this._crescendo===b.Crescendo?(i-=Na.Padding*this.scale,s.moveTo(i,t+this.y),s.lineTo(a,t+this.y+r/2),s.lineTo(i,t+this.y+r)):(i-=Na.Padding*this.scale,s.moveTo(a,t+this.y),s.lineTo(i,t+this.y+r/2),s.lineTo(a,t+this.y+r)),s.stroke()}}Na.Padding=Fs.QuarterNoteHeadWidth/2|0;class xa extends wa{get notationElement(){return n.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==b.None}createNewGlyph(e,t){return new Na(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Pa extends Cs{constructor(e,t,i){super(e,t,.6,Pa.getSymbol(i))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case w.PPP:return E.DynamicPPP;case w.PP:return E.DynamicPP;case w.P:return E.DynamicPiano;case w.MP:return E.DynamicMP;case w.MF:return E.DynamicMF;case w.F:return E.DynamicForte;case w.FF:return E.DynamicFF;case w.FFF:return E.DynamicFFF;default:return E.None}}}class Ea extends wa{get notationElement(){return n.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest||e.graceType!==_.None)return!1;let t=this.getPreviousDynamicsBeat(e),i=0===e.voice.index&&!t||e.dynamics!==(null==t?void 0:t.dynamics);if(i&&e.voice.index>0)for(let t of e.voice.bar.voices)if(t.index<e.voice.index){let s=t.getBeatAtPlaybackStart(e.playbackStart);s&&e.dynamics===s.dynamics&&this.internalShouldCreateGlyph(s)&&(i=!1)}return i}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest&&t.graceType===_.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Pa(0,0,t.dynamics)}canExpand(e,t){return!0}}class Ca extends Es{doLayout(){super.doLayout(),this.height=17*this.scale}paint(e,t,i){let s=6*this.scale,a=Math.max(this.width,14*this.scale),r=this.height/2;i.beginPath(),i.moveTo(e+this.x,t+this.y+r),i.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r-s),i.moveTo(e+this.x,t+this.y+r),i.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r+s),i.stroke()}}class Fa extends wa{get notationElement(){return n.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new Ca}canExpand(e,t){return!0}}class La extends Cs{constructor(e,t,i){super(e,t,1,La.getSymbol(i))}static getSymbol(e){switch(e){case V.Short:return E.FermataShortAbove;case V.Medium:return E.FermataAbove;case V.Long:return E.FermataLongAbove;default:return E.None}}doLayout(){this.width=23*this.scale,this.height=12*this.scale}paint(e,t,i){super.paint(e-this.width/2,t+this.height,i)}}class Ma extends wa{get notationElement(){return n.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new La(0,0,t.fermata.type)}canExpand(e,t){return!0}}class Ia extends wa{get notationElement(){return n.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(t,i){return!(0!==i.voice.index||i.isRest||t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBand&&t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBandForcePiano)&&(1===i.notes.length&&i.notes[0].isFingering)}createNewGlyph(e,t){var s;let a=i.Unknown,r=!1,n=t.notes[0];n.leftHandFinger!==i.Unknown?(a=n.leftHandFinger,r=!0):n.rightHandFinger!==i.Unknown&&(a=n.rightHandFinger);let o=null!==(s=fe.fingerToString(e.settings,t,a,r))&&void 0!==s?s:"";return new Ba(0,0,o,e.resources.fingeringFont,C.Left)}canExpand(e,t){return!0}}class Da extends wa{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,i=t.notes.length;e<i;e++){let i=t.notes[e];this.shouldCreateGlyphForNote(i)&&this.lastCreateInfo.push(i)}return this.lastCreateInfo.length>0}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}canExpand(e,t){return!0}}class Aa extends va{constructor(e){super(ie.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=ie.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=C.Center,i.fillText(this._label,e+this.x,t+this.y),i.textAlign=a}paintGrouped(e,t,i,s){this.paintNonGrouped(e,t,s);let a=3*this.scale,r=s.measureText(this._label),n=e+this.x+r/2+a,o=t+this.y+4*this.scale,h=8*this.scale;if(i>n){let e=n;for(;e<i;)s.beginPath(),s.moveTo(e,0|o),s.lineTo(Math.min(e+h,i),0|o),e+=h+a,s.stroke();s.beginPath(),s.moveTo(i,o-5*this.scale|0),s.lineTo(i,o+5*this.scale|0),s.stroke()}}}Aa.LineSpacing=3,Aa.LineTopPadding=4,Aa.LineTopOffset=5,Aa.LineSize=8;class Ra extends Da{constructor(e){switch(super(),this._beat=null,this._harmonicType=B.None,this._harmonicType=e,e){case B.None:this._effectId="harmonics-none";break;case B.Natural:this._effectId="harmonics-natural";break;case B.Artificial:this._effectId="harmonics-artificial";break;case B.Pinch:this._effectId="harmonics-pinch";break;case B.Tap:this._effectId="harmonics-tap";break;case B.Semi:this._effectId="harmonics-semi";break;case B.Feedback:this._effectId="harmonics-feedback"}}get effectId(){return this._effectId}get notationElement(){return n.EffectHarmonics}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return ne.GroupedOnBeat}createNewGlyph(e,t){return new Aa(Ra.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case B.Natural:return"N.H.";case B.Artificial:return"A.H.";case B.Pinch:return"P.H.";case B.Tap:return"T.H.";case B.Semi:return"S.H.";case B.Feedback:return"Fdbk."}return""}}class Oa extends wa{get notationElement(){return n.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return ne.GroupedOnBeat}createNewGlyph(e,t){return new Aa("LetRing")}canExpand(e,t){return!0}}class Ga extends Es{constructor(e,t,i,s,a=C.Center){super(e,t),this._lines=i,this.font=s,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,i){i.font=this.font;let s=i.textAlign;i.textAlign=this.textAlign;for(let s=0;s<this._lines.length;s++)this._lines[s]&&i.fillText(this._lines[s],e+this.x,t+this.y+s*this.font.size);i.textAlign=s}}class Va extends wa{get notationElement(){return n.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new Ga(0,0,t.lyrics,e.resources.effectFont,C.Center)}canExpand(e,t){return!0}}class Ha extends wa{get notationElement(){return n.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return ne.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 Ba(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,C.Left)}canExpand(e,t){return!0}}class Wa extends va{constructor(e,t){super(ie.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13*this.scale}paintNonGrouped(e,t,i){this.paintOttava(e,t,i)}paintOttava(e,t,i){let s=0;switch(this._ottava){case p._15ma:s=37*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,E.QuindicesimaAlta,!1);break;case p._8va:s=26*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,E.OttavaAlta,!1);break;case p._8vb:s=23*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,E.OttavaBassaVb,!1);break;case p._15mb:s=36*this.scale,i.fillMusicFontSymbols(e+this.x-s/2,t+this.y+this.height,.8,[E.Quindicesima,E.OctaveBaselineM,E.OctaveBaselineB],!1)}return s/2}paintGrouped(e,t,i,s){let a=this.paintOttava(e,t,s),r=3*this.scale,n=e+this.x+a+r,o=t+this.y;o+=this._aboveStaff?2*this.scale:this.height-2*this.scale;let h=8*this.scale;if(i>n){let e=n;for(;e<i;)s.beginPath(),s.moveTo(e,0|o),s.lineTo(Math.min(e+h,i),0|o),e+=h+r,s.stroke();s.beginPath(),this._aboveStaff?(s.moveTo(i,o),s.lineTo(i,t+this.y+this.height)):(s.moveTo(i,o),s.lineTo(i,t+this.y)),s.stroke()}}}class Ua extends wa{constructor(e){super(),this._aboveStaff=e}get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return n.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.GroupedOnBeat}shouldCreateGlyph(e,t){switch(t.ottava){case p._15ma:case p._8va:return this._aboveStaff;case p._8vb:case p._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new Wa(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class za extends Da{get notationElement(){return n.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return ne.GroupedOnBeat}createNewGlyph(e,t){return new Aa("P.M.")}constructor(){super()}}class Xa extends Da{get notationElement(){return n.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===v.PickSlideDown||e.slideOutType===v.PickSlideUp}get sizingMode(){return ne.GroupedOnBeat}createNewGlyph(e,t){return new Aa("P.S.")}constructor(){super()}}class Ya extends Cs{constructor(e,t,i){super(e,t,Fs.GraceScale,Ya.getSymbol(i))}doLayout(){this.width=9*this.scale,this.height=13*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}static getSymbol(e){switch(e){case P.Up:return E.StringsUpBow;case P.Down:return E.StringsDownBow;default:return E.None}}}class qa extends wa{get notationElement(){return n.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==P.None}createNewGlyph(e,t){return new Ya(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Ja extends va{constructor(e){super(ie.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case N.Slight:this._stepSize=12*this.scale;break;case N.Wide:this._stepSize=23*this.scale}this.height=18*this.scale}paintGrouped(e,t,i,s){let a=e+this.x,r=i-a,n=Math.max(1,r/this._stepSize);s.beginPath(),s.moveTo(a,t+this.y);for(let e=0;e<n;e++)s.lineTo(a+this._stepSize/2,t+this.y+this.height),s.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;s.stroke()}}class Qa extends wa{get notationElement(){return n.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===N.Slight}createNewGlyph(e,t){return new Ja(N.Slight)}canExpand(e,t){return!0}}class ja extends va{constructor(e,t,i,s=1.2,a=!1){super(ie.EndBeat),this._scale=0,this._symbol=E.None,this._symbolSize=0,this._type=i,this._scale=s,this.x=e,this.y=t,this._partialWaves=a}doLayout(){super.doLayout();let e=0;switch(this._type){case N.Slight:this._symbol=E.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case N.Wide:this._symbol=E.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e*this.scale}paintGrouped(e,t,i,s){let a=i-(e+this.x),r=this._symbolSize*this.scale,n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let i=0;i<n;i++)s.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale*this.scale,this._symbol,!1),o+=r}}class Ka extends Da{get notationElement(){return n.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===N.Slight||e.isTieDestination&&e.tieOrigin.vibrato===N.Slight}get sizingMode(){return ne.GroupedOnBeatToEnd}createNewGlyph(e,t){return new ja(0,0,N.Slight,1.2)}constructor(){super()}}class $a extends wa{get notationElement(){return n.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let i=e.resources;return t.slap?new Ba(0,0,"S",i.effectFont,C.Left):t.pop?new Ba(0,0,"P",i.effectFont,C.Left):new Ba(0,0,"T",i.effectFont,C.Left)}canExpand(e,t){return!0}}class Za extends Es{constructor(e,t,i){super(e,t),this._tempo=0,this._tempo=i}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.markerFont,i.fillMusicFontSymbol(e+this.x,t+this.y+.8*this.height,this.scale*Fs.GraceScale,E.NoteQuarterUp,!1),i.fillText("= "+this._tempo,e+this.x+this.height/2,t+this.y+i.font.size/2)}}class er extends wa{get notationElement(){return n.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return ne.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&(!!t.voice.bar.masterBar.tempoAutomation||0===t.voice.bar.index)}createNewGlyph(e,t){let i=0;return i=t.voice.bar.masterBar.tempoAutomation?t.voice.bar.masterBar.tempoAutomation.value:t.voice.bar.staff.track.score.tempo,new Za(0,0,i)}canExpand(e,t){return!0}}class tr extends wa{get notationElement(){return n.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Ba(0,0,t.text,e.resources.effectFont,C.Left)}canExpand(e,t){return!0}}class ir extends Es{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=20*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.markerFont;let a=i.measureText("tr");i.fillText("tr",e+this.x,t+this.y+i.font.size/2);let r=a+3*this.scale,n=this.width-r,o=11*this.scale*1.2,h=Math.max(1,(n-r)/o),l=r,c=t+this.y+this.height;for(let t=0;t<h;t++)i.fillMusicFontSymbol(e+this.x+l,c,1.2,E.WiggleTrill,!1),l+=o}}class sr extends Da{get notationElement(){return n.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return ne.SingleOnBeat}createNewGlyph(e,t){return new ir(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(oe||(oe={}));class ar extends Es{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,i){e+=this.x;let s=(t+=this.y)+this.height*Fs.GraceScale;i.font=this.renderer.resources.effectFont,i.fillText("(",e,t+.3*this.height);let a=e+10*this.scale,r=e+40*this.scale;switch(this._tripletFeel){case R.NoTripletFeel:this.renderBarNote(a,s,ar.NoteScale,i,[oe.Full]),this.renderBarNote(r,s,ar.NoteScale,i,[oe.Full]);break;case R.Triplet8th:this.renderBarNote(a,s,ar.NoteScale,i,[oe.Full]),i.fillMusicFontSymbol(r,s,ar.NoteScale,E.NoteQuarterUp,!1),i.fillMusicFontSymbol(r+ar.NoteSeparation*this.scale,s,ar.NoteScale,E.NoteEighthUp,!1),this.renderTriplet(r,t,i);break;case R.Triplet16th:this.renderBarNote(a,s,ar.NoteScale,i,[oe.Full,oe.Full]),this.renderBarNote(r,s,ar.NoteScale,i,[oe.Full,oe.PartialRight]),this.renderTriplet(r,t,i);break;case R.Dotted8th:this.renderBarNote(a,s,ar.NoteScale,i,[oe.Full]),this.renderBarNote(r,s,ar.NoteScale,i,[oe.Full,oe.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case R.Dotted16th:this.renderBarNote(a,s,ar.NoteScale,i,[oe.Full,oe.Full]),this.renderBarNote(r,s,ar.NoteScale,i,[oe.Full,oe.Full,oe.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case R.Scottish8th:this.renderBarNote(a,s,ar.NoteScale,i,[oe.Full]),this.renderBarNote(r,s,ar.NoteScale,i,[oe.Full,oe.PartialLeft]),i.fillCircle(r+ar.NoteSeparation*this.scale+8*this.scale,s,this.scale);break;case R.Scottish16th:this.renderBarNote(a,s,ar.NoteScale,i,[oe.Full,oe.Full]),this.renderBarNote(r,s,ar.NoteScale,i,[oe.Full,oe.Full,oe.PartialLeft]),i.fillCircle(r+ar.NoteSeparation*this.scale+8*this.scale,s,this.scale)}i.fillText("=",e+30*this.scale,t+5*this.scale),i.fillText(")",e+65*this.scale,t+.3*this.height)}renderBarNote(e,t,i,s,a){s.fillMusicFontSymbol(e,t,i,E.NoteQuarterUp,!1);let r=ar.NoteSeparation/2*this.scale;for(let i=0;i<a.length;i++)switch(a[i]){case oe.Full:s.fillRect(e+4*this.scale,t-ar.NoteHeight*this.scale+ar.BarSeparation*this.scale*i,ar.NoteSeparation*this.scale,ar.BarHeight*this.scale);break;case oe.PartialLeft:s.fillRect(e+4*this.scale,t-ar.NoteHeight*this.scale+ar.BarSeparation*this.scale*i,r,ar.BarHeight*this.scale);break;case oe.PartialRight:s.fillRect(e+4*this.scale+r,t-ar.NoteHeight*this.scale+ar.BarSeparation*this.scale*i,r,ar.BarHeight*this.scale)}s.fillMusicFontSymbol(e+ar.NoteSeparation*this.scale,t,i,E.NoteQuarterUp,!1)}renderTriplet(e,t,i){t+=2*this.scale;let s=this.renderer.resources.effectFont;i.font=new we(s.family,.8*s.size,s.style);let a=e+ar.NoteSeparation*this.scale+3*this.scale;i.beginPath(),i.moveTo(e,t+3*this.scale),i.lineTo(e,t),i.lineTo(e+5*this.scale,t),i.moveTo(a+5*this.scale,t+3*this.scale),i.lineTo(a+5*this.scale,t),i.lineTo(a,t),i.stroke(),i.fillText("3",e+7*this.scale,t-10*this.scale),i.font=s}}ar.NoteScale=.4,ar.NoteHeight=12,ar.NoteSeparation=12,ar.BarHeight=2,ar.BarSeparation=3;class rr extends wa{get notationElement(){return n.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return ne.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==R.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new ar(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class nr extends wa{get notationElement(){return n.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ne.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new Aa("w/bar")}canExpand(e,t){return!0}}class or extends wa{get notationElement(){return n.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ne.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===N.Wide}createNewGlyph(e,t){return new Ja(N.Wide)}canExpand(e,t){return!0}}class hr extends Da{get notationElement(){return n.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===N.Wide||e.isTieDestination&&e.tieOrigin.vibrato===N.Wide}get sizingMode(){return ne.GroupedOnBeatToEnd}createNewGlyph(e,t){return new ja(0,0,N.Wide,1.2)}}class lr extends Es{constructor(e,t,i){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=i}doLayout(){super.doLayout();const e=this.scale;let t=this.renderer.resources;this._textRow=1.5*t.effectFont.size*e,this._fretRow=1.5*t.effectFont.size*e,this._chord.firstFret>1?this._firstFretSpacing=lr.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(lr.Frets-1)*lr.FretSpacing*e+2*lr.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*lr.StringSpacing*e+2*lr.Padding*e}paint(e,t,i){e+=this.x+lr.Padding*this.scale+this._firstFretSpacing,t+=this.y;let s=this.width-2*lr.Padding*this.scale+this.scale-this._firstFretSpacing,a=lr.StringSpacing*this.scale,r=lr.FretSpacing*this.scale,n=this.renderer.resources,o=lr.CircleRadius*this.scale,h=i.textAlign,l=i.textBaseline;i.font=n.effectFont,i.textAlign=C.Center,i.textBaseline=F.Top,this._chord.showName&&i.fillText(this._chord.name,e+this.width/2,t+n.effectFont.size/2),t+=this._textRow,e+=a/2,i.font=n.fretboardNumberFont,i.textBaseline=F.Middle;for(let s=0;s<this._chord.staff.tuning.length;s++){let r=e+s*a,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-s-1];o<0?i.fillMusicFontSymbol(r,n,this.scale,E.FretboardX,!0):0===o?i.fillMusicFontSymbol(r,n,this.scale,E.FretboardO,!0):(o-=this._chord.firstFret-1,i.fillText(o.toString(),r,n))}t+=this._fretRow;for(let s=0;s<this._chord.staff.tuning.length;s++){let n=e+s*a;i.fillRect(n,t,1,r*lr.Frets+this.scale)}this._chord.firstFret>1&&(i.textAlign=C.Left,i.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+r/2)),i.fillRect(e,t-this.scale,s,2*this.scale);for(let a=0;a<=lr.Frets;a++){let n=t+a*r;i.fillRect(e,n,s,this.scale)}let c=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let s=0;s<this._chord.strings.length;s++){let n=this._chord.strings[s];if(n>0){if(n-=this._chord.firstFret,c.has(n)){let e=c.get(n);(-1===e[0]||s<e[0])&&(e[0]=s),(-1===e[1]||s>e[1])&&(e[1]=s)}let h=t+n*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-s-1)*a;i.fillCircle(l,h,o)}}for(const[s,n]of c){let h=t+s*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-n[1]-1)*a,c=e+(this._chord.strings.length-n[0]-1)*a;i.fillRect(l,h-o,c-l,2*o)}i.textAlign=h,i.textBaseline=l}}lr.Padding=5,lr.Frets=5,lr.CircleRadius=2.5,lr.StringSpacing=10,lr.FretSpacing=12;class cr extends $s{constructor(e,t,i=C.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=i}doLayout(){let e=0;switch(this._align){case C.Left:e=0;break;case C.Center:e=(this.width-this._glyphWidth)/2;break;case C.Right:e=this.width-this._glyphWidth}for(let t of this.glyphs)t.x=e,e+=t.width}addGlyphToRow(e){this.glyphs.push(e),this._glyphWidth+=e.width,e.height>this.height&&(this.height=e.height)}}class dr extends $s{constructor(e,t,i=C.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=i}doLayout(){let e=0,t=0,i=2*dr.Padding*this.scale;this._rows=[];let s=new cr(e,t,this._align);s.width=this.width;for(let a of this.glyphs)e+a.width<this.width?(s.addGlyphToRow(a),e+=a.width):(s.isEmpty||(s.doLayout(),this._rows.push(s),t+=s.height+i),e=0,s=new cr(e,t,this._align),s.width=this.width,s.addGlyphToRow(a),e+=a.width);s.isEmpty||(s.doLayout(),this._rows.push(s),t+=s.height+i),this.height=t+i}paint(e,t,i){for(let s of this._rows)s.paint(e+this.x,t+this.y+dr.Padding*this.scale,i)}}dr.Padding=3;class ur extends dr{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new lr(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class pr{constructor(e,t,i){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.trackIndex=0,this.staveTop=0,this.topSpacing=20,this.bottomSpacing=5,this.staveBottom=0,this.isFirstInAccolade=!1,this.isLastInAccolade=!1,this._factory=i,this.trackIndex=e,this.modelStaff=t}get staveId(){return this._factory.staffId}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInAccolade(){return this._factory.isInAccolade}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.staveGroup.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let i;i=e?this._factory.create(this.staveGroup.layout.renderer,e):new ca(this.staveGroup.layout.renderer,e),i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo(),this.barRenderers.push(i),e&&this.staveGroup.layout.registerBarRenderer(this.staveId,i)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];return this.barRenderers.splice(this.barRenderers.length-1,1),this.staveGroup.layout.unregisterBarRenderer(this.staveId,e),e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=(e-this.staveGroup.width)/this.barRenderers.length;for(let e=0,i=this.barRenderers.length;e<i;e++)this.barRenderers[e].scaleToWidth(this.barRenderers[e].width+t)}get topOverflow(){let e=0;for(let t=0,i=this.barRenderers.length;t<i;t++){let i=this.barRenderers[t];i.topOverflow>e&&(e=i.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,i=this.barRenderers.length;t<i;t++){let i=this.barRenderers[t];i.bottomOverflow>e&&(e=i.bottomOverflow)}return e}finalizeStaff(){let e=0;this.height=0;let t=this.topOverflow,i=this.bottomOverflow;for(let i=0;i<this.barRenderers.length;i++)this.barRenderers[i].x=e,this.barRenderers[i].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[i].height),this.barRenderers[i].finalizeRenderer(),e+=this.barRenderers[i].width;this.height>0&&(this.height+=this.topSpacing+t+i+this.bottomSpacing)}paint(e,t,i,s,a){if(0!==this.height&&0!==a)for(let r=s,n=Math.min(s+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,i)}}class gr{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 fr{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSizes=new Map,this.onBeatSizes=new Map,this.onBeatCenterX=new Map,this.preBeatSize=0,this.postBeatSize=0,this.voiceSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateVoiceSize(e){e>this.voiceSize&&(this.voiceSize=e,this.version++)}setPreBeatSize(e,t){(!this.preBeatSizes.has(e.index)||this.preBeatSizes.get(e.index)<t)&&(this.preBeatSizes.set(e.index,t),this.version++)}getPreBeatSize(e){return this.preBeatSizes.has(e.index)?this.preBeatSizes.get(e.index):0}setOnBeatSize(e,t){(!this.onBeatSizes.has(e.index)||this.onBeatSizes.get(e.index)<t)&&(this.onBeatSizes.set(e.index,t),this.version++)}getOnBeatSize(e){return this.onBeatSizes.has(e.index)?this.onBeatSizes.get(e.index):0}getBeatCenterX(e){return this.onBeatCenterX.has(e.index)?this.onBeatCenterX.get(e.index):0}setBeatCenterX(e,t){(!this.onBeatCenterX.has(e.index)||this.onBeatCenterX.get(e.index)<t)&&(this.onBeatCenterX.set(e.index,t),this.version++)}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}addSpring(e,t,i,s,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<i&&(r.graceBeatWidth=i),r.preBeatWidth<s&&(r.preBeatWidth=s),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new gr,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){let e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations){e.timePosition}}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=i,r.preBeatWidth=s,this.springs.set(e,r);let n=this._timeSortedSprings,o=n.length-1;for(;o>0&&n[o].timePosition>e;)o--;this._timeSortedSprings.splice(o+1,0,r)}return(-1===this._minTime||this._minTime>e)&&(this._minTime=e),r}addBeatSpring(e,t,i){let s=e.absoluteDisplayStart;if(e.graceType!==_.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));let r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<i&&(r.postSpringWidth=i),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new gr;r.timePosition=s,r.postSpringWidth=i,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(s,e.displayDuration,a,t,i)}}finish(){for(const[e,t]of this.allGraceRods){let i=0;if(this.incompleteGraceRods.has(e))for(const e of t)i+=e.preBeatWidth,e.graceBeatWidth=i,i+=e.postSpringWidth;else for(let e=t.length-1;e>=0;e--)t[e].graceBeatWidth=i,i-=t[e].preBeatWidth+t[e].postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){this._xMin=0;let e=this.springs;for(const t of e.values())t.springWidth<this._xMin&&(this._xMin=t.springWidth);let t=0,i=this._timeSortedSprings;if(0===i.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<i.length;e++){let s=i[e],a=0;if(e===i.length-1)a=s.longestDuration;else{let t=i[e+1];a=Math.abs(t.timePosition-s.timePosition)}s.springConstant=this.calculateSpringConstant(s,a),t+=1/s.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<i.length;e++){let t=i[e],s=0;if(e===i.length-1)s=t.postSpringWidth;else{let a=i[e+1];s=t.postSpringWidth+a.preSpringWidth}0===e&&(s+=t.preSpringWidth);let a=s*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,i){}calculateSpringConstant(e,t){return t<=0&&(t=xe.toTicks(S.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/fr.MinDuration))*fr.MinDurationWidth))}spaceToForce(e){return-1!==this.totalSpringConstant?(this._timeSortedSprings.length>0&&(e-=this._timeSortedSprings[0].preSpringWidth),e-=this._incompleteGraceRodsWidth,Math.max(e,0)*this.totalSpringConstant):-1}calculateVoiceWidth(e){let t=0;return-1!==this.totalSpringConstant&&(t=this.calculateWidth(e,this.totalSpringConstant)),this._timeSortedSprings.length>0&&(t+=this._timeSortedSprings[0].preSpringWidth),t+=this._incompleteGraceRodsWidth,t}calculateWidth(e,t){return e/t}buildOnTimePositions(e){if(-1===this.totalSpringConstant)return new Map;if(fe.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;let t=this._onTimePositions=new Map,i=this._timeSortedSprings;if(0===i.length)return t;let s=i[0].preSpringWidth;for(let a=0;a<i.length;a++)t.set(i[a].timePosition,s),s+=this.calculateWidth(e,i[a].springConstant);return t}}fr.MinDuration=30,fr.MinDurationWidth=7;class mr{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class yr{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInAccolade=null,this.lastStaffInAccolade=null,this.staveGroup=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class br{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),this.calculateAccoladeSpacing(e),t.layoutingInfo.preBeatSize=0;let i=0;for(let e=0,s=this.staves.length;e<s;e++){let s=this.staves[e];for(let e=0,a=s.staves.length;e<a;e++){let a=s.staves[e],r=t.renderers[i++];a.addBarRenderer(r)}}return this.updateWidth(),t}addBars(e,t){if(0===e.length)return null;let i=new mr;i.layoutingInfo=new fr,i.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(i),this.calculateAccoladeSpacing(e);let s=i.layoutingInfo;for(let e of this.staves)for(let a of e.staves){let r=e.track.staves[a.modelStaff.index].bars[t];a.addBar(r,s);let n=a.barRenderers[a.barRenderers.length-1];i.renderers.push(n),n.isLinkedToPrevious&&(i.isLinkedToPrevious=!0),n.canWrap||(i.canWrap=!1)}return s.finish(),i.width=this.updateWidth(),i}revertLastBar(){if(this.masterBarsRenderers.length>1){let e=this.masterBarsRenderers[this.masterBarsRenderers.length-1];this.masterBarsRenderers.splice(this.masterBarsRenderers.length-1,1);let t=0;for(let e=0,i=this._allStaves.length;e<i;e++){let i=this._allStaves[e].revertLastBar();t=Math.max(t,i.width)}return this.width-=t,e}return null}updateWidth(){let e=0;for(let t=0,i=this._allStaves.length;t<i;t++){let i=this._allStaves[t];i.barRenderers[i.barRenderers.length-1].applyLayoutingInfo(),i.barRenderers[i.barRenderers.length-1].width>e&&(e=i.barRenderers[i.barRenderers.length-1].width)}return this.width+=e,e}calculateAccoladeSpacing(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(n.TrackNames)){let t=this.layout.renderer.canvas,i=this.layout.renderer.settings.display.resources.effectFont;t.font=i;for(let i of e)this.accoladeSpacing=Math.ceil(Math.max(this.accoladeSpacing,t.measureText(i.shortName)));this.accoladeSpacing*=this.layout.scale,this.accoladeSpacing+=2*br.AccoladeLabelSpacing*this.layout.scale,this.width+=this.accoladeSpacing}else this.accoladeSpacing=0}getStaveTrackGroup(e){for(let t=0,i=this.staves.length;t<i;t++){let i=this.staves[t];if(i.track===e)return i}return null}addStaff(e,t){let i=this.getStaveTrackGroup(e);i||(i=new yr(this,e),this.staves.push(i)),t.staveTrackGroup=i,t.staveGroup=this,t.index=this._allStaves.length,this._allStaves.push(t),i.addStaff(t),t.isInAccolade&&(this._firstStaffInAccolade||(this._firstStaffInAccolade=t,t.isFirstInAccolade=!0),i.firstStaffInAccolade||(i.firstStaffInAccolade=t),this._lastStaffInAccolade||(this._lastStaffInAccolade=t,t.isLastInAccolade=!0),this._lastStaffInAccolade&&(this._lastStaffInAccolade.isLastInAccolade=!1),this._lastStaffInAccolade=t,this._lastStaffInAccolade.isLastInAccolade=!0,i.lastStaffInAccolade=t)}get height(){return this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height}scaleToWidth(e){for(let t=0,i=this._allStaves.length;t<i;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,i){this.paintPartial(e+this.x,t+this.y,i,0,this.masterBarsRenderers.length)}paintPartial(e,t,i,s,a){this.buildBoundingsLookup(e,t);for(let r=0,n=this._allStaves.length;r<n;r++)this._allStaves[r].paint(e,t,i,s,a);let r=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===s){if(i.color=r.barSeparatorColor,this._firstStaffInAccolade&&this._lastStaffInAccolade){let s=t+this._firstStaffInAccolade.y+this._firstStaffInAccolade.staveTop+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow,a=t+this._lastStaffInAccolade.y+this._lastStaffInAccolade.topSpacing+this._lastStaffInAccolade.topOverflow+this._lastStaffInAccolade.staveBottom,r=e+this._firstStaffInAccolade.x;i.beginPath(),i.moveTo(r,s),i.lineTo(r,a),i.stroke()}i.font=r.effectFont;for(let s=0,a=this.staves.length;s<a;s++){let a=this.staves[s];if(a.firstStaffInAccolade&&a.lastStaffInAccolade){let s=t+a.firstStaffInAccolade.y+a.firstStaffInAccolade.staveTop+a.firstStaffInAccolade.topSpacing+a.firstStaffInAccolade.topOverflow,r=t+a.lastStaffInAccolade.y+a.lastStaffInAccolade.topSpacing+a.lastStaffInAccolade.topOverflow+a.lastStaffInAccolade.staveBottom,o=e+a.firstStaffInAccolade.x,h=3*this.layout.renderer.settings.display.scale,l=h,c=s-4*h,d=r+4*h;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(n.TrackNames)&&i.fillText(a.track.shortName,e+br.AccoladeLabelSpacing*this.layout.scale,s),i.fillRect(o-l-h,c,h,d-c);let u=o-l-h,p=o+2*h;i.beginPath(),i.moveTo(u,c),i.bezierCurveTo(u,c,u,c,p,c-h),i.bezierCurveTo(o,c+h,u,c+h,u,c+h),i.closePath(),i.fill(),i.beginPath(),i.moveTo(u,d),i.bezierCurveTo(u,d,o,d,p,d+h),i.bezierCurveTo(o,d-h,u,d-h,u,d-h),i.closePath(),i.fill()}}}}finalizeGroup(){let e=0;for(let t of this._allStaves)t.x=this.accoladeSpacing,t.y=e,t.finalizeStaff(),e+=t.height}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;if(!this._firstStaffInAccolade||!this._lastStaffInAccolade)return;let i=this._allStaves[this._allStaves.length-1],s=t+this.y+this._firstStaffInAccolade.y,a=t+this.y+this._lastStaffInAccolade.y+this._lastStaffInAccolade.height,r=t+this.y+this._allStaves[0].y,n=t+this.y+i.y+i.height,o=t+this.y+this._firstStaffInAccolade.y+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow+(this._firstStaffInAccolade.barRenderers.length>0?this._firstStaffInAccolade.barRenderers[0].topPadding:0),h=a-s,l=t+this.y+i.y+i.height-i.bottomSpacing-i.bottomOverflow-(i.barRenderers.length>0?i.barRenderers[0].bottomPadding:0)-o,c=n-r,d=this.x+this._firstStaffInAccolade.x,u=new ps;u.visualBounds=new ht,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new ht,u.realBounds.x=e,u.realBounds.y=t+this.y,u.realBounds.w=this.width,u.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaveGroup(u);let p=new Map;for(let e=0;e<this.staves.length;e++)for(let i of this.staves[e].stavesRelevantForBoundsLookup)for(let e of i.barRenderers){let a;p.has(e.bar.masterBar.index)?a=p.get(e.bar.masterBar.index):(a=new ds,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new ht,a.realBounds.x=d+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=c,a.visualBounds=new ht,a.visualBounds.x=d+e.x,a.visualBounds.y=s,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new ht,a.lineAlignedBounds.x=d+e.x,a.lineAlignedBounds.y=o,a.lineAlignedBounds.w=e.width,a.lineAlignedBounds.h=l,this.layout.renderer.boundsLookup.addMasterBar(a),p.set(a.index,a)),e.buildBoundingsLookup(a,d,t+this.y+i.y)}}getBarX(e){if(!this._firstStaffInAccolade||0===this.layout.renderer.tracks.length)return 0;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInAccolade.staveId,t).x}}br.AccoladeLabelSpacing=10;class Sr extends $s{constructor(e,t,i,s){super(e,t),this._tuning=i,this._trackLabel=s,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}createGlyphs(e){const t=this.renderer.scale,i=this.renderer.resources;this.height=0;const s=15*t;this._trackLabel.length>0&&(this.addGlyph(new Ba(0,this.height,this._trackLabel,i.effectFont,C.Left)),this.height+=s),this.addGlyph(new Ba(0,this.height,e.name,i.effectFont,C.Left));const a=64*t;if(this.renderer.scoreRenderer.canvas.font=i.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel)*t,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name)*t,2*a)),this.height+=s,!e.isStandard){const r=.7,n=Sr.CircleNumberHeight*r*t;let o=0|Math.ceil(e.tunings.length/2),h=0,l=this.height;for(let c=0,d=e.tunings.length;c<d;c++){const d=E.GuitarString0+(c+1);this.addGlyph(new Cs(h,l+n/1.2,r,d));const u="= "+je.getTextForTuning(e.tunings[c],!1);this.addGlyph(new Ba(h+n+1*t,l,u,i.effectFont,C.Left)),l+=s,c===o-1&&(l=this.height,h+=a)}this.height+=o*s}this.width+=15*t}}Sr.CircleNumberHeight=20;class wr extends dr{constructor(e,t){super(e,t,C.Left)}addTuning(e,t){if(e.tunings.length>0){let i=new Sr(0,0,e,t);i.renderer=this.renderer,i.doLayout(),this.glyphs.push(i)}}}class _r{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}layoutAndRender(){let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let i=this.renderer.settings.display.barCount;i<0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this.lastBarIndex=i,this.createScoreInfoGlyphs(),this.doLayoutAndRender()}createScoreInfoGlyphs(){Fe.debug("ScoreLayout","Creating score info glyphs");let e=this.renderer.settings.notation,t=this.renderer.score,i=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,t.title&&e.isNotationElementVisible(n.ScoreTitle)&&this.scoreInfoGlyphs.set(n.ScoreTitle,new Ba(0,0,t.title,i.titleFont,C.Center)),t.subTitle&&e.isNotationElementVisible(n.ScoreSubTitle)&&this.scoreInfoGlyphs.set(n.ScoreSubTitle,new Ba(0,0,t.subTitle,i.subTitleFont,C.Center)),t.artist&&e.isNotationElementVisible(n.ScoreArtist)&&this.scoreInfoGlyphs.set(n.ScoreArtist,new Ba(0,0,t.artist,i.subTitleFont,C.Center)),t.album&&e.isNotationElementVisible(n.ScoreAlbum)&&this.scoreInfoGlyphs.set(n.ScoreAlbum,new Ba(0,0,t.album,i.subTitleFont,C.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(n.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(n.ScoreWordsAndMusic,new Ba(0,0,"Music and Words by "+t.words,i.wordsFont,C.Center)):(t.music&&e.isNotationElementVisible(n.ScoreMusic)&&this.scoreInfoGlyphs.set(n.ScoreMusic,new Ba(0,0,"Music by "+t.music,i.wordsFont,C.Right)),t.words&&e.isNotationElementVisible(n.ScoreWords)&&this.scoreInfoGlyphs.set(n.ScoreWords,new Ba(0,0,"Words by "+t.words,i.wordsFont,C.Left)));const s=new ca(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(n.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let i of t.staves)if(!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature){e.push(i);break}if(e.length>0){this.tuningGlyph=new wr(0,0),this.tuningGlyph.renderer=s;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(e.isNotationElementVisible(n.ChordDiagrams)){this.chordDiagrams=new ur(0,0),this.chordDiagrams.renderer=s;let e=new Map;for(let t of this.renderer.tracks)for(let i of t.staves)for(const[t,s]of i.chords)e.has(t)||s.showDiagram&&(e.set(t,s),this.chordDiagrams.addChord(s))}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let t=new br;t.layout=this;for(let i=0;i<this.renderer.tracks.length;i++){let s=this.renderer.tracks[i],a=!1;for(let e of s.staves)if(e.showStandardNotation){a=!0;break}for(let r=0;r<s.staves.length;r++){let n,o=s.staves[r];if(o.isPercussion)n=e.StaveProfile.Score;else if(this.renderer.settings.display.staveProfile!==e.StaveProfile.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=e.StaveProfile.ScoreTab;else if(o.showTablature)n=a?e.StaveProfile.TabMixed:e.StaveProfile.Tab;else{if(!o.showStandardNotation)continue;n=e.StaveProfile.Score}let h=to.staveProfiles.get(n);for(let e of h)e.canCreate(s,o)&&t.addStaff(s,new pr(i,o,e))}}return t}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let i=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(i)?this._barRendererLookup.get(e).get(i):null}renderAnnotation(){let e=this.renderer.canvas,t=this.renderer.settings.display.resources,i=12*this.renderer.settings.display.scale,s=2*i;this.height+=s;let a=this.width/2;e.beginRender(this.width,s),e.color=t.mainGlyphColor,e.font=new we(t.copyrightFont.family,i,o.Bold),e.textAlign=C.Center,e.fillText("rendered by alphaTab",a,i);let r=e.endRender(),n=new hs;n.width=this.width,n.height=s,n.renderResult=r,n.totalWidth=this.width,n.totalHeight=this.height,n.firstMasterBarIndex=-1,n.lastMasterBarIndex=-1,this.renderer.partialRenderFinished.trigger(n)}}class Br{constructor(){this.width=0,this.masterBars=[]}}class Tr extends _r{constructor(e){super(e),this._group=null,this._pagePadding=null}get name(){return"HorizontalScreen"}get supportsResize(){return!1}resize(){}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Tr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this.renderer.score,t=this.renderer.canvas,i=this.renderer.settings.display.startBar;i--,i=Math.min(e.masterBars.length-1,Math.max(0,i));let s=i,a=this.renderer.settings.display.barCount;a<=0&&(a=e.masterBars.length),a=i+a-1,a=Math.min(e.masterBars.length-1,Math.max(0,a)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let r=this.renderer.settings.display.barCountPerPartial,n=[],o=new Br;for(;s<=a;){let t=this._group.addBars(this.renderer.tracks,s);if(t)if(0===o.masterBars.length&&t.isLinkedToPrevious&&n.length>0){let i=n[n.length-1];i.masterBars.push(e.masterBars[s]),i.width+=t.width}else o.masterBars.push(e.masterBars[s]),o.width+=t.width,o.masterBars.length>=r&&(0===n.length&&(o.width+=this._group.x+this._group.accoladeSpacing),n.push(o),Fe.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null),o=new Br);s++}o.masterBars.length>0&&(0===n.length&&(o.width+=this._group.x+this._group.accoladeSpacing),n.push(o),Fe.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null)),this._group.finalizeGroup(),this.height=this._group.y+this._group.height+this._pagePadding[3],this.width=this._group.x+this._group.width+this._pagePadding[2],s=0;for(let e=0;e<n.length;e++){let i=n[e];t.beginRender(i.width,this.height),t.color=this.renderer.settings.display.resources.mainGlyphColor,t.textAlign=C.Left;let a=this._group.getBarX(i.masterBars[0].index)+this._group.accoladeSpacing;0===e&&(a-=this._group.x+this._group.accoladeSpacing),Fe.debug(this.name,"Rendering partial from bar "+i.masterBars[0].index+" to "+i.masterBars[i.masterBars.length-1].index,null),this._group.paintPartial(-a,this._group.y,this.renderer.canvas,s,i.masterBars.length);let r=t.endRender(),o=new hs;o.totalWidth=this.width,o.totalHeight=this.height,o.width=i.width,o.height=this.height,o.renderResult=r,o.firstMasterBarIndex=i.masterBars[0].index,o.lastMasterBarIndex=i.masterBars[i.masterBars.length-1].index,this.renderer.partialRenderFinished.trigger(o),s+=i.masterBars.length}}}Tr.PagePadding=[20,20,20,20],Tr.GroupSpacing=20;class kr extends _r{constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}get name(){return"PageView"}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=kr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this._pagePadding[0],t=this._pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],t=this.layoutAndRenderScoreInfo(e,t,-1),t=this.layoutAndRenderTunings(t,-1),t=this.layoutAndRenderChordDiagrams(t,-1),t=this.layoutAndRenderScore(e,t),this.height=t+this._pagePadding[3]}get supportsResize(){return!0}resize(){let e=this._pagePadding[0],t=this._pagePadding[1];this.width=this.renderer.width;let i=this.height;t=this.layoutAndRenderScoreInfo(e,t,i),t=this.layoutAndRenderTunings(t,i),t=this.layoutAndRenderChordDiagrams(t,i),t=this.resizeAndRenderScore(e,t,i),this.height=t+this._pagePadding[3]}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let i=this.renderer.settings.display.resources;this.tuningGlyph.width=this.width,this.tuningGlyph.doLayout();let s=this.tuningGlyph.height+11*this.scale;e+=s;let a=this.renderer.canvas;a.beginRender(this.width,s),a.color=i.scoreInfoColor,a.textAlign=C.Center,this.tuningGlyph.paint(this._pagePadding[0],0,a);let r=a.endRender(),n=new hs;return n.width=this.width,n.height=s,n.renderResult=r,n.totalWidth=this.width,n.totalHeight=t<0?e:t,n.firstMasterBarIndex=-1,n.lastMasterBarIndex=-1,this.renderer.partialRenderFinished.trigger(n),e}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;let i=this.renderer.settings.display.resources;this.chordDiagrams.width=this.width,this.chordDiagrams.doLayout();let s=this.renderer.canvas;s.beginRender(this.width,this.chordDiagrams.height),s.color=i.scoreInfoColor,s.textAlign=C.Center,this.chordDiagrams.paint(0,0,s);let a=s.endRender();e+=this.chordDiagrams.height;let r=new hs;return r.width=this.width,r.height=this.chordDiagrams.height,r.renderResult=a,r.totalWidth=this.width,r.totalHeight=t<0?e:t,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.renderer.partialRenderFinished.trigger(r),e}layoutAndRenderScoreInfo(e,t,i=-1){Fe.debug(this.name,"Layouting score info");let s=this.scale,a=this.renderer.settings.display.resources,r=[n.ScoreTitle,n.ScoreSubTitle,n.ScoreArtist,n.ScoreAlbum,n.ScoreWordsAndMusic];for(let e=0;e<r.length;e++)if(this.scoreInfoGlyphs.has(r[e])){let i=this.scoreInfoGlyphs.get(r[e]);i.x=this.width/2,i.y=t,i.textAlign=C.Center,t+=i.font.size*s}let o=!1,h=0;if(this.scoreInfoGlyphs.has(n.ScoreMusic)){let e=this.scoreInfoGlyphs.get(n.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=t,e.textAlign=C.Right,o=!0,h=e.font.size*s}if(this.scoreInfoGlyphs.has(n.ScoreWords)){let i=this.scoreInfoGlyphs.get(n.ScoreWords);i.x=e,i.y=t,i.textAlign=C.Left,o=!0,h=i.font.size*s}o&&(t+=h),t+=17*this.scale;let l=this.renderer.canvas;l.beginRender(this.width,t),l.color=a.scoreInfoColor,l.textAlign=C.Center;for(const e of this.scoreInfoGlyphs.values())e.paint(0,0,l);let c=l.endRender(),d=new hs;return d.width=this.width,d.height=t,d.renderResult=c,d.totalWidth=this.width,d.totalHeight=i<0?t:i,d.firstMasterBarIndex=-1,d.lastMasterBarIndex=-1,this.renderer.partialRenderFinished.trigger(d),t}resizeAndRenderScore(e,t,i){let s=this.renderer.canvas;if(-1!==this.renderer.settings.display.barsPerRow)for(let e=0;e<this._groups.length;e++){let a=this._groups[e];this.fitGroup(a),a.finalizeGroup(),t+=this.paintGroup(a,i,s)}else{this._groups=[];let a=0,r=this.maxWidth,n=this.createEmptyStaveGroup();for(n.index=this._groups.length,n.x=e,n.y=t;a<this._allMasterBarRenderers.length;){let o=this._allMasterBarRenderers[a];if(n.width+o.width<=r||0===n.masterBarsRenderers.length)n.addMasterBarRenderers(this.renderer.tracks,o),a++;else{for(;o&&!o.canWrap&&n.masterBarsRenderers.length>1;)o=n.revertLastBar(),a--;n.isFull=!0,n.isLast=this.lastBarIndex===n.lastBarIndex,this._groups.push(n),this.fitGroup(n),n.finalizeGroup(),t+=this.paintGroup(n,i,s),n=this.createEmptyStaveGroup(),n.index=this._groups.length,n.x=e,n.y=t}}n.isLast=this.lastBarIndex===n.lastBarIndex,this.fitGroup(n),n.finalizeGroup(),t+=this.paintGroup(n,i,s)}return t}layoutAndRenderScore(e,t){let i=this.renderer.canvas,s=this.firstBarIndex,a=this.lastBarIndex;for(this._groups=[];s<=a;){let r=this.createStaveGroup(s,a);this._groups.push(r),r.x=e,r.y=t,s=r.lastBarIndex+1,this.fitGroup(r),r.finalizeGroup(),Fe.debug(this.name,"Rendering partial from bar "+r.firstBarIndex+" to "+r.lastBarIndex,null),t+=this.paintGroup(r,t,i)}return t}paintGroup(e,t,i){let s=e.height+20*this.scale;i.beginRender(this.width,s),this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=C.Left,e.paint(0,-e.y,i),t+=s;let a=i.endRender(),r=new hs;return r.totalWidth=this.width,r.totalHeight=t,r.width=this.width,r.height=s,r.renderResult=a,r.firstMasterBarIndex=e.firstBarIndex,r.lastMasterBarIndex=e.lastBarIndex,this.renderer.partialRenderFinished.trigger(r),s}fitGroup(e){(e.isFull||e.width>this.maxWidth)&&e.scaleToWidth(this.maxWidth),this.width=Math.max(this.width,e.width)}createStaveGroup(e,t){let i=this.createEmptyStaveGroup();i.index=this._groups.length;let s=this.renderer.settings.display.barsPerRow,a=this.maxWidth,r=t+1;for(let t=e;t<r;t++){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)i.addMasterBarRenderers(this.renderer.tracks,e),t=e.masterBar.index;else{let e=i.addBars(this.renderer.tracks,t);e&&this._allMasterBarRenderers.push(e)}this._barsFromPreviousGroup=[];let e=!1;if((-1===s&&i.width>=a&&0!==i.masterBarsRenderers.length||i.masterBarsRenderers.length===s+1)&&(e=!0),e){let e=i.revertLastBar();if(e)for(this._barsFromPreviousGroup.push(e);e&&!e.canWrap&&i.masterBarsRenderers.length>1;)e=i.revertLastBar(),e&&this._barsFromPreviousGroup.push(e);return i.isFull=!0,i.isLast=!1,this._barsFromPreviousGroup.reverse(),i}i.x=0}return i.isLast=t===i.lastBarIndex,i}get maxWidth(){return this.renderer.width-this._pagePadding[0]-this._pagePadding[2]}}kr.PagePadding=[40,40,40,40],kr.GroupSpacing=20;class vr extends Cs{constructor(e,t,i,s=!1){super(e,t,s?Fs.GraceScale:1,vr.getMusicSymbol(i)),this._isGrace=s,this._accidentalType=i}static getMusicSymbol(e){switch(e){case se.Natural:return E.AccidentalNatural;case se.Sharp:return E.AccidentalSharp;case se.Flat:return E.AccidentalFlat;case se.NaturalQuarterNoteUp:return E.AccidentalQuarterToneNaturalArrowUp;case se.SharpQuarterNoteUp:return E.AccidentalQuarterToneSharpArrowUp;case se.FlatQuarterNoteUp:return E.AccidentalQuarterToneFlatArrowUp;case se.DoubleSharp:return E.AccidentalDoubleSharp;case se.DoubleFlat:return E.AccidentalDoubleFlat}return E.None}doLayout(){switch(this._accidentalType){case se.DoubleFlat:this.width=18;break;default:this.width=8}this.width=this.width*(this._isGrace?Fs.GraceScale:1)*this.scale}}class Nr extends Ps{constructor(e,t,i){super(e,t),this._number=0,this._number=i}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString())+5*this.scale}paint(e,t,i){if(!this.renderer.staff.isFirstInAccolade)return;let s=this.renderer.resources,a=i.color;i.color=s.barNumberColor,i.font=s.barNumberFont,i.fillText(this._number.toString(),e+this.x,t+this.y),i.color=a}}class xr extends Ps{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15*this.scale:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2*this.scale:(this.width=2*this.scale,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2*this.scale))}paint(e,t,i){let s=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a;this.renderer.isLast?(i.fillRect(n+this.width-s-s,a,this.scale,o),i.fillRect(n+this.width-s,a,s,o)):this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart||(i.fillRect(n+this.width-this.scale,a,this.scale,o),this.renderer.bar.masterBar.isDoubleBar&&i.fillRect(n+this.width-5*this.scale,a,this.scale,o))}}class Pr extends Cs{constructor(e,t,i,s){super(e,t,1,Pr.getSymbol(i)),this._clef=i,this._clefOttava=s}doLayout(){switch(this._clef){case u.Neutral:this.width=15*this.scale;break;case u.C3:case u.C4:case u.F4:case u.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case u.Neutral:return E.UnpitchedPercussionClef1;case u.C3:case u.C4:return E.CClef;case u.F4:return E.FClef;case u.G2:return E.GClef;default:return E.None}}paint(e,t,i){let s;super.paint(e,t,i);let a=!1;switch(this._clefOttava){case p._15ma:s=new Cs(-4*this.scale,0,.5,E.Quindicesima),a=!0;break;case p._8va:s=new Cs(-2*this.scale,0,.5,E.Ottava),a=!0;break;case p._8vb:s=new Cs(-6*this.scale,0,.5,E.Ottava);break;case p._15mb:s=new Cs(-8*this.scale,0,.5,E.Quindicesima);break;default:return}let r=0,n=0;switch(this._clef){case u.Neutral:r=a?-12:15,n=0;break;case u.C3:case u.C4:r=a?-19:27,n=0;break;case u.F4:r=a?-9:27,n=-4;break;case u.G2:r=a?-37:30,n=0;break;default:return}s.renderer=this.renderer,s.doLayout();let o=this.width/2;s.paint(e+this.x+o+n*this.scale,t+this.y+r*this.scale,i)}}class Er extends Ps{constructor(e,t){super(e,t)}doLayout(){this.width=11*this.scale}paint(e,t,i){let s=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a,h=1.5*this.scale,l=(a+r)/2;i.fillCircle(n,l-3*h,h),i.fillCircle(n,l+3*h,h),n+=4*this.scale,i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke(),n+=3*this.scale+.5,i.fillRect(n,a,s,o)}}class Cr extends Ps{constructor(e,t,i){super(e,t),this._count=0,this._count=0,this._count=i}doLayout(){this.width=0}paint(e,t,i){let s=this.renderer.resources,a=i.textAlign;i.font=s.barNumberFont,i.textAlign=C.Right;let r="x"+this._count,n=i.measureText(r)/1.5;i.fillText(r,e+this.x-n,t+this.y),i.textAlign=a}}class Fr extends Ps{constructor(e,t,i,s){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=s,this._circleSize=i}doLayout(){this.width=13*this.scale}paint(e,t,i){let s=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x+.5,o=r-a;i.fillRect(n,a,s,o),n+=2*s-.5,i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke(),n+=3*this.scale;let h=this._circleSize*this.scale,l=(a+r)/2;i.fillCircle(n,l-h*this._dotOffset,h),i.fillCircle(n,l+h*this._dotOffset,h)}}class Lr extends Cs{constructor(e,t,i){super(e,t,1,Lr.getSymbol(i))}static getSymbol(e){switch(e){case c.None:return E.None;case c.Normal:return E.ArticAccentAbove;case c.Heavy:return E.ArticMarcatoAbove;default:return E.None}}doLayout(){this.width=9*this.scale,this.height=9*this.scale}paint(e,t,i){super.paint(e-2*this.scale,t+this.height,i)}}class Mr extends Ps{constructor(e,t,i){super(e,t),this._size=0,this._size=i}doLayout(){this.width=this._size+3*this.scale}paint(e,t,i){i.fillCircle(e+this.x,t+this.y,this._size)}}class Ir extends Cs{constructor(e,t,i){super(e,t,i?Fs.GraceScale:1,E.NoteheadXOrnate),this._isGrace=i}doLayout(){this.width=9*(this._isGrace?Fs.GraceScale:1)*this.scale,this.height=Fs.NoteHeadHeight*this.scale}}class Dr extends Cs{constructor(e,t,i,s){super(e,t,s?Fs.GraceScale:1,Dr.getSymbol(i)),this._isGrace=s}static getSymbol(e){switch(e){case S.QuadrupleWhole:case S.DoubleWhole:case S.Whole:case S.Half:return E.NoteheadDiamondWhiteWide;default:return E.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Fs.GraceScale:1)*this.scale,this.height=Fs.NoteHeadHeight*this.scale}}class Ar extends Ps{constructor(e,t,i){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=U.Up,this.startBeat=e,this.endBeat=t,this.forEnd=i}doLayout(){this.width=0}paint(e,t,i){if(!this.endBeat)return;let s=this.startNoteRenderer=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.endNoteRenderer=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar),r=0,n=0,o=0,h=0,l=!1;this.tieDirection=s?this.getBeamDirection(this.startBeat,s):this.getBeamDirection(this.endBeat,a),!this.forEnd&&s?(s!==a?(r=e+s.x+this.getStartX(),o=t+s.y+this.getStartY()+this.yOffset,a&&s.staff===a.staff?(n=e+a.x+this.getEndX(),h=t+a.y+this.getEndY()+this.yOffset):(n=e+s.x+s.width,h=o)):(r=e+s.x+this.getStartX(),n=e+a.x+this.getEndX(),o=t+s.y+this.getStartY()+this.yOffset,h=t+a.y+this.getEndY()+this.yOffset),l=!0):s&&s.staff===a.staff||(r=e+a.x,n=e+a.x+this.getEndX(),o=t+a.y+this.getEndY()+this.yOffset,h=o,l=!0),l&&(this.shouldDrawBendSlur()?Ar.drawBendSlur(i,r,o,n,h,this.tieDirection===U.Down,this.scale):Ar.paintTie(i,this.scale,r,o,n,h,this.tieDirection===U.Down,this.getTieHeight(r,o,n,h),4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,i,s){return 22}getBeamDirection(e,t){return U.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static paintTie(e,t,i,s,a,r,n=!1,o=22,h=4){if(i===a&&s===r)return;if(a<i){let e=i;i=a,a=e,e=s,s=r,r=e}o*=t,h*=t;let l=r-s,c=a-i,d=Math.sqrt(l*l+c*c);n?l*=-1:c*=-1,l/=d,c/=d;let u=(a+i)/2,p=(r+s)/2,g=u+o*l,f=p+o*c,m=u+(o-h)*l,y=p+(o-h)*c;e.beginPath(),e.moveTo(i,s),e.quadraticCurveTo(g,f,a,r),e.quadraticCurveTo(m,y,i,s),e.closePath(),e.fill()}static drawBendSlur(e,t,i,s,a,r,n,o){let h=a-i,l=s-t,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(s+t)/2,u=(a+i)/2,p=Ar.BendSlurHeight*n;s-t<20&&(p/=2);let g=d+p*h,f=u+p*l;if(e.beginPath(),e.moveTo(t,i),e.lineTo(g,f),e.lineTo(s,a),e.stroke(),o){let t=e.measureText(o),i=r?0:-e.font.size;e.fillText(o,g-t/2,f+i)}}}Ar.BendSlurHeight=11;class Rr extends Ps{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=Rr.Size*this.scale}paint(e,t,i){this._isOpen?Ar.paintTie(i,this.scale,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):Ar.paintTie(i,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}Rr.Size=6;class Or{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class Gr extends Ps{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){let t=this.renderer,i=t.getNoteLine(e),s=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(n.ParenthesisOnTiedBends);this.addParenthesisOnLine(i,s)}addParenthesisOnLine(e,t){let i=new Or(e,t);this._infos.push(i),t&&(this.isEmpty=!1)}isTiedBend(e){return!!e.isTieDestination&&(!!e.tieOrigin.hasBend||this.isTiedBend(e.tieOrigin))}doLayout(){let e=this.renderer;this._infos.sort(((e,t)=>e.line-t.line));let t=null,i=e.getScoreHeight(1);for(let s=0,a=this._infos.length;s<a;s++){let a;if(this._infos[s].isGhost)if(t){let a=e.getScoreY(this._infos[s].line)+i;t.height=a-t.y}else a=new Rr(this._isOpen),a.renderer=this.renderer,a.y=e.getScoreY(this._infos[s].line)-i,a.height=2*i,a.doLayout(),this._glyphs.push(a),t=a;else t=null}this.width=this._glyphs.length>0?this._glyphs[0].width:0}paint(e,t,i){super.paint(e,t,i);for(let s of this._glyphs)s.paint(e+this.x,t+this.y,i)}}class Vr{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class Hr extends Ps{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){let i=new Vr(e,t);this._infos.push(i),(!this.minNote||this.minNote.line>i.line)&&(this.minNote=i),(!this.maxNote||this.maxNote.line<i.line)&&(this.maxNote=i)}get hasTopOverflow(){return!!this.minNote&&this.minNote.line<=0}get hasBottomOverflow(){return!!this.maxNote&&this.maxNote.line>8}doLayout(){this._infos.sort(((e,t)=>t.line-e.line));let e=0,t=!1,i=0,s=!1,a=this.direction,r=0;for(let n=0,o=this._infos.length;n<o;n++){let o=this._infos[n].glyph;o.renderer=this.renderer,o.doLayout();let h=!1;0===n?e=o.width:Math.abs(i-this._infos[n].line)<=1?t?t=!1:(h=!0,o.x=e,s=!0,t=!0):t=!1,a===U.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,i=this._infos[n].line,r=Math.max(r,o.x+o.width)}s?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===U.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,i){e+=this.x,t+=this.y;let s=this.renderer,a=3*this.scale,r=this.width-this.noteStartX+2*a;if(this.hasTopOverflow){let n=i.color;i.color=s.resources.staffLineColor;let o=-2;for(;o>=this.minNote.line;){let n=t+s.getScoreY(o);i.fillRect(e-a+this.noteStartX,n,r,this.scale),o-=2}i.color=n}if(this.hasBottomOverflow){let n=i.color;i.color=s.resources.staffLineColor;let o=10;for(;o<=this.maxNote.line;){let n=t+s.getScoreY(o);i.fillRect(e-a+this.noteStartX,n,r,this.scale),o+=2}i.color=n}let n=this._infos,o=e+this._noteHeadPadding;for(let e of n)e.glyph.renderer=this.renderer,e.glyph.paint(o,t,i)}}class Wr extends Cs{constructor(e,t,i){super(e,t,1,Wr.getSymbol(i))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case S.ThirtySecond:return E.Tremolo3;case S.Sixteenth:return E.Tremolo2;case S.Eighth:return E.Tremolo1;default:return E.None}}}class Ur extends Hr{constructor(){super(),this._noteGlyphLookup=new Map,this._notes=[],this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){let i=this._noteGlyphLookup.get(e.id),s=this.x+i.x+this._noteHeadPadding;switch(t){case re.Left:break;case re.Center:s+=i.width/2;break;case re.Right:s+=i.width}return s}return 0}getNoteY(e,t){if(this._noteGlyphLookup.has(e.id)){const i=this._noteGlyphLookup.get(e.id);let s=this.y+i.y;switch(t){case ae.TopWithStem:s-=this.renderer.getStemSize(this.beamingHelper);break;case ae.Top:s-=i.height/2;break;case ae.Center:break;case ae.Bottom:s+=i.height/2;break;case ae.BottomWithStem:s+=this.renderer.getStemSize(this.beamingHelper)}return s}return 0}addNoteGlyph(e,t,i){super.add(e,i),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();let e=this.direction;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout();for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout();if(this.beat.isTremolo){let t=0,i=e===U.Up?this.minNote:this.maxNote,s=e===U.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case S.ThirtySecond:t=e===U.Up?-15:15;break;case S.Sixteenth:t=e===U.Up?-12:15;break;case S.Eighth:t=e===U.Up?-10:10;break;default:t=e===U.Up?-10:15}this._tremoloPicking=new Wr(s,i.glyph.y+t*this.scale,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,i){for(let s of this._notes)if(this._noteGlyphLookup.has(s.id)){let a=this._noteGlyphLookup.get(s.id),r=new us;r.note=s,r.noteHeadBounds=new ht,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=i+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,i){let s=this.renderer,a=0,r=0,n=1,o=-n;this.beamingHelper.direction===U.Up?(r=s.getScoreY(this.minNote.line),a=s.getScoreY(this.maxNote.line-2)):(r=s.getScoreY(this.maxNote.line-1),a=s.getScoreY(this.minNote.line+1),o*=-1,n*=-1);for(const s of this.aboveBeatEffects.values())a+=o*s.height,s.paint(e+this.x+2*this.scale,t+this.y+a,i);for(const s of this.belowBeatEffects.values())r+=n*s.height,s.paint(e+this.x+2*this.scale,t+this.y+r,i);super.paint(e,t,i),this._tremoloPicking&&this._tremoloPicking.paint(e,t,i)}}class zr extends Cs{constructor(e,t,i){super(e,t,1,zr.getSymbol(i)),this._duration=i}static getSymbol(e){switch(e){case S.QuadrupleWhole:return E.RestLonga;case S.DoubleWhole:return E.RestDoubleWhole;case S.Whole:return E.RestWhole;case S.Half:return E.RestHalf;case S.Quarter:return E.RestQuarter;case S.Eighth:return E.RestEighth;case S.Sixteenth:return E.RestSixteenth;case S.ThirtySecond:return E.RestThirtySecond;case S.SixtyFourth:return E.RestSixtyFourth;case S.OneHundredTwentyEighth:return E.RestOneHundredTwentyEighth;case S.TwoHundredFiftySixth:return E.RestTwoHundredFiftySixth;default:return E.None}}static getSize(e){switch(e){case S.QuadrupleWhole:case S.DoubleWhole:case S.Whole:case S.Half:case S.Quarter:case S.Eighth:case S.Sixteenth:return 9;case S.ThirtySecond:return 12;case S.SixtyFourth:return 14;case S.OneHundredTwentyEighth:case S.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=zr.getSize(this._duration)*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class Xr{constructor(){this.x=0,this.y=-3e3,this.width=0}}class Yr extends $s{constructor(){super(0,0)}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);this.glyphs.sort(((e,t)=>e.y<t.y?-1:e.y>t.y?1:0));let e=[];e.push(new Xr);let t=21*this.scale;for(let i=0,s=this.glyphs.length;i<s;i++){let s=this.glyphs[i];s.renderer=this.renderer,s.doLayout();let a=0;for(;e[a].y>s.y;)a++,a===e.length&&e.push(new Xr);s.x=a,e[a].y=s.y+t,e[a].width<s.width&&(e[a].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];const s=e[i.x];i.x=this.width-s.x}}}class qr extends Hr{constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new Yr,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new Gr(!0),this._postNoteParenthesis=new Gr(!1))}get direction(){return U.Up}containsNoteValue(e){return this._noteValueLookup.has(e)}getNoteValueY(e){return this._noteValueLookup.has(e)?this.y+this._noteValueLookup.get(e).y:0}addGlyph(e,t=!1){let i=this.renderer,s=new Fs(0,0,S.Quarter,!0),a=i.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),r=i.accidentalHelper.getNoteLineForValue(e,!1);if(s.y=i.getScoreY(r),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(r,!0),this._postNoteParenthesis.addParenthesisOnLine(r,!0)),a!==se.None){let e=new vr(0,s.y,a,!0);e.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,s),this.add(s,r),this.isEmpty=!1}doLayout(){let e=0;this._showParenthesis&&(this._preNoteParenthesis.x=e,this._preNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.doLayout(),e+=this._preNoteParenthesis.width+qr.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+qr.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+qr.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+qr.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+qr.ElementPadding*this.scale)}paint(e,t,i){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,i),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,i),this._postNoteParenthesis.paint(e+this.x,t+this.y,i)),super.paint(e,t,i)}}qr.ElementPadding=2;class Jr extends Ps{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,i,s,a,r,n,o){Ar.drawBendSlur(e,t,i,s,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10*this.scale}getTieDirection(e,t){switch(t.getBeatDirection(e)){case U.Up:return U.Down;default:return U.Up}}}Jr.EndPadding=8;class Qr extends Pe{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class jr extends Ps{constructor(){super(0,0),this._notes=[],this._renderPoints=new Map,this._preBendMinValue=-1,this._bendMiddleMinValue=-1,this._bendEndMinValue=-1,this._bendEndContinuedMinValue=-1,this._releaseMinValue=-1,this._releaseContinuedMinValue=-1,this._maxBendValue=-1}addBends(e){this._notes.push(e);let t=this.createRenderingPoints(e);this._renderPoints.set(e.id,t),(-1===this._maxBendValue||this._maxBendValue<e.maxBendPoint.value)&&(this._maxBendValue=e.maxBendPoint.value);let i=0;switch(e.bendType){case m.Bend:i=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||i<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=i):(-1===this._bendEndMinValue||i<this._bendEndMinValue)&&(this._bendEndMinValue=i);break;case m.Release:i=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i);break;case m.BendRelease:i=t[1].value,(-1===this._bendMiddleMinValue||i<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=i),i=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i);break;case m.Prebend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i);break;case m.PrebendBend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i),i=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||i<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=i):(-1===this._bendEndMinValue||i<this._bendEndMinValue)&&(this._bendEndMinValue=i);break;case m.PrebendRelease:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i),i=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i)}}doLayout(){super.doLayout();let e=this._maxBendValue*jr.BendValueHeight*this.scale;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let i=this._renderPoints.get(e.id);switch(e.bendType){case m.Bend:i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case m.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t);break;case m.BendRelease:i[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[2].lineValue=t);break;case m.Prebend:i[0].lineValue=this._preBendMinValue;break;case m.PrebendBend:i[0].lineValue=this._preBendMinValue,i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case m.PrebendRelease:i[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){let t=[];switch(e.bendType){case m.Custom:for(let i of e.bendPoints)t.push(new Qr(i.offset,i.value));break;case m.BendRelease:t.push(new Qr(0,e.bendPoints[0].value)),t.push(new Qr(Pe.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new Qr(Pe.MaxPosition,e.bendPoints[3].value));break;case m.Bend:case m.Hold:case m.Prebend:case m.PrebendBend:case m.PrebendRelease:case m.Release:t.push(new Qr(0,e.bendPoints[0].value)),t.push(new Qr(Pe.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,i){let s=i.color;this._notes.length>1&&(i.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,h=!1,l=null,c=!1,d=a.bendStyle===f.Gradual?"grad.":"",u=null;for(;o.isTieOrigin;){let 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){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,y=t+n.y;p=e+n.x,r[0].value>0||a.isContinuedBend?p+=n.getBeatX(a.beat,ie.MiddleNotes):p+=n.getNoteX(a,re.Right),g=!u||u.isLastOfVoice&&!c?e+l.x+l.postBeatGlyphsStart:c||!u.nextBeat?e+l.x+l.getBeatX(u,ie.MiddleNotes):a.bendType===m.Hold?e+l.x+l.getBeatX(u.nextBeat,ie.OnNotes):e+l.x+l.getBeatX(u.nextBeat,ie.PreNotes),h||(g-=jr.ArrowSize*this.scale);let b=(g-p)/Pe.MaxPosition;i.beginPath();for(let e=0,t=r.length-1;e<t;e++){let t=r[e],s=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new Qr(0,0),t,p,y,b,d,i),a.bendType!==m.Prebend?(0===e&&(p+=2*this.scale),this.paintBend(a,t,s,p,y,b,d,i)):a.isTieOrigin&&a.tieDestination.hasBend&&(s=new Qr(Pe.MaxPosition,t.value),s.lineValue=t.lineValue,this.paintBend(a,t,s,p,y,b,d,i))}i.color=s}}paintBend(e,t,i,s,a,r,n,o){let h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=s+r*t.offset,u=jr.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?i.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,ae.Top):p+=h.getNoteY(e,ae.Center):p+=c;let g=s+r*i.offset,f=a-u*i.lineValue;0===i.lineValue?f+=h.getNoteY(e,ae.Center):f+=c;let m=0,y=jr.ArrowSize*this.scale;if(i.value>t.value?(f+y>p&&(f=p-y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f+y),o.lineTo(g+.5*y,f+y),o.closePath(),o.fill(),m=y):i.value!==t.value&&(f<p&&(f=p+y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f-y),o.lineTo(g+.5*y,f-y),o.closePath(),o.fill(),m=-y),o.stroke(),t.value===i.value){if(t.lineValue>0){let e=g,t=jr.DashSize*this.scale,i=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>i;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,f+m),o.stroke()):(o.moveTo(d,p),o.lineTo(g,f),o.stroke());if(n&&t.offset<i.offset){o.font=l.graceFont;let e=o.measureText(n),t=0,i=0;if(p>f){let s=Math.abs(p-f);t=s>1.3*o.font.size?p-s/2:p,i=(d+g-e)/2}else t=p,i=g-e;o.fillText(n,i,t)}if(0!==i.value&&t.value!==i.value){let e=i.value,s=i.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){let t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=jr.getFractionSign(e)),""!==r){f=a-u*i.value;let e=f;s||(e=p+1*Math.abs(f-p)/3),o.font=l.tablatureFont;let t=o.measureText(r),n=e-.5*l.tablatureFont.size-2*this.scale,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return e+"/ 4"}}}jr.ArrowSize=6,jr.DashSize=3,jr.BendValueHeight=6;class Kr extends Ps{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===L.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case L.Dive:case L.Hold:case L.PrediveDive:case L.Predive:t.push(new Pe(0,e.whammyBarPoints[0].value)),t.push(new Pe(Pe.MaxPosition,e.whammyBarPoints[1].value));break;case L.Dip:t.push(new Pe(0,e.whammyBarPoints[0].value)),t.push(new Pe(Pe.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new Pe(Pe.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===e.NotationMode.SongBook&&this._beat.whammyBarType===L.Dip;let t=null,i=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!t||t.value>s.minWhammyPoint.value)&&(t=s.minWhammyPoint),(!i||i.value<s.maxWhammyPoint.value)&&(i=s.maxWhammyPoint),s=s.nextBeat;let a=i.value>0?Math.abs(this.getOffset(i.value)):0;(a>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(n.ZerosOnDiveWhammys))&&(a+=2*this.renderer.resources.tablatureFont.size);let r=t.value<0?Math.abs(this.getOffset(t.value)):0;this.renderer.registerOverflowTop(a+r),a>this.renderer.staff.getSharedLayoutData(Kr.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(Kr.TopOffsetSharedDataKey,a)}getOffset(e){if(0===e)return 0;let t=Kr.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*Kr.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(t,i,s){let a=this.renderer,r=this._beat.nextBeat,n=null,o=ie.PreNotes;r&&(n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.voice.bar),n&&n.staff===a.staff&&(n===a||r.hasWhammyBar)?o=!r.hasWhammyBar||a.settings.notation.notationMode===e.NotationMode.SongBook&&r.whammyBarType===L.Dip?ie.PreNotes:ie.MiddleNotes:(r=null,n=null));let h=0,l=0;this._isSimpleDip?(h=t+a.x+a.getBeatX(this._beat,ie.OnNotes)-2*this.scale,l=t+a.x+a.getBeatX(this._beat,ie.PostNotes)+2*this.scale):(h=t+a.x+a.getBeatX(this._beat,ie.MiddleNotes),l=n?t+n.x+n.getBeatX(r,o):t+a.x+a.width-2*this.scale);let c=s.textAlign;if(s.textAlign=C.Center,this._renderPoints.length>=2){let e=(l-h)/Pe.MaxPosition;s.beginPath();let t=i+this.renderer.staff.getSharedLayoutData(Kr.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===f.Gradual?"grad.":"";for(let i=0,r=this._renderPoints.length-1;i<r;i++){let n=this._renderPoints[i],o=this._renderPoints[i+1],l=i<r-2?this._renderPoints[i+2]:null,c=0===i;0!==i||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new Pe(0,0),n,o,h,t,e,s),c=!1),this.paintWhammy(c,n,o,l,h,t,e,s,a),a=""}s.stroke()}s.textAlign=c}paintWhammy(e,t,i,s,a,r,o,h,l){let c=a+o*t.offset,d=a+o*i.offset,u=r-this.getOffset(t.value),p=r-this.getOffset(i.value);if(t.offset===i.offset){let e=Kr.DashSize*this.scale;if(Math.abs(p-u)/(2*e)<1)h.moveTo(c,u),h.lineTo(d,p);else{let t=Math.max(u,p),i=Math.min(u,p);for(;t>i;)h.moveTo(c,i),h.lineTo(c,i+e),i+=2*e}h.stroke()}else if(t.value===i.value){let e=Kr.DashSize*this.scale;if(Math.abs(d-c)/(2*e)<1)h.moveTo(c,u),h.lineTo(d,p);else{let t=Math.max(c,d),i=Math.min(c,d);for(;t>i;)h.moveTo(t,u),h.lineTo(t-e,u),t-=2*e}h.stroke()}else h.moveTo(c,u),h.lineTo(d,p);let g=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=u;e-=g.tablatureFont.size+2*this.scale,this.renderer.settings.notation.isNotationElementVisible(n.ZerosOnDiveWhammys)&&h.fillText("0",c,e),l&&(e-=g.tablatureFont.size+2*this.scale,h.fillText(l,c,e))}let f=Math.abs(i.value);if((0!==f||this.renderer.settings.notation.isNotationElementVisible(n.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==i.value){let e="";if(i.value<0&&(e+="-"),f>=4){let t=f/4|0;e+=t,f-=4*t}else 0===f&&(e+="0");f>0&&(e+=jr.getFractionSign(f));let a=0;this._isSimpleDip?a=Math.min(u,p)-g.tablatureFont.size-2*this.scale:(a=t.offset===i.offset?Math.min(u,p):p,a-=g.tablatureFont.size+2*this.scale,s&&s.value>i.value&&(a-=2*this.scale));let r=d;h.fillText(e,r,a)}}}Kr.TopOffsetSharedDataKey="tab.whammy.topoffset",Kr.PerHalfSize=6,Kr.DashSize=3;class $r extends Jr{constructor(e){super(0,0),this._beat=e}doLayout(){let t=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case L.None:case L.Custom:case L.Hold:return;case L.Dive:case L.PrediveDive:{let e=new qr(this._beat,!1);e.renderer=this.renderer;let t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let i of this._beat.notes)i.isTieOrigin||e.addGlyph(this.getBendNoteValue(i,t),t.value%2!=0);e.doLayout(),this.BendNoteHeads.push(e)}break;case L.Dip:if(t===e.NotationMode.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+$r.SimpleDipHeight*this.scale+$r.SimpleDipPadding*this.scale}else{let t=new qr(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[1];for(let i of this._beat.notes)t.addGlyph(this.getBendNoteValue(i,this._beat.whammyBarPoints[1]),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t);let i=new qr(this._beat,!1);if(i.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let t of this._beat.notes)i.addGlyph(this.getBendNoteValue(t,e),e.value%2!=0)}i.doLayout(),this.BendNoteHeads.push(i)}break;case L.Predive:}super.doLayout()}paint(t,i,s){let a=this._beat;switch(a.whammyBarType){case L.None:case L.Custom:return}let r=this.renderer.settings.notation.notationMode,n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),o=t+n.x+n.getBeatX(a,ie.MiddleNotes),h=this.getTieDirection(a,n),l=1===this._beat.notes.length?h:U.Up,c=s.textAlign;for(let c=0;c<a.notes.length;c++){let d=a.notes[c],u=i+n.y;c>0&&c>=(this._beat.notes.length/2|0)&&(l=U.Down),l===U.Down?u+=n.getNoteY(d,ae.Bottom):u+=n.getNoteY(d,ae.Top);let p=t+n.x;a.isLastOfVoice?p+=n.width:p+=n.getBeatX(a,ie.EndBeat),p-=8*this.scale;let g=a.whammyStyle===f.Gradual&&0===c?"grad.":"",m=null;d.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,d.tieDestination.beat.voice.bar),m&&m.staff===n.staff?p=t+m.x+m.getBeatX(d.tieDestination.beat,ie.MiddleNotes):m=null);let y=Fs.NoteHeadHeight*this.scale*Fs.GraceScale*.5;l===U.Up&&(y=-y);let b=a.whammyBarPoints.length>0?this.getBendNoteValue(d,a.whammyBarPoints[a.whammyBarPoints.length-1]):0,S=0,w=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,w=!0):m&&(d.isTieOrigin&&d.tieDestination.beat.hasWhammyBar||d.beat.isContinuedWhammy)?(S=i+m.y+m.getNoteY(d.tieDestination,ae.Top),w=!0,l===U.Down&&(S+=Fs.NoteHeadHeight*this.scale)):d.isTieOrigin&&(S=m?i+m.y+m.getNoteY(d.tieDestination,ae.Top):u,l===U.Down&&(S+=Fs.NoteHeadHeight*this.scale)),a.whammyBarType){case L.Hold:d.isTieOrigin&&Ar.paintTie(s,this.scale,o,u,p,S,h===U.Down,22,4);break;case L.Dive:0===c&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(b)&&(S+=this.BendNoteHeads[0].y)),w?this.drawBendSlur(s,o,u,p,S,l===U.Down,this.scale,g):d.isTieOrigin&&Ar.paintTie(s,this.scale,o,u,p,S,h===U.Down,22,4);break;case L.Dip:if(r===e.NotationMode.SongBook){if(0===c){let e=t+n.x+n.getBeatX(this._beat,ie.OnNotes)-2*this.scale,a=t+n.x+n.getBeatX(this._beat,ie.PostNotes)+2*this.scale,r=(e+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,r,i+this.y);let h=i+this.y+s.font.size+2*this.scale,l=h+$r.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(e,l),s.lineTo(r,h),s.lineTo(a,l)):(s.moveTo(e,h),s.lineTo(r,l),s.lineTo(a,h)),s.stroke()}d.isTieOrigin&&Ar.paintTie(s,this.scale,o,u,p,S,h===U.Down,22,4)}else{let e=(o+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s);let t=this.getBendNoteValue(d,a.whammyBarPoints[1]),r=this.BendNoteHeads[0].getNoteValueY(t)+y;this.drawBendSlur(s,o,u,e,r,l===U.Down,this.scale,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=i+n.y,this.BendNoteHeads[1].paint(0,0,s),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(s,e,r,p,S,l===U.Down,this.scale,g)}break;case L.PrediveDive:case L.Predive:let f=t+n.x+n.getBeatX(d.beat,ie.PreNotes);f+=n.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let m=i+n.y+n.getScoreY(n.accidentalHelper.getNoteLineForValue(d.displayValue-(d.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(s,f,m,o,u,l===U.Down,this.scale,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,o,u,p,S,l===U.Down,this.scale,g))}}s.textAlign=c}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}$r.SimpleDipHeight=2*Kr.PerHalfSize,$r.SimpleDipPadding=2;class Zr extends Ps{constructor(e,t,i){super(e,t),this.width=i}}class en extends Cs{constructor(e,t,i,s,a){super(e,t,a?Fs.GraceScale:1,i.getSymbol(s)),this._isGrace=a,this._articulation=i}paint(e,t,i){let s=this._isGrace?this.scale:0;i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this.symbol,!1),this._articulation.techniqueSymbol!==E.None&&this._articulation.techniqueSymbolPlacement===F.Middle&&i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Fs.GraceScale:1)*this.scale;switch(this.symbol){case E.NoteheadWhole:this.width=14;break;case E.NoteheadCircleX:case E.NoteheadDiamondWhite:this.width=9;break;case E.NoteheadHeavyXHat:case E.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Fs.GraceScale:1)*this.scale,this.height=Fs.NoteHeadHeight*e}}class tn extends Cs{constructor(e,t){super(e,t,Fs.GraceScale,E.ArticStaccatoAbove)}doLayout(){this.width=Fs.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,i){super.paint(e+3*this.scale,t+5*this.scale,i)}}class sn extends Cs{constructor(e,t){super(e,t,.5,E.PictEdgeOfCymbal)}doLayout(){this.width=22*this.scale,this.height=15*this.scale}paint(e,t,i){super.paint(e-3*this.scale,t+this.height,i)}}class an extends Cs{constructor(e,t){super(e,t,Fs.GraceScale,E.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}}class rn extends ma{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.noteHeads=null,this.restGlyph=null}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,i){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,i+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph&&(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset)){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}paint(e,t,i){this._skipPaint||super.paint(e,t,i)}doLayout(){let e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);if(this.container.beat.duration===S.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2),this.restGlyph=new zr(0,e.getScoreY(t),this.container.beat.duration),this.restGlyph.beat=this.container.beat,this.restGlyph.beamingHelper=this.beamingHelper,this.addGlyph(this.restGlyph),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=ra.computeLineHeightsForRest(this.container.beat.duration);let i=this.restGlyph.y-e.getScoreHeight(t[0]),s=this.restGlyph.y+e.getScoreHeight(t[1]);this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,i,s)}else this.renderer.helpers.collisionHelper.registerRest(this.container.beat);if(this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,t),this.container.beat.dots>0){this.addGlyph(new Zr(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new $s(0,0);this.createBeatDot(t,e),this.addGlyph(e)}}}else{this.noteHeads=new Ur,this.noteHeads.beat=this.container.beat,this.noteHeads.beamingHelper=this.beamingHelper;let t=new Gr(!1);t.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));if(this.addGlyph(this.noteHeads),t.isEmpty||(this.addGlyph(new Zr(0,0,4*(this.container.beat.graceType!==_.None?Fs.GraceScale:1)*this.scale)),this.addGlyph(t)),this.container.beat.hasWhammyBar){let e=new $r(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Zr(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new $s(0,0);for(let i of this.container.beat.notes)this.createBeatDot(e.getNoteLine(i),t);this.addGlyph(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteHeads.x+this.noteHeads.width/2}createBeatDot(e,t){let i=this.renderer;t.addGlyph(new Mr(0,i.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==_.None;if(e.beat.voice.bar.staff.isPercussion){const i=Me.getArticulation(e);if(i)return new en(0,0,i,e.beat.duration,t);Fe.warning("Rendering","No articulation found for percussion instrument "+e.percussionArticulation)}return e.isDead?new Ir(0,0,t):e.beat.graceType===_.BendGrace?new Fs(0,0,S.Quarter,!0):e.harmonicType===B.Natural?new Dr(0,0,e.beat.duration,t):new Fs(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===_.BendGrace&&!e.hasBend)return;let t=this.renderer,i=this.createNoteHeadGlyph(e),s=t.getNoteLine(e);if(i.y=t.getScoreY(s),this.noteHeads.addNoteGlyph(i,e,s),e.harmonicType!==B.None&&e.harmonicType!==B.Natural){let a=e.displayValue+e.harmonicPitch;i=new Dr(0,0,e.beat.duration,this.container.beat.graceType!==_.None),s=t.accidentalHelper.getNoteLineForValue(a,!1),i.y=t.getScoreY(s),this.noteHeads.addNoteGlyph(i,e,s)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new tn(0,0)),e.accentuated!==c.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new Lr(0,0,c.Normal)),e.accentuated!==c.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new Lr(0,0,c.Heavy)),e.isPercussion){const t=Me.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==F.Middle){const e=t.techniqueSymbolPlacement===F.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case E.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new sn(0,0));break;case E.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new tn(0,0));break;case E.StringsUpBow:e.set("StringsUpBow",new Ya(0,0,P.Up));break;case E.StringsDownBow:e.set("StringsDownBow",new Ya(0,0,P.Down));break;case E.GuitarGolpe:e.set("GuitarGolpe",new an(0,0))}}}}}class nn extends Ps{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,i){let s=this.renderer,a=s.lineOffset,r=t+this.y+(s.getNoteY(this._beat.maxNote,ae.Bottom)-a),n=t+this.y+s.getNoteY(this._beat.minNote,ae.Top)+a,o=e+this.x+this.width/2,h=8*this.scale;if(this._beat.brushType!==y.None){let t=new ja(0,0,N.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=-t.height/2;if(this._beat.brushType===y.ArpeggioUp){let a=r+h,l=n-h;t.width=Math.abs(l-a),i.beginRotate(e+this.x+5*this.scale,l,-90),t.paint(0,s,i),i.endRotate(),i.beginPath(),i.moveTo(o,n),i.lineTo(o+h/2,n-h),i.lineTo(o-h/2,n-h),i.closePath(),i.fill()}else if(this._beat.brushType===y.ArpeggioDown){let a=r+h,l=n;t.width=Math.abs(l-a),i.beginRotate(e+this.x+5*this.scale,a,90),t.paint(0,s,i),i.endRotate(),i.beginPath(),i.moveTo(o,r),i.lineTo(o+h/2,r+h),i.lineTo(o-h/2,r+h),i.closePath(),i.fill()}}}}class on extends fa{constructor(){super(),this._prebends=null,this.accidentals=null}get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new Yr,t=new Gr(!0);t.renderer=this.renderer,this._prebends=new qr(this.container.beat,!0),this._prebends.renderer=this.renderer;for(let i of this.container.beat.notes)if(i.isVisible){if(i.hasBend)switch(i.bendType){case m.PrebendBend:case m.Prebend:case m.PrebendRelease:this._prebends.addGlyph(i.displayValue-(i.bendPoints[0].value/2|0),!1)}else if(i.beat.hasWhammyBar)switch(i.beat.whammyBarType){case L.PrediveDive:case L.Predive:this._prebends.addGlyph(i.displayValue-(i.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(i,e),t.addParenthesis(i)}this._prebends.isEmpty||(this.addGlyph(this._prebends),this.addGlyph(new Zr(0,0,4*(this.container.beat.graceType!==_.None?Fs.GraceScale:1)*this.scale))),this.container.beat.brushType!==y.None&&(this.addGlyph(new nn(this.container.beat)),this.addGlyph(new Zr(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new Zr(0,0,4*(this.container.beat.graceType!==_.None?Fs.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new Zr(0,0,2*(this.container.beat.graceType!==_.None?Fs.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new Zr(0,0,2*(this.container.beat.graceType!==_.None?Fs.GraceScale:1)*this.scale)))}super.doLayout()}createAccidentalGlyph(e,t){let i=this.renderer,s=i.accidentalHelper.applyAccidental(e),a=i.getNoteLine(e),r=this.container.beat.graceType!==_.None;if(s!==se.None){let e=new vr(0,i.getScoreY(a),s,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==B.None&&e.harmonicType!==B.Natural){let n=e.displayValue+e.harmonicPitch;s=i.accidentalHelper.applyAccidentalForValue(e.beat,n,r,!1),a=i.accidentalHelper.getNoteLineForValue(n,!1);let o=new vr(0,i.getScoreY(a),s,r);o.renderer=this.renderer,t.addGlyph(o)}}}class hn extends Cs{constructor(e,t,i,s){super(e,t,s,hn.getSymbol(i)),this._digit=0,this._scale=0,this._digit=i,this._scale=s}doLayout(){this.width=this.getDigitWidth(this._digit)*this.scale*this._scale}getDigitWidth(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return 14;case 1:return 10;default:return 0}}static getSymbol(e){switch(e){case 0:return E.TimeSig0;case 1:return E.TimeSig1;case 2:return E.TimeSig2;case 3:return E.TimeSig3;case 4:return E.TimeSig4;case 5:return E.TimeSig5;case 6:return E.TimeSig6;case 7:return E.TimeSig7;case 8:return E.TimeSig8;case 9:return E.TimeSig9;default:return E.None}}}class ln extends $s{constructor(e,t,i,s=1){super(e,t),this._number=0,this._scale=0,this._number=i,this._scale=s}doLayout(){let e=this._number;for(;e>0;){let t=new hn(0,0,e%10,this._scale);this.addGlyph(t),e=e/10|0}if(this.glyphs){this.glyphs.reverse();let e=0;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.x=e,i.y=0,i.renderer=this.renderer,i.doLayout(),e+=i.width}this.width=e}}}ln.numberHeight=18;class cn extends $s{constructor(e,t,i,s,a){super(e,t),this._numerator=0,this._denominator=0,this._numerator=i,this._denominator=s,this._isCommon=a}doLayout(){if(this._isCommon&&2===this._numerator&&2===this._denominator){let e=new Cs(0,0,this.commonScale,E.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Cs(0,0,this.commonScale,E.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=ln.numberHeight*this.scale;let t=new ln(0,-e/2,this._numerator,this.numberScale),i=new ln(0,e/2,this._denominator,this.numberScale);this.addGlyph(t),this.addGlyph(i),super.doLayout();for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=(this.width-t.width)/2}}}}class dn extends cn{get commonScale(){return 1}get numberScale(){return 1}}class un extends Jr{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),!e.isTieOrigin)switch(e.bendType){case m.Bend:case m.PrebendRelease:case m.PrebendBend:{let t=this._endNoteGlyph;t||(t=this._endNoteGlyph=new qr(e.beat,!1),t.renderer=this.renderer,this.BendNoteHeads.push(t));let i=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0)}break;case m.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=this._endNoteGlyph=new qr(e.beat,!1),t.renderer=this.renderer,this.BendNoteHeads.push(t));let i=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0)}break;case m.BendRelease:{let t=this._middleNoteGlyph;t||(t=this._middleNoteGlyph=new qr(e.beat,!1),t.renderer=this.renderer,this.BendNoteHeads.push(t));let i=e.bendPoints[1];t.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),i.value%2!=0);let s=this._endNoteGlyph;s||(s=this._endNoteGlyph=new qr(e.beat,!1),s.renderer=this.renderer,this.BendNoteHeads.push(s));let a=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,a),a.value%2!=0)}}}paint(e,t,i){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+s.x+s.getBeatX(this._beat,ie.MiddleNotes),r=e+s.x;this._beat.isLastOfVoice?r+=s.postBeatGlyphsStart:r+=s.getBeatX(this._beat.nextBeat,ie.PreNotes),r-=8*this.scale;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+s.y,this._middleNoteGlyph.paint(0,0,i)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+s.y,this._endNoteGlyph.paint(0,0,i)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));let o=this._beat.graceType===_.BendGrace?this._beat.nextBeat:this._beat,h=1===this._notes.length?this.getTieDirection(o,s):U.Up;for(let o=0;o<this._notes.length;o++){let l=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(h=U.Down);let c=t+s.y+s.getNoteY(l,ae.Top),d=Fs.NoteHeadHeight*this.scale*Fs.GraceScale*.5;h===U.Down&&(c+=Fs.NoteHeadHeight*this.scale);let u=l.bendStyle===f.Gradual?"grad.":"";if(l.isTieOrigin){let r=l.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===s.staff){let s=e+n.x+n.getBeatX(r.beat,ie.MiddleNotes),o=t+n.y+n.getNoteY(r,ae.Top);h===U.Down&&(o+=Fs.NoteHeadHeight*this.scale),l.bendType===m.Hold||l.bendType===m.Prebend?Ar.paintTie(i,this.scale,a,c,s,o,h===U.Down,22,4):this.drawBendSlur(i,a,c,s,o,h===U.Down,this.scale,u)}else{let r=e+s.x+s.width,n=l.tieDestination.realValue;s.accidentalHelper.applyAccidentalForValue(l.beat,n,!1,!0);let o=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(n,!1));l.bendType===m.Hold||l.bendType===m.Prebend?Ar.paintTie(i,this.scale,a,c,r,o,h===U.Down,22,4):this.drawBendSlur(i,a,c,r,o,h===U.Down,this.scale,u)}switch(l.bendType){case m.Prebend:case m.PrebendBend:case m.PrebendRelease:let r=e+s.x+s.getBeatX(l.beat,ie.PreNotes);r+=s.getPreNotesGlyphForBeat(l.beat).prebendNoteHeadOffset;let n=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(l.displayValue-(l.bendPoints[0].value/2|0),!1))+d;this.drawBendSlur(i,r,n,a,c,h===U.Down,this.scale)}}else{h===U.Up&&(d=-d);let o=0,p=0;switch(l.bendType){case m.Bend:o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),p=this._endNoteGlyph.getNoteValueY(o)+d,this.drawBendSlur(i,a,c,r,p,h===U.Down,this.scale,u);break;case m.BendRelease:let g=this.getBendNoteValue(l,l.bendPoints[1]),f=this._middleNoteGlyph.getNoteValueY(g)+d;this.drawBendSlur(i,a,c,n,f,h===U.Down,this.scale,u),o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),p=this._endNoteGlyph.getNoteValueY(o)+d,this.drawBendSlur(i,n,f,r,p,h===U.Down,this.scale,u);break;case m.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),p=this.BendNoteHeads[0].getNoteValueY(o)+d,this.drawBendSlur(i,a,c,r,p,h===U.Down,this.scale,u));break;case m.Prebend:case m.PrebendBend:case m.PrebendRelease:let y=e+s.x+s.getBeatX(l.beat,ie.PreNotes);y+=s.getPreNotesGlyphForBeat(l.beat).prebendNoteHeadOffset;let b=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(l.displayValue-(l.bendPoints[0].value/2|0),!1))+d;this.drawBendSlur(i,y,b,a,c,h===U.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),p=this.BendNoteHeads[0].getNoteValueY(o)+d,this.drawBendSlur(i,a,c,r,p,h===U.Down,this.scale,u))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class pn extends Ar{constructor(e,t,i=!1){super(e,t,i)}doLayout(){super.doLayout()}getBeamDirection(e,t){if(e.isRest)return U.Up;switch(t.getBeatDirection(e)){case U.Up:return U.Down;default:return U.Up}}getStartY(){if(this.startBeat.isRest)return this.startNoteRenderer.getScoreY(9);switch(this.tieDirection){case U.Up:return this.startNoteRenderer.getNoteY(this.startBeat.maxNote,ae.Top);default:return this.startNoteRenderer.getNoteY(this.startBeat.minNote,ae.Bottom)}}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)switch(this.tieDirection){case U.Up:return e.getScoreY(9);default:return e.getScoreY(0)}const t=this.startNoteRenderer.getBeatDirection(this.startBeat),i=e.getBeatDirection(this.endBeat);if(t!==i&&this.startBeat.graceType===_.None)if(i===this.tieDirection)switch(this.tieDirection){case U.Up:return e.getNoteY(this.endBeat.maxNote,ae.TopWithStem);default:return e.getNoteY(this.endBeat.minNote,ae.BottomWithStem)}else switch(this.tieDirection){case U.Up:return e.getNoteY(this.endBeat.maxNote,ae.BottomWithStem);default:return e.getNoteY(this.endBeat.minNote,ae.TopWithStem)}switch(this.tieDirection){case U.Up:return e.getNoteY(this.endBeat.maxNote,ae.Top);default:return e.getNoteY(this.endBeat.minNote,ae.Bottom)}}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,ie.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>S.Whole&&e===this.tieDirection?ie.Stem:ie.MiddleNotes)}}class gn extends Ps{constructor(e,t,i,s){super(0,0),this._outType=t,this._inType=e,this._startNote=i,this._parent=s}doLayout(){this.width=0}paint(e,t,i){this.paintSlideIn(e,t,i),this.drawSlideOut(e,t,i)}paintSlideIn(e,t,i){let s=this.renderer,a=12*this.scale,r=e+s.x+s.getNoteX(this._startNote,re.Left)-2*this.scale,n=t+s.y+s.getNoteY(this._startNote,ae.Center),o=r-a,h=t+s.y;switch(this._inType){case k.IntoFromBelow:h+=s.getNoteY(this._startNote,ae.Bottom);break;case k.IntoFromAbove:h+=s.getNoteY(this._startNote,ae.Top);break;default:return}let l=this.getAccidentalsWidth(s,this._startNote.beat);o-=l,r-=l,this.paintSlideLine(i,!1,o,r,h,n)}getAccidentalsWidth(e,t){let i=e.getPreNotesGlyphForBeat(t);return i&&i.accidentals?i.accidentals.width:0}drawSlideOut(e,t,i){let s=this.renderer,a=12*this.scale,r=3*this.scale,n=1*this.scale,o=2*this.scale,h=0,l=0,c=0,d=0,u=!1;switch(this._outType){case v.Shift:case v.Legato:if(h=e+s.x+s.getBeatX(this._startNote.beat,ie.PostNotes)+r,l=t+s.y+s.getNoteY(this._startNote,ae.Center),this._startNote.slideTarget){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);i&&i.staff===s.staff?(c=e+i.x+i.getBeatX(this._startNote.slideTarget.beat,ie.PreNotes)-n,d=t+i.y+i.getNoteY(this._startNote.slideTarget,ae.Center)):(c=e+s.x+this._parent.x,d=l),this._startNote.slideTarget.realValue>this._startNote.realValue?(l+=o,d-=o):(l-=o,d+=o)}else c=e+s.x+this._parent.x,d=l;break;case v.OutUp:h=e+s.x+s.getNoteX(this._startNote,re.Right),l=t+s.y+s.getNoteY(this._startNote,ae.Center),c=h+a,d=t+s.y+s.getNoteY(this._startNote,ae.Top);break;case v.OutDown:h=e+s.x+s.getNoteX(this._startNote,re.Right),l=t+s.y+s.getNoteY(this._startNote,ae.Center),c=h+a,d=t+s.y+s.getNoteY(this._startNote,ae.Bottom);break;case v.PickSlideUp:h=e+s.x+s.getNoteX(this._startNote,re.Right)+r,l=t+s.y+s.getNoteY(this._startNote,ae.Center),d=t+s.y+s.getNoteY(this._startNote,ae.Top),c=e+s.x+s.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(c=e+s.x+s.getBeatX(this._startNote.beat.nextBeat,ie.PreNotes)),u=!0;break;case v.PickSlideDown:h=e+s.x+s.getNoteX(this._startNote,re.Right)+r,l=t+s.y+s.getNoteY(this._startNote,ae.Center),d=t+s.y+s.getNoteY(this._startNote,ae.Bottom),c=e+s.x+s.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(c=e+s.x+s.getBeatX(this._startNote.beat.nextBeat,ie.PreNotes)),u=!0;break;default:return}this.paintSlideLine(i,u,h,c,l,d)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new ja(0,0,N.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=s-i,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;let l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(i,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(i,a),e.lineTo(s,r),e.stroke()}}class fn extends pn{constructor(e,t,i=!1){super(e.beat,t.beat,i),this._startNote=e,this._endNote=t}getTieHeight(e,t,i,s){return Math.log2(i-e+1)*this.renderer.settings.notation.slurHeight}getStartY(){if(this.isStartCentered())switch(this.tieDirection){case U.Up:return this.startNoteRenderer.getNoteY(this._startNote,ae.Top);default:return this.startNoteRenderer.getNoteY(this._startNote,ae.Bottom)}return this.startNoteRenderer.getNoteY(this._startNote,ae.Center)}getEndY(){if(!this.isEndCentered())return this.endNoteRenderer.getNoteY(this._endNote,ae.Center);if(this.isEndOnStem())switch(this.tieDirection){case U.Up:return this.endNoteRenderer.getNoteY(this._endNote,ae.TopWithStem);default:return this.endNoteRenderer.getNoteY(this._endNote,ae.BottomWithStem)}else switch(this.tieDirection){case U.Up:return this.endNoteRenderer.getNoteY(this._endNote,ae.Top);default:return this.endNoteRenderer.getNoteY(this._endNote,ae.Bottom)}}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===U.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===U.Down}isEndCentered(){return this._startNote.beat.graceType===_.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===U.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===U.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===_.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,ie.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,re.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,ie.Stem):this.endNoteRenderer.getNoteX(this._endNote,re.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,ie.PreNotes)}}class mn extends Ar{constructor(e,t,i=!1){super(e?e.beat:null,t?t.beat:null,i),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){switch(t.getBeatDirection(e)){case U.Up:return U.Down;default:return U.Up}}getStartY(){if(this.startBeat.isRest)return this.startNoteRenderer.getScoreY(9);switch(this.tieDirection){case U.Up:return this.startNoteRenderer.getNoteY(this.startNote,ae.Top);default:return this.startNoteRenderer.getNoteY(this.startNote,ae.Bottom)}}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)switch(this.tieDirection){case U.Up:return e.getScoreY(9);default:return e.getScoreY(0)}switch(this.tieDirection){case U.Up:return e.getNoteY(this.endNote,ae.Top);default:return e.getNoteY(this.endNote,ae.Bottom)}}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,ie.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,ie.PreNotes)}}class yn extends Ms{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){if(this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.ties.push(new pn(this.beat,e,!1))}}else if(this.beat.isLegatoDestination&&!this.beat.isLegatoOrigin){let e=this.beat.previousBeat;for(;e.previousBeat&&e.previousBeat.isLegatoOrigin;)e=e.previousBeat;this.ties.push(new pn(e,this.beat,!0))}this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==_.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new mn(e,e.tieDestination,!1);this.ties.push(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new mn(e.tieOrigin,e,!0);this.ties.push(t)}if(e.slideInType!==k.None||e.slideOutType!==v.None){let t=new gn(e.slideInType,e.slideOutType,e,this);this.ties.push(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new fn(e,e.slurDestination,!1);this.ties.push(t)}if(e.isSlurDestination){let t=new fn(e.slurOrigin,e,!0);this.ties.push(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination&&(this._effectSlur=new fn(e,e.effectSlurDestination,!1),this.ties.push(this._effectSlur)),!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){let t=this.onNotes.beamingHelper.direction,i=t===U.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,s=t===U.Up?e.beat.minNote:e.beat.maxNote;this._effectEndSlur=new fn(i,s,!0),this.ties.push(this._effectEndSlur)}e.hasBend&&(this._bend||(this._bend=new un(e.beat),this._bend.renderer=this.renderer,this.ties.push(this._bend)),this._bend.addBends(e))}}}class bn extends ca{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new ia(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(ca.LineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=e.tablatureFont.size/2+.2*e.tablatureFont.size;this.topPadding=t*this.scale,this.bottomPadding=t*this.scale,this.height=4*this.lineOffset+this.topPadding+this.bottomPadding,this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=4*this.lineOffset,t=(this.bar.staff.standardNotationLineCount-1)*this.lineOffset;this._firstLineY=(e-t)/2}doLayout(){if(this.updateFirstLineY(),super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){let e=this.getScoreY(-2),t=this.getScoreY(6),i=this.simpleWhammyOverflow;this.registerOverflowTop(i);let s=this.getScoreY(this.accidentalHelper.maxLine),a=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);a.direction===U.Up&&(s-=this.getStemSize(a),s-=a.fingeringCount*this.resources.graceFont.size,a.hasTuplet&&(s-=2*this.resources.effectFont.size)),a.hasTuplet&&(s-=1.5*this.resources.effectFont.size),s<e&&this.registerOverflowTop(Math.abs(s)+i);let r=this.getScoreY(this.accidentalHelper.minLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);n.direction===U.Down&&(r+=this.getStemSize(n),r+=n.fingeringCount*this.resources.graceFont.size),r>t&&this.registerOverflowBottom(Math.abs(r)-t)}}paint(e,t,i){super.paint(e,t,i),this.paintBeams(e,t,i),this.paintTuplets(e,t,i)}paintTuplets(e,t,i){for(let s of this.bar.voices)if(this.hasVoiceContainer(s)){let a=this.getVoiceContainer(s);for(let s of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,i,s)}}paintBeams(e,t,i){for(let s=0,a=this.helpers.beamHelpers.length;s<a;s++){let a=this.helpers.beamHelpers[s];for(let s=0,r=a.length;s<r;s++){let r=a[s];this.paintBeamHelper(e+this.beatGlyphsStart,t,i,r)}}}paintBeamHelper(e,t,i,s){i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isRestBeamHelper||(1===s.beats.length?this.paintFlag(e,t,i,s):this.paintBar(e,t,i,s))}paintTupletHelper(e,t,i,s){let a,r=this.resources,n=i.textAlign,o=i.textBaseline;i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.textAlign=C.Center,i.textBaseline=F.Middle;let h=s.beats[0].tupletNumerator,l=s.beats[0].tupletDenominator;a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l;let c=10*this.scale,d=5*this.scale;if(1!==s.beats.length&&s.isFull){let n=s.beats[0],o=s.beats[s.beats.length-1],h=null,l=null;for(let e=0;e<s.beats.length;e++)if(!s.beats[e].isRest){h=s.beats[e];break}for(let e=s.beats.length-1;e>=0;e--)if(!s.beats[e].isRest){l=s.beats[e];break}let u=!1;h||(h=n,u=!0),l||(l=o);let p=this.helpers.beamHelperLookup[s.voice.index].get(n.index),g=this.helpers.beamHelperLookup[s.voice.index].get(o.index),f=p.getBeatLineX(n),m=g.getBeatLineX(o),y=this.helpers.beamHelperLookup[s.voice.index].get(h.index),b=this.helpers.beamHelperLookup[s.voice.index].get(l.index),S=p.direction,w=this.calculateBeamYWithDirection(y,f,S),_=this.calculateBeamYWithDirection(b,m,S);u&&(w=Math.max(w,_),_=w),i.font=r.effectFont;let B=i.measureText(a),T=3*this.scale,k=(f+m)/2,v=k-B/2-T,N=k+B/2+T,x=(_-w)/(m-f),P=w-x*f,E=x*v+P,C=x*k+P,F=x*N+P;S===U.Down&&(c*=-1,d*=-1),i.beginPath(),i.moveTo(e+this.x+f,t+this.y+w-c|0),i.lineTo(e+this.x+f,t+this.y+w-c-d|0),i.lineTo(e+this.x+v,t+this.y+E-c-d|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+N,t+this.y+F-c-d|0),i.lineTo(e+this.x+m,t+this.y+_-c-d|0),i.lineTo(e+this.x+m,t+this.y+_-c|0),i.stroke(),i.fillText(a,e+this.x+k,t+this.y+C-c-d)}else for(let n=0,o=s.beats.length;n<o;n++){let o=s.beats[n],h=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(!h)continue;let l=h.direction,u=h.getBeatLineX(o),p=this.calculateBeamYWithDirection(h,u,l);l===U.Down&&(c*=-1,d*=-1),i.font=r.effectFont,i.fillText(a,e+this.x+u,t+this.y+p-c-d)}i.textAlign=n,i.textBaseline=o}getStemSize(e){let t=1===e.beats.length?this.getFlagStemSize(e.shortestDuration):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(t*=Fs.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case S.QuadrupleWhole:case S.Half:case S.Quarter:case S.Eighth:case S.Sixteenth:t=6;break;case S.ThirtySecond:t=8;break;case S.SixtyFourth:case S.OneHundredTwentyEighth:t=9;break;case S.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case S.QuadrupleWhole:case S.Half:case S.Quarter:case S.Eighth:case S.Sixteenth:case S.ThirtySecond:case S.SixtyFourth:case S.OneHundredTwentyEighth:case S.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let i=super.getNoteY(e,t);if(isNaN(i)){const t=ia.computeLineWithoutAccidentals(this.bar,e);i=this.getScoreY(t)}return i}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,e.direction)}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let e=this.getScoreY(-2),t=this.getScoreY(6),i=this.helpers.collisionHelper.getBeatMinMaxY();i[0]<e&&this.registerOverflowTop(Math.abs(i[0])),i[1]>t&&this.registerOverflowBottom(Math.abs(i[1])-t)}return e}calculateBeamYWithDirection(e,t,i){let s=this.getStemSize(e);if(!e.drawingInfos.has(i)){let t=new aa;e.drawingInfos.set(i,t);const a=e.beats[0],r=e.beats[e.beats.length-1];let n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?i===U.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===U.Up?this.getScoreY(this.accidentalHelper.getMinLine(a))-s:this.getScoreY(this.accidentalHelper.getMaxLine(a))+s,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?i===U.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===U.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-s:this.getScoreY(this.accidentalHelper.getMaxLine(r))+s;let o=10*this.scale;if(i===U.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),i===U.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),i===U.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),i===U.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(i===U.Up){let i=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-s;const a=t.calcY(e.getBeatLineX(e.beatOfHighestNote))-i;a>0&&(t.startY-=a,t.endY-=a)}else{const i=this.getScoreY(this.accidentalHelper.getMaxLine(e.beatOfLowestNote))+s-t.calcY(e.getBeatLineX(e.beatOfLowestNote));i>0&&(t.startY+=i,t.endY+=i)}if(null!==e.minRestLine||null!==e.maxRestLine){const s=fe.getIndex(e.shortestDuration)-2;let a=e.isGrace?Fs.GraceScale:1,r=s*(ca.BeamSpacing+ca.BeamThickness)*this.scale*a;if(r+=ca.BeamSpacing,i===U.Up&&null!==e.minRestLine){let i=this.getScoreY(e.minRestLine)-r;const s=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-i;s>0&&(t.startY-=s,t.endY-=s)}else if(i===U.Down&&null!==e.maxRestLine){const i=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));i>0&&(t.startY+=i,t.endY+=i)}}}}return e.drawingInfos.get(i).calcY(t)}paintBar(e,t,i,s){for(let a=0,r=s.beats.length;a<r;a++){let r=s.beats[a],n=r.graceType!==_.None?Fs.GraceScale:1,o=s.getBeatLineX(r),h=s.direction,l=t+this.y;l+=h===U.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let c=t+this.y;c+=this.calculateBeamY(s,o),i.lineWidth=bn.StemWidth*this.scale,i.beginPath(),i.moveTo(e+this.x+o,l),i.lineTo(e+this.x+o,c),i.stroke(),i.lineWidth=this.scale;let d=c;h===U.Down?d+=2*i.font.size:0!==a&&(d-=1.5*i.font.size),this.paintFingering(i,r,e+this.x+o,h,d);let u=6*this.scale*n,p=(ca.BeamSpacing+ca.BeamThickness)*this.scale*n,g=ca.BeamThickness*this.scale*n,f=fe.getIndex(r.duration)-2,m=t+this.y;h===U.Down&&(p=-p,g=-g);for(let t=0;t<f;t++){let n=0,h=0,l=0,c=0,d=m+t*p;if(a<s.beats.length-1){if(ra.isFullBarJoin(r,s.beats[a+1],t))n=o,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&ra.isFullBarJoin(s.beats[a-1],r,t))continue;n=o,h=n+u}l=d+this.calculateBeamY(s,n),c=d+this.calculateBeamY(s,h),bn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,c,g)}else a>0&&!ra.isFullBarJoin(r,s.beats[a-1],t)&&(n=o-u,h=o,l=d+this.calculateBeamY(s,n),c=d+this.calculateBeamY(s,h),bn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,c,g))}}}static paintSingleBar(e,t,i,s,a,r){e.beginPath(),e.moveTo(t,i),e.lineTo(s,a),e.lineTo(s,a+r),e.lineTo(t,i+r),e.closePath(),e.fill()}paintFlag(t,i,s,a){let r=a.beats[0];if(r.graceType===_.BendGrace||r.graceType!==_.None&&this.settings.notation.notationMode===e.NotationMode.SongBook)return;let n=r.graceType!==_.None,o=n?Fs.GraceScale:1,h=this.getFlagStemSize(a.shortestDuration),l=a.getBeatLineX(r),c=a.direction,d=this.getScoreY(this.accidentalHelper.getMinLine(r)),u=this.getScoreY(this.accidentalHelper.getMaxLine(r)),p=0,g=0;if(c===U.Down?(u+=h*o,p=u,g=i+this.y+u):(d-=h*o,p=d,g=i+this.y+d),this.paintFingering(s,r,t+this.x+l,c,g),a.hasLine){if(s.lineWidth=ca.StemWidth*this.scale,s.beginPath(),s.moveTo(t+this.x+l,i+this.y+d),s.lineTo(t+this.x+l,i+this.y+u),s.stroke(),s.lineWidth=this.scale,r.graceType===_.BeforeBeat){let e=15*this.scale,a=12*this.scale;s.beginPath(),c===U.Down?(s.moveTo(t+this.x+l-a/2,i+this.y+u-e),s.lineTo(t+this.x+l+a/2,i+this.y+u)):(s.moveTo(t+this.x+l-a/2,i+this.y+d+e),s.lineTo(t+this.x+l+a/2,i+this.y+d)),s.stroke()}if(a.hasFlag){let e=new Ls(l-this.scale/2,p,r.duration,c,n);e.renderer=this,e.doLayout(),e.paint(t+this.x,i+this.y,s)}}}paintFingering(t,s,a,r,n){let o=this.settings;if(o.notation.fingeringMode!==e.FingeringMode.ScoreDefault&&o.notation.fingeringMode!==e.FingeringMode.ScoreForcePiano)return;r===U.Up?a-=10*this.scale:a+=3*this.scale;let h=s.notes.slice(0);h.sort(((e,t)=>e.realValue-t.realValue));for(let e=0;e<h.length;e++){let r=h[e],l=null;r.leftHandFinger!==i.Unknown?l=fe.fingerToString(o,s,r.leftHandFinger,!0):r.rightHandFinger!==i.Unknown&&(l=fe.fingerToString(o,s,r.rightHandFinger,!1)),l&&(t.fillText(l,a,n),n-=0|t.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Fr(0,0,1.5,3)),this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case u.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case u.F4:e=2;break;case u.C3:e=4;break;case u.C4:e=2;break;case u.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new Pr(0,this.getScoreY(e)+.5*ca.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&0!==this.bar.masterBar.keySignature||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Nr(0,this.getScoreHeight(-.5),this.bar.index+1))}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(t)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Er(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Cr(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new xr(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Zr(0,0,2*this.scale)),this._startSpacing=!0)}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,i=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case u.Neutral:e=0;break;case u.G2:e=1;break;case u.F4:e=2;break;case u.C3:e=-1;break;case u.C4:e=1}let s=new Map,a=[];if(fe.keySignatureIsSharp(t))for(let i=0;i<Math.abs(t);i++){let t=bn.SharpKsSteps[i]+e;a.push(new vr(0,this.getScoreY(t),se.Sharp,!1)),s.set(t,!0)}else for(let i=0;i<Math.abs(t);i++){let t=bn.FlatKsSteps[i]+e;a.push(new vr(0,this.getScoreY(t),se.Flat,!1)),s.set(t,!0)}let r=Math.abs(i),n=fe.keySignatureIsSharp(i)?bn.SharpKsSteps:bn.FlatKsSteps;for(let t=0;t<r;t++){let i=n[t]+e;s.has(i)||this.addPreBeatGlyph(new vr(0,this.getScoreY(n[t]+e),se.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Zr(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new dn(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new yn(i,this.getVoiceContainer(e));s.preNotes=new on,s.onNotes=new rn,this.addBeatGlyph(s)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}getScoreY(e){return this._firstLineY+this.lineOffset+this.getScoreHeight(e)}getScoreHeight(e){return this.lineOffset/2*e}paintBackground(e,t,i){super.paintBackground(e,t,i);let s=this.resources;i.color=s.staffLineColor;for(let s=0;s<this.bar.staff.standardNotationLineCount;s++){const a=t+this.y+this.getScoreY(2*s);i.fillRect(e+this.x,0|a,this.width,this.scale*ca.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,ae.Center),i=this.getNoteY(e.lowestNoteInHelper,ae.Center),s=this.getStemSize(e);e.hasTuplet&&(s+=2*this.resources.effectFont.size),e.direction==U.Up?t-=s:i+=s;for(const s of e.beats)this.helpers.collisionHelper.reserveBeatSlot(s,t,i)}}}bn.StaffId="score",bn.SharpKsSteps=[-1,2,-2,1,4,0,3],bn.FlatKsSteps=[3,0,4,1,5,2,6];class Sn extends Ks{get staffId(){return bn.StaffId}create(e,t){return new bn(e,t)}constructor(){super()}}class wn extends Ps{constructor(e,t,i,s){super(0,0),this._inType=e,this._outType=t,this._startNote=i,this._parent=s}doLayout(){this.width=0}paint(e,t,i){this.paintSlideIn(e,t,i),this.paintSlideOut(e,t,i)}paintSlideIn(e,t,i){let s=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0;switch(this._inType){case k.IntoFromBelow:h=e+s.x+s.getNoteX(this._startNote,re.Left),l=t+s.y+s.getNoteY(this._startNote,ae.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,ae.Center)+r;break;case k.IntoFromAbove:h=e+s.x+s.getNoteX(this._startNote,re.Left),l=t+s.y+s.getNoteY(this._startNote,ae.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,ae.Center)-r;break;default:return}this.paintSlideLine(i,!1,n,h,o,l)}paintSlideOut(e,t,i){let s=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0,c=!1;const d=2*this.scale;switch(this._outType){case v.Shift:case v.Legato:if(n=e+s.x+s.getBeatX(this._startNote.beat,ie.PostNotes),o=t+s.y+s.getNoteY(this._startNote,ae.Center),this._startNote.slideTarget){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);i&&i.staff===s.staff?(h=e+i.x+i.getBeatX(this._startNote.slideTarget.beat,ie.OnNotes)-d,l=t+i.y+i.getNoteY(this._startNote.slideTarget,ae.Center)):(h=e+s.x+this._parent.x,l=o),this._startNote.slideTarget.fret>this._startNote.fret?(o+=r,l-=r):(o-=r,l+=r)}else h=e+s.x+this._parent.x,l=o;break;case v.OutUp:n=e+s.x+s.getNoteX(this._startNote,re.Right),o=t+s.y+s.getNoteY(this._startNote,ae.Center),h=n+a-d,l=t+s.y+s.getNoteY(this._startNote,ae.Center)-r;break;case v.OutDown:n=e+s.x+s.getNoteX(this._startNote,re.Right),o=t+s.y+s.getNoteY(this._startNote,ae.Center),h=n+a-d,l=t+s.y+s.getNoteY(this._startNote,ae.Center)+r;break;case v.PickSlideDown:n=e+s.x+s.getNoteX(this._startNote,re.Right),o=t+s.y+s.getNoteY(this._startNote,ae.Center),h=e+s.x+s.getBeatX(this._startNote.beat,ie.EndBeat),l=o+3*r,c=!0;break;case v.PickSlideUp:n=e+s.x+s.getNoteX(this._startNote,re.Right),o=t+s.y+s.getNoteY(this._startNote,ae.Center),h=e+s.x+s.getBeatX(this._startNote.beat,ie.EndBeat),l=o-3*r,c=!0;break;default:return}this.paintSlideLine(i,c,n,h,o,l)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new ja(0,0,N.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=s-i,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;let l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(i,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(i,a),e.lineTo(s,r),e.stroke()}}class _n extends Ar{constructor(e,t,i=!1){super(e.beat,t.beat,i),this.startNote=e,this.endNote=t}getTieHeight(e,t,i,s){return this.startNote===this.endNote?15:super.getTieHeight(e,t,i,s)}getBeamDirection(e,t){return this.startNote===this.endNote?U.Up:_n.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?U.Up:U.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,ae.Center):this.tieDirection===U.Up?this.startNoteRenderer.getNoteY(this.startNote,ae.Top):this.startNoteRenderer.getNoteY(this.startNote,ae.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,re.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,re.Left):this.endNoteRenderer.getNoteX(this.endNote,re.Center)}}class Bn extends _n{constructor(e,t,i,s=!1){super(e,t,s),this._direction=_n.getBeamDirectionForNote(e),this._forSlide=i}getTieHeight(e,t,i,s){return Math.log(i-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,i,s){if(this._forSlide!==i)return!1;if(this.forEnd!==s)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;if(this._direction!==_n.getBeamDirectionForNote(e))return!1;switch(this._direction){case U.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 U.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,i){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,s),r="tab.slur."+this.startNote.beat.id+"."+this.endNote.beat.id+"."+a,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,i))}}class Tn extends Ms{constructor(e,t){super(e,t),this._bend=null,this._effectSlurs=[]}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;let t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){let t=new _n(e,e.tieDestination,!1);this.ties.push(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new _n(e.tieOrigin,e,!0);this.ties.push(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new _n(e,e,!1);this.ties.push(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(let i of this._effectSlurs)if(i.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){let t=new Bn(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.ties.push(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(let i of this._effectSlurs)if(i.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){let t=new Bn(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.ties.push(t)}}if(e.slideInType!==k.None||e.slideOutType!==v.None){let t=new wn(e.slideInType,e.slideOutType,e,this);this.ties.push(t)}e.hasBend&&(this._bend||(this._bend=new jr,this._bend.renderer=this.renderer,this.ties.push(this._bend)),this._bend.addBends(e))}}class kn extends Ps{constructor(e,t,i){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=i}doLayout(){let t=this._note,i=t.fret-t.beat.voice.bar.staff.transpositionPitch;if(t.harmonicType===B.Natural&&0!==t.harmonicValue&&(i=t.harmonicValue-t.beat.voice.bar.staff.transpositionPitch),t.isTieDestination)0===t.beat.index&&this.renderer.settings.notation.notationMode==e.NotationMode.GuitarPro||(t.bendType===m.Bend||t.bendType===m.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(n.TabNotesOnTiedBends)?this._noteString="("+(t.tieOrigin.fret-t.beat.voice.bar.staff.transpositionPitch)+")":this._noteString="";else if(this._noteString=t.isDead?"x":i.toString(),t.isGhost)this._noteString="("+this._noteString+")";else if(t.harmonicType===B.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(t.isTrill)this._trillNoteString="("+(t.trillFret-t.beat.voice.bar.staff.transpositionPitch)+")";else if(fe.isAlmostEqualTo(t.harmonicValue,0))this._trillNoteString="";else switch(t.harmonicType){case B.Artificial:case B.Pinch:case B.Tap:case B.Semi:case B.Feedback:let e=(i+t.harmonicValue).toString(),s=e.indexOf(String.fromCharCode(46));s>=0&&(e=e.substr(0,s+2)),this._trillNoteString="<"+e+">";break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.width=this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString)*this.scale,this.height=this.renderer.scoreRenderer.canvas.font.size,!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3*this.scale+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString),this.width+=this._trillNoteStringWidth)}}paint(e,t,i){if(this.isEmpty)return;let s=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-s)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,i.fillText(this._trillNoteString,a+this.noteStringWidth+3*this.scale,t+this.y),this.renderer.scoreRenderer.canvas.font=r,i.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,i){let s=new us;s.note=this._note,s.noteHeadBounds=new ht,s.noteHeadBounds.x=t+this.x,s.noteHeadBounds.y=i+this.y-this.height/2,s.noteHeadBounds.w=this.width,s.noteHeadBounds.h=this.height,this.renderer.scoreRenderer.boundsLookup.addNote(s)}}class vn extends Ps{constructor(e,t,i){super(e,t),this._notes=[],this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=i}buildBoundingsLookup(e,t,i){for(const s of this._notes)s.buildBoundingsLookup(e,t+this.x,i+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){let i=this.notesPerString.get(e.string),s=this.x+i.x;switch(t){case re.Left:break;case re.Center:s+=i.noteStringWidth/2;break;case re.Right:s+=i.width}return s}return 0}getNoteY(e,t){if(this.notesPerString.has(e.string)){const i=this.notesPerString.get(e.string);let s=this.y+i.y;switch(t){case ae.Top:case ae.TopWithStem:s-=i.height/2+2*this.scale;break;case ae.Center:break;case ae.Bottom:case ae.BottomWithStem:s+=i.height/2}return s}return 0}doLayout(){let e=0,t=0;for(let i=0,s=this._notes.length;i<s;i++){let s=this._notes[i];s.renderer=this.renderer,s.doLayout(),s.width>e&&(e=s.width),s.noteStringWidth>t&&(t=s.noteStringWidth)}this.noteStringWidth=t;let i=this.renderer.resources.tablatureFont.size,s=this.getNoteY(this.minStringNote,ae.Center)+i/2,a=7*this.scale;for(const e of this.beatEffects.values())e.y+=s,e.x+=this.width/2,e.renderer=this.renderer,s+=a,e.doLayout();this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,i){e+=this.x,t+=this.y;let s=this.renderer.resources,a=i.textBaseline;i.textBaseline=F.Middle,i.font=this._isGrace?s.graceFont:s.tablatureFont;let r=this._notes,n=this.width;for(let s of r)s.renderer=this.renderer,s.width=n,s.paint(e,t,i);i.textBaseline=a;for(const s of this.beatEffects.values())s.paint(e,t,i)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class Nn extends Cs{constructor(e,t,i,s){super(e,t,1,zr.getSymbol(s)),this._isVisibleRest=i,this._duration=s}doLayout(){this._isVisibleRest?this.width=zr.getSize(this._duration)*this.scale:this.width=10*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,i){this._isVisibleRest&&super.paint(e,t,i)}}class xn extends ma{constructor(){super(...arguments),this.noteNumbers=null,this.restGlyph=null}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,i){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,i+this.y)}doLayout(){let t=this.renderer;if(this.container.beat.isRest){let e=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),i=t.getTabY(e);if(this.restGlyph=new Nn(0,i,t.showRests,this.container.beat.duration),this.restGlyph.beat=this.container.beat,this.restGlyph.beamingHelper=this.beamingHelper,this.addGlyph(this.restGlyph),this.container.beat.dots>0&&t.showRests){this.addGlyph(new Zr(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new Mr(0,i,1.5*this.scale))}}else{let i=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==_.None;this.noteNumbers=new vn(0,0,i),this.noteNumbers.beat=this.container.beat,this.noteNumbers.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(this.noteNumbers),this.container.beat.hasWhammyBar){let e=new Kr(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case S.ThirtySecond:e=10;break;case S.Sixteenth:e=5;break;case S.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new Wr(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&t.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden){this.addGlyph(new Zr(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new Mr(0,t.lineOffset*t.bar.staff.tuning.length+t.settings.notation.rhythmHeight*t.scale,1.5*this.scale))}}if(!this.glyphs)return;let i=0;for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=i,t.renderer=this.renderer,t.doLayout(),i+=t.width}this.width=i,this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2}updateBeamingHelper(){this.container.beat.isRest?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.noteNumbers.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,i=new kn(0,0,e),s=e.beat.voice.bar.staff.tuning.length-e.string;i.y=t.getTabY(s),i.renderer=this.renderer,i.doLayout(),this.noteNumbers.addNoteGlyph(i,e);let a=i.y-i.height/2,r=a+i.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class Pn extends Ps{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,i){let s=this.renderer,a=t+this.x+s.getNoteY(this._beat.maxNote,ae.Top),r=t+this.y+s.getNoteY(this._beat.minNote,ae.Bottom),n=e+this.x+this.width/2|0,o=8*this.scale;if(this._beat.brushType!==y.None){if(this._beat.brushType===y.BrushUp||this._beat.brushType===y.BrushDown)i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke();else if(this._beat.brushType===y.ArpeggioUp){let t=new ja(0,0,N.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=a,n=r-o;t.width=Math.abs(n-s),i.beginRotate(e+this.x+4*this.scale,n,-90),t.paint(0,-t.height/2,i),i.endRotate()}else if(this._beat.brushType===y.ArpeggioDown){let t=new ja(0,0,N.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=a+o,n=r;t.width=Math.abs(n-s),i.beginRotate(e+this.x+4*this.scale,s,90),t.paint(0,-t.height/2,i),i.endRotate()}this._beat.brushType===y.BrushUp||this._beat.brushType===y.ArpeggioUp?(i.beginPath(),i.moveTo(n,r),i.lineTo(n+o/2,r-o),i.lineTo(n-o/2,r-o),i.closePath(),i.fill()):(i.beginPath(),i.moveTo(n,a),i.lineTo(n+o/2,a+o),i.lineTo(n-o/2,a+o),i.closePath(),i.fill())}}}class En extends fa{doLayout(){this.container.beat.brushType===y.None||this.container.beat.isRest||(this.addGlyph(new Pn(this.container.beat)),this.addGlyph(new Zr(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class Cn extends Ps{constructor(e,t){super(e,t)}doLayout(){this.width=28*this.scale}paint(e,t,i){let s=this.renderer.bar.staff.tuning.length,a=s<=4?E.FourStringTabClef:E.SixStringTabClef,r=s<=4?s/4.5:s/6.5;i.fillMusicFontSymbol(e+this.x+5*this.scale,t+this.y,r*this.scale,a,!1)}}class Fn extends cn{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Fs.GraceScale:1}}class Ln extends ca{constructor(e,t){super(e,t),this._firstLineY=0,this._tupletSize=0,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._startSpacing=!1}get lineOffset(){return(Ln.TabLineSpacing+1)*this.scale}updateSizes(){let t=this.resources,i=(t.tablatureFont.size/2+.2*t.tablatureFont.size)*this.scale;this.topPadding=i,this.bottomPadding=i,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*i,this.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden&&(this.height+=this.settings.notation.rhythmHeight*this.settings.display.scale,this.bottomPadding+=this.settings.notation.rhythmHeight*this.settings.display.scale),this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=this.resources;this._firstLineY=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale}doLayout(){if(this.updateFirstLineY(),super.doLayout(),this.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden){let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&(this._tupletSize=.8*this.resources.effectFont.size,this.registerOverflowBottom(this._tupletSize))}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Fr(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Cn(5*this.scale,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Nr(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Zr(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Zr(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new Fn(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new Tn(i,this.getVoiceContainer(e));s.preNotes=new En,s.onNotes=new xn,this.addBeatGlyph(s)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Er(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Cr(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new xr(0,0))}getTabY(e){return this._firstLineY+this.getTabHeight(e)}getTabHeight(e){return this.lineOffset*e}get middleYPosition(){return this.getTabY(this.bar.staff.tuning.length-1)}paintBackground(e,t,i){super.paintBackground(e,t,i);let s=this.resources;i.color=s.staffLineColor;let a=this.scale,r=[];for(let e=0,t=this.bar.staff.tuning.length;e<t;e++)r.push([]);for(let e of this.bar.voices)if(this.hasVoiceContainer(e)){let t=this.getVoiceContainer(e);for(let e of t.beatGlyphs){let i=e.onNotes,s=i.noteNumbers;if(s)for(const[n,o]of s.notesPerString)o.isEmpty||r[this.bar.staff.tuning.length-n].push(new Float32Array([t.x+e.x+i.x+s.x,s.width+a]))}}for(let e of r)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let s=0,a=this.bar.staff.tuning.length;s<a;s++){const a=this.getTabY(s);let n=0;for(let o of r[s])i.fillRect(e+this.x+n,t+this.y+a|0,o[0]-n,this.scale*ca.StaffLineThickness),n=o[0]+o[1];i.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*ca.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}paint(t,i,s){super.paint(t,i,s),this.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden&&(this.paintBeams(t,i,s),this.paintTuplets(t,i,s))}paintBeams(e,t,i){for(let s=0,a=this.helpers.beamHelpers.length;s<a;s++){let a=this.helpers.beamHelpers[s];for(let s=0,r=a.length;s<r;s++){let r=a[s];this.paintBeamHelper(e+this.beatGlyphsStart,t,i,r)}}}paintTuplets(e,t,i){for(let s of this.bar.voices)if(this.hasVoiceContainer(s)){let a=this.getVoiceContainer(s);for(let s of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,i,s)}}paintBeamHelper(t,i,s,a){s.color=0===a.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,a.isRestBeamHelper||(1===a.beats.length||this.settings.notation.rhythmMode===e.TabRhythmMode.ShowWithBeams?this.paintFooter(t,i,s,a):this.paintBar(t,i,s,a))}paintBar(e,t,i,s){for(let a=0,r=s.beats.length;a<r;a++){let r=s.beats[a];if(s.hasBeatLineX(r)){let n=s.getBeatLineX(r),o=t+this.y,h=t+this.y+this.height-this._tupletSize,l=this.getOnNotesGlyphForBeat(r);l.noteNumbers?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,ae.Bottom)+this.lineOffset/2:o+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(r,t+this.y,e+this.x+n,o,h,i);let c=6*this.scale,d=-6*this.scale,u=3*this.scale,p=fe.getIndex(r.duration)-2,g=h;for(let t=0;t<p;t++){let o=0,h=0,l=0,p=0,f=g+t*d;if(1===s.beats.length)o=n,h=n+c,l=f,p=f,Ln.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u);else if(a<s.beats.length-1){if(ra.isFullBarJoin(r,s.beats[a+1],t))o=n,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&ra.isFullBarJoin(s.beats[a-1],r,t))continue;o=n,h=o+c}l=f,p=f,Ln.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u)}else a>0&&!ra.isFullBarJoin(r,s.beats[a-1],t)&&(o=n-c,h=n,l=f,p=f,Ln.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u))}}}}paintTupletHelper(e,t,i,s){let a,r=this.resources,n=i.textAlign,o=i.textBaseline;i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.textAlign=C.Center,i.textBaseline=F.Middle;let h=s.beats[0].tupletNumerator,l=s.beats[0].tupletDenominator;if(a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l,1!==s.beats.length&&s.isFull){let n=s.beats[0],o=s.beats[s.beats.length-1],h=this.helpers.beamHelperLookup[s.voice.index].get(n.index),l=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(h&&l){let s=h.getBeatLineX(n),c=l.getBeatLineX(o);i.font=r.effectFont;let d=i.measureText(a),u=3*this.scale,p=(s+c)/2,g=p-d/2-u,f=p+d/2+u,m=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size,y=.25*-r.effectFont.size,b=-5*this.scale;i.beginPath(),i.moveTo(e+this.x+s,m-y|0),i.lineTo(e+this.x+s,m-y-b|0),i.lineTo(e+this.x+g,m-y-b|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+f,m-y-b|0),i.lineTo(e+this.x+c,m-y-b|0),i.lineTo(e+this.x+c,m-y|0),i.stroke(),i.fillText(a,e+this.x+p,m-y-b)}}else for(let n=0,o=s.beats.length;n<o;n++){let o=s.beats[n],h=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(!h)continue;let l=h.getBeatLineX(o),c=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size;i.font=r.effectFont,i.fillText(a,e+this.x+l,c)}i.textAlign=n,i.textBaseline=o}static paintSingleBar(e,t,i,s,a,r){e.beginPath(),e.moveTo(t,i),e.lineTo(s,a),e.lineTo(s,a-r),e.lineTo(t,i-r),e.closePath(),e.fill()}paintBeamingStem(e,t,i,s,a,r){r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>s;){r.moveTo(i,o);let e=s;if(!(n.length>0)){r.lineTo(i,s);break}{const s=n.pop();e=t+s.bottomY,r.lineTo(i,e),o=t+s.topY}}r.stroke()}paintFooter(e,t,i,s){for(let a of s.beats){if(a.graceType!==_.None||a.duration===S.Whole||a.duration===S.DoubleWhole||a.duration===S.QuadrupleWhole)return;let r=s.getBeatLineX(a),n=t+this.y,o=t+this.y+this.height-this._tupletSize,h=this.getOnNotesGlyphForBeat(a);if(h.noteNumbers?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,ae.Bottom):n+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(a,t+this.y,e+this.x+r,n,o,i),a.duration>S.Quarter){let t=new Ls(0,0,a.duration,U.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,i)}}}}Ln.StaffId="tab",Ln.TabLineSpacing=10;class Mn extends Ks{constructor(e,t,i){super(),this._showTimeSignature=e,this._showRests=t,this._showTiedNotes=i,this.hideOnPercussionTrack=!0}get staffId(){return Ln.StaffId}canCreate(e,t){return t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let i=new Ln(e,t);return i.showRests=this._showRests,i.showTimeSignature=this._showTimeSignature,i.showTiedNotes=this._showTiedNotes,i}}class In extends Es{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+In.Padding*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=C.Center,i.fillText("T",e+this.x,t+this.y+i.font.size/2),i.textAlign=a,i.strokeCircle(e+this.x,t+this.y+i.font.size/2+(In.Padding-1)*this.scale,i.font.size/1.6)}}In.Padding=4;class Dn extends Da{get notationElement(){return n.EffectTap}get sizingMode(){return ne.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new In}}class An{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"}(he||(he={}));class Rn extends An{constructor(){super(...arguments),this.align=C.Left,this.frame=he.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class On extends An{constructor(){super(...arguments),this.chord=new We}}class Gn extends An{}class Vn extends An{}class Hn extends An{constructor(){super(...arguments),this.number=0}}class Wn extends An{constructor(){super(...arguments),this.decrescendo=!1}}class Un extends An{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class zn extends An{constructor(){super(...arguments),this.octave=1}}class Xn extends An{}class Yn{constructor(){this.defaultClef=u.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class qn{constructor(){this.from=0,this.to=0,this.curly=!1}}class Jn{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class Qn{constructor(){this._trackChannel=0,this._beamingMode=M.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new ze,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;let i=new ft;try{i.parse(e)}catch(e){throw new ke("Could not parse XML",e)}this.parseDom(i),this.consolidate(),this.score.finish(t)}consolidate(){let e=this.score.tempo;for(const t of this.score.tracks){const i=this._voiceCounts.get(t.index);for(const s of t.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const t of s.bars){for(;t.voices.length<i;)t.addVoice(new Ze);for(const e of t.voices)if(0===e.beats.length){const t=new He;t.isEmpty=!0,e.addBeat(t)}const s=t.masterBar;s.tempoAutomation&&(s.tempoAutomation.value!==e?e=s.tempoAutomation.value:s.tempoAutomation=null)}}}Qn.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),Qn.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?b.Decrescendo:b.Crescendo}))}static applyEffectRange(e,t){for(const[i,s]of e){const e=s.noteRange;let a=i;for(let i=0;i<e;i++)if(t(s,a),a.index+1<a.voice.beats.length)a=a.voice.beats[a.index+1];else{if(!(a.voice.bar.index+1<a.voice.bar.staff.bars.length))break;a=a.voice.bar.staff.bars[a.voice.bar.index+1].voices[a.voice.index].beats[0]}}}parseDom(e){let t=e.firstElement;if(t){if("score"!==t.localName)throw new ke("Root node of XML was not GPIF");this.score=new qe,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"info":this.parseInfo(e);break;case"layout":this.parseLayout(e);break;case"gallery":this.parseGallery(e);break;case"pageObjects":this.parsePageObjects(e);break;case"systems":this.parseSystems(e)}}}parseLayout(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"staves":this.parseLayoutStaves(t);break;case"brackets":this.parseBrackets(t)}const t=this._brackets.filter((e=>e.curly));t.sort(((e,t)=>e.from-t.from));let i=0,s=null;for(let e=0;e<this._staffLayouts.length;e++){const a=this._staffLayouts[e];for(;i<t.length&&e>t[i].to;)i++;s&&i<t.length&&e>t[i].from&&e<=t[i].to?s.ensureStaveCount(s.staves.length+1):(s=new $e,s.ensureStaveCount(1),s.name=a.description,s.playbackInfo.volume=Math.floor(a.volume/128*16),s.playbackInfo.program=a.instrument,a.percussion?(s.playbackInfo.primaryChannel=9,s.playbackInfo.secondaryChannel=9):(s.playbackInfo.primaryChannel=this._trackChannel++,s.playbackInfo.secondaryChannel=this._trackChannel++),this.score.addTrack(s));const r=s.staves[s.staves.length-1];r.isPercussion=a.percussion,r.transpositionPitch=a.transpose,r.displayTranspositionPitch=0,r.showTablature=!1,this._staffLookup.set(a.index,r)}}parseBrackets(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"bracket":this.parseBracket(t)}}parseBracket(e){const t=new qn;t.from=parseInt(e.getAttribute("from")),t.to=parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"staffLayout":this.parseStaffLayout(t)}}parseStaffLayout(e){const t=new Yn;t.description=e.getAttribute("description");for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"notation":i.attributes.has("defaultClef")&&(t.defaultClef=this.parseClef(i.attributes.get("defaultClef")));break;case"sound":i.attributes.has("percussion")&&(t.percussion="true"===i.attributes.get("percussion")),i.attributes.has("instr")&&(t.instrument=parseInt(i.attributes.get("instr"))),i.attributes.has("volume")&&(t.volume=parseInt(i.attributes.get("volume"))),i.attributes.has("transpose")&&(t.transpose=parseInt(i.attributes.get("transpose")))}this._staffLayoutLookup.set(t.description,t),t.index=this._staffLayouts.length,this._staffLayouts.push(t)}parseClef(e){switch(e){case"treble":return u.G2;case"bass":return u.F4;case"alto":case"tenor":return u.C4}return u.G2}parseClefOttava(e){return e.endsWith("-")?p._8vb:e.endsWith("+")?p._8va:p.Regular}parseSystems(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"system":this.parseSystem(t)}}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=M.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"staves":this.parseStaves(e,t)}this._isFirstSystem=!1}parseStaves(e,t){let i=this.score.masterBars.length;for(let s of t.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"staff":this.parseStaff(e,i,s)}}parseStaff(e,t,i){const s=i.getAttribute("layout");this._currentStaffLayout=this._staffLayoutLookup.get(s),this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!1,this.parseTime(i.getAttribute("defaultTime"));const a=this._staffLookup.get(this._currentStaffLayout.index);for(;a.bars.length<t;)this.addNewBar(a);for(let r of i.childNodes)if(r.nodeType===H.Element)switch(r.localName){case"voices":this.parseVoices(s,a,e,t,r)}}parseTime(e){switch(e){case"allaBreve":case"C":this._timeSignature.timeSignatureNumerator=2,this._timeSignature.timeSignatureDenominator=2,this._timeSignature.timeSignatureCommon=!0;break;case"longAllaBreve":this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!0;break;default:if(e.indexOf("/")>0){const t=e.split("/");this._timeSignature.timeSignatureNumerator=parseInt(t[0]),this._timeSignature.timeSignatureDenominator=parseInt(t[1]),this._timeSignature.timeSignatureCommon=!1}}}parseVoices(e,t,i,s,a){let r=0;for(let n of a.childNodes)if(n.nodeType===H.Element)switch(n.localName){case"voice":this.parseVoice(e,t,i,r,s,n),r++}}getOrCreateBar(e,t){return t<e.bars.length?e.bars[t]:this.addNewBar(e)}addNewBar(e){let t=new Ne;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){let e=new ze;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,i,s,a,r){const n=e+"_"+s;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,s)):(this._currentVoiceState=new Jn,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(n,this._currentVoiceState),this.newBar(t,s)),r.attributes.has("stemDir"))switch(r.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=U.Up;break;case"down":this._currentVoiceState.voiceStemDir=U.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const o=r.findChildElement("noteObjects");if(i.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new ve,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=d.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(i.attributes.get("tempo"))),o)for(let e of o.childNodes)if(e.nodeType===H.Element)switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,s),e.localName){case"clefSign":this._currentBar.clef=this.parseClef(e.getAttribute("clef")),this._currentBar.clefOttava=this.parseClefOttava(e.getAttribute("clef"));break;case"keySign":this._currentBar.masterBar.keySignature=parseInt(e.getAttribute("fifths"));break;case"timeSign":this.parseTime(e.getAttribute("time")),this._currentBar.masterBar.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,this._currentBar.masterBar.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,this._currentBar.masterBar.timeSignatureCommon=this._timeSignature.timeSignatureCommon,this._currentVoiceState.currentPosition=0,this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1);break;case"barline":switch(e.getAttribute("type")){case"double":this._currentBar.masterBar.isDoubleBar=!0,this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"end":this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0);break;case"repEnd":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"repBegin":this.newBar(t,s),this._currentBar.masterBar.isRepeatStart=!0,this._currentVoiceState.repeatEnd=null,this._currentVoiceState.repeatCount=0;break;case"repEndBegin":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this.newBar(t,s),this._currentBar.masterBar.isRepeatStart=!0;break;case"dashed":this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"single":default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":let i=new He;this.initFromPreviousBeat(i,this._currentVoice),i.beamingMode=this._beamingMode,this._currentVoiceState.voiceStemDir&&(i.preferredBeamDirection=this._currentVoiceState.voiceStemDir),this.parseDuration(this._currentBar,i,e.findChildElement("duration")),i.updateDurations(),this._currentVoiceState.currentPosition+=i.playbackDuration,this._currentVoice.addBeat(i),this.parseChord(i,e),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0);break;case"rest":const a=this.parseRestDurations(this._currentBar,e.findChildElement("duration"));a&&(this.initFromPreviousBeat(a,this._currentVoice),a.updateDurations(),this._currentVoiceState.currentPosition+=a.playbackDuration,this._currentVoice.addBeat(a),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0))}}initFromPreviousBeat(e,t){let i=this.getLastBeat(t);i&&(e.dynamics=i.dynamics)}getLastBeat(e){if(e.beats.length>0)return e.beats[e.beats.length-1];if(e.bar.index>0){const t=e.bar.staff.bars[e.bar.index-1];if(e.index<t.voices.length){const i=t.voices[e.index];return this.getLastBeat(i)}}return null}ensureVoice(e,t){for(;this._currentBar.voices.length<t+1;)this._currentBar.addVoice(new Ze);(!this._voiceCounts.has(e.track.index)||this._voiceCounts.get(e.track.index)<this._currentBar.voices.length)&&this._voiceCounts.set(e.track.index,this._currentBar.voices.length),this._currentVoice=this._currentBar.voices[t]}parseChord(e,t){const i=new Ie;for(let s of t.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"stem":switch(s.getAttribute("dir")){case"up":e.preferredBeamDirection=U.Up;break;case"down":e.preferredBeamDirection=U.Down}break;case"articulation":switch(s.getAttribute("type")){case"staccato":i.isStaccato=!0;break;case"normalAccent":i.accentuated=c.Normal;break;case"strongAccent":i.accentuated=c.Heavy}break;case"lyric":this.parseLyric(e,s);break;case"drawObjects":this.parseBeatDrawObject(e,s);break;case"heads":this.parseHeads(e,i,s);break;case"beam":switch(s.getAttribute("group")){case"force":e.beamingMode=M.ForceMergeWithNext;break;case"divide":e.beamingMode=M.ForceSplitToNext}}}parseHeads(e,t,i){for(let s of i.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"head":this.parseHead(e,t,s)}}parseHead(e,t,i){const s=new Ie,a=fe.parseTuning(i.getAttribute("pitch"));s.octave=a.octave-1,s.tone=a.noteValue,s.isStaccato=t.isStaccato,s.accentuated=t.accentuated,e.addNote(s);for(let e of i.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"alter":e.attributes.has("step")&&(s.tone+=parseInt(e.attributes.get("step")));break;case"tie":e.attributes.has("begin")?this._tieStartIds.has(s.id)||(this._tieStartIds.set(s.id,!0),this._tieStarts.push(s)):e.attributes.has("end")&&this._tieStarts.length>0&&!s.isTieDestination&&(s.isTieDestination=!0,s.tieOriginNoteId=this._tieStarts[0].id,this._tieStarts.splice(0,1),this._tieStartIds.delete(s.id))}}parseBeatDrawObject(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"drawObj":const t=this.parseDrawObj(i);if(t)if(t instanceof Rn)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new ct,e.fermata.type=V.Medium):"f"===t.text?e.dynamics=w.F:"j"===t.text&&(e.dynamics=w.MF):this._isFirstSystem&&""===this.score.title&&t.align===C.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===C.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===C.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof On);else if(t instanceof Vn)e.vibrato=N.Slight;else if(t instanceof Wn)e.crescendo=t.decrescendo?b.Decrescendo:b.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof Gn){const i=t;this._slurs.set(e,i)}else t instanceof Un&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"drawObj":const e=this.parseDrawObj(t);e&&e instanceof Un&&this.applyVolta(e)}}applyVolta(e){if(e.lastNumber>0?(this._currentVoiceState.repeatCount=e.lastNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)):e.firstNumber>0&&(this._currentVoiceState.repeatCount=e.firstNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)),e.lastNumber>0&&e.firstNumber>0){let t=0;for(let i=e.firstNumber;i<=e.lastNumber;i++)t|=1<<i-1;this._currentBar.masterBar.alternateEndings=t}else e.lastNumber>0?this._currentBar.masterBar.alternateEndings=1<<e.lastNumber-1:e.firstNumber>0&&(this._currentBar.masterBar.alternateEndings=1<<e.firstNumber-1)}parseLyric(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"verse":e.lyrics||(e.lyrics=[]);let t=i.innerText;"true"===i.getAttribute("hyphen")&&(t+="-"),e.lyrics.push(t)}}parseRestDurations(e,t){const i=t.getAttribute("base");if(-1!==i.indexOf("/")){let i=new He;return i.beamingMode=this._beamingMode,this.parseDuration(e,i,t),i}if(1===parseInt(i)){let e=new He;return e.beamingMode=this._beamingMode,e.duration=S.Whole,e}return Fe.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return S.DoubleWhole;case"1/1":return S.Whole;case"1/2":return S.Half;case"1/4":return S.Quarter;case"1/8":return S.Eighth;case"1/16":return S.Sixteenth;case"1/32":return S.ThirtySecond;case"1/64":return S.SixtyFourth;case"1/128":return S.OneHundredTwentyEighth;default:return Fe.warning("Importer","Unsupported duration"),S.Quarter}}parseDuration(e,t,i){const s=i.getAttribute("base");t.duration=this.parseDurationValue(s),i.attributes.has("dots")&&(t.dots=parseInt(i.attributes.get("dots")));const a=i.findChildElement("tuplet");if(a){t.tupletNumerator=parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,i="true"===a.getAttribute("prolong")?0:1;let s=0;for(;e*Math.pow(2,s+i)<t.tupletNumerator;)s++;t.tupletDenominator=e*Math.pow(2,s)}}parsePageObjects(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"drawObj":const e=this.parseDrawObj(t);if(e&&e instanceof Rn)switch(e.align){case C.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case C.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"drawObj":const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,i=1;for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"text":t=this.parseText(s);break;case"guitar":t=this.parseGuitar(s);break;case"slur":t=this.parseSlur(s);break;case"wavyLine":t=this.parseWavyLine(s);break;case"bracket":t=this.parseTupletBracket(s);break;case"wedge":t=this.parseWedge(s);break;case"volta":t=this.parseVolta(s);break;case"octaveClef":t=this.parseOctaveClef(s);break;case"trill":t=this.parseTrill(s);break;case"basic":s.attributes.has("noteRange")&&(i=parseInt(s.attributes.get("noteRange")))}return t&&(t.noteRange=i),t}parseTrill(e){return new Xn}parseOctaveClef(e){const t=new zn;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new Un;return t.allNumbers="true"===e.attributes.get("allNumbers"),e.attributes.has("firstNumber")&&(t.firstNumber=parseInt(e.attributes.get("firstNumber"))),e.attributes.has("lastNumber")&&(t.lastNumber=parseInt(e.attributes.get("lastNumber"))),t}parseWedge(e){const t=new Wn;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Hn;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new Vn}parseSlur(e){return new Gn}parseGuitar(e){const t=new On,i=e.innerText.trim();for(let e=0;e<i.length;e++)"/"===i.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(parseInt(i.charAt(e)));return t}parseText(e){const t=new Rn;switch(e.attributes.has("x")&&(t.x=parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=C.Left;break;case"center":t.align=C.Center;break;case"right":t.align=C.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=he.Rectangle;break;case"ellipse":t.frame=he.Ellipse;break;case"circle":t.frame=he.Circle;break;case"none":t.frame=he.None}if(e.firstElement){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"font":t.fontFace=i.getAttribute("face"),i.attributes.has("weight")&&(t.weight=parseInt(i.attributes.get("weight"))),i.attributes.has("height")&&(t.height=parseInt(i.attributes.get("height")));break;case"content":t.text=i.innerText}}else t.text=e.innerText;return t}parseInfo(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class jn extends Te{get name(){return"Capella"}constructor(){super()}readScore(){Fe.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Ct(this.data).read(),Fe.debug(this.name,"Zip entries loaded"),e.length>0)for(let i of e)switch(i.fileName){case"score.xml":t=st.toString(i.data,this.settings.importer.encoding)}else this.data.reset(),t=st.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new ke("No valid capella file");Fe.debug(this.name,"Start Parsing score.xml");try{let e=new Qn;return e.parseXml(t,this.settings),Fe.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new ke("Failed to parse CapXML",e)}}}class Kn{constructor(e){this._targets=new Set,this._callback=e,window.addEventListener("resize",this.onWindowResize.bind(this),!1)}observe(e){this._targets.add(e)}unobserve(e){this._targets.delete(e)}disconnect(){this._targets.clear()}onWindowResize(){const e=[];for(const t of this._targets)e.push({target:t,contentRect:void 0,borderBoxSize:void 0,contentBoxSize:[]});this._callback(e,this)}}class $n{constructor(e){this._elements=[];let t=null;const i=this._check.bind(this);this._check=()=>{t||(t=setTimeout((()=>{i(),t=null}),100))},this._callback=e,window.addEventListener("resize",this._check,!0),document.addEventListener("scroll",this._check,!0)}observe(e){this._elements.indexOf(e)>=0||(this._elements.push(e),this._check())}unobserve(e){this._elements=this._elements.filter((t=>t!=e))}_check(){const e=[];this._elements.forEach((t=>{const i=t.getBoundingClientRect();i.top+i.height>=0&&i.top<=window.innerHeight&&i.left+i.width>=0&&i.left<=window.innerWidth&&e.push({target:t,isIntersecting:!0})})),e.length&&this._callback(e,this)}}class Zn{constructor(e,t){this.vertical=e,this.createLayout=t}}class eo{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class to{static createStyleElement(e,t){let i=e.getElementById("alphaTabStyle");if(!i){if(!t)return void Fe.error("AlphaTab","Font directory could not be detected, cannot create style element");i=e.createElement("style"),i.id="alphaTabStyle";let s=`\n @font-face {\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n } \n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${to.MusicFontSize}px;\n overflow: visible !important;\n }`;i.innerHTML=s,e.getElementsByTagName("head").item(0).appendChild(i),to.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===to._globalThis){try{to._globalThis=globalThis}catch(e){}void 0===to._globalThis&&(to._globalThis=self),void 0===to._globalThis&&(to._globalThis=window),void 0===to._globalThis&&(to._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in to.globalThis}static throttle(e,t){let i=0;return()=>{window.clearTimeout(i),i=window.setTimeout(e,t)}}static detectScriptFile(){return to.isRunningInWorker?null:document.currentScript.src}static registerJQueryPlugin(){if(!to.isRunningInWorker&&to.globalThis&&"jQuery"in to.globalThis){let e=to.globalThis.jQuery,t=new Js;e.fn.alphaTab=function(e){const i=Array.prototype.slice.call(arguments,1);return 1===this.length?t.exec(this[0],e,i):this.each(((s,a)=>{t.exec(a,e,i)}))},e.alphaTab={restore:Js.restore},e.fn.alphaTab.fn=t}}static createScoreRenderer(e){return new fs(e)}static getRenderEngineFactory(e){return e.core.engine&&to.renderEngines.has(e.core.engine)?to.renderEngines.get(e.core.engine):to.renderEngines.get("default")}static getLayoutEngineFactory(t){return t.display.layoutMode&&to.layoutEngines.has(t.display.layoutMode)?to.layoutEngines.get(t.display.layoutMode):to.layoutEngines.get(e.LayoutMode.Page)}static buildImporters(){return[new at,new At,new Ft,new Rt,new jn,new tt]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new eo(!0,(()=>new js))),e.set("default",e.get("svg")),to.createPlatformSpecificRenderEngines(e),e}static createPlatformSpecificRenderEngines(e){e.set("html5",new eo(!1,(()=>new ys)))}static createDefaultStaveProfiles(){const t=new Map;t.set(e.StaveProfile.ScoreTab,[new ba("score-effects",[new er,new rr,new Ha,new tr,new ka,new Ma,new nr,new sr,new Ua(!0),new or,new Qa,new hr,new Ka,new Dn,new _a]),new Sn,new ba("tab-effects",[new xa,new Ua(!1),new Ea,new Va,new sr,new or,new Qa,new hr,new Ka,new $a,new Fa,new Ra(B.Natural),new Ra(B.Artificial),new Ra(B.Pinch),new Ra(B.Tap),new Ra(B.Semi),new Ra(B.Feedback),new Oa,new Ta,new Ia,new za,new qa,new Xa,new Dn]),new Mn(!1,!1,!1)]),t.set(e.StaveProfile.Score,[new ba("score-effects",[new er,new rr,new Ha,new tr,new ka,new Ma,new nr,new sr,new Ua(!0),new or,new Qa,new hr,new Ka,new Fa,new Oa,new za,new qa,new Xa,new Dn,new _a]),new Sn,new ba("score-bottom-effects",[new xa,new Ua(!1),new Ea,new Va])]);let i=[new er,new rr,new Ha,new tr,new ka,new Ma,new sr,new or,new Qa,new hr,new Ka,new $a,new Fa,new Ra(B.Artificial),new Ra(B.Pinch),new Ra(B.Tap),new Ra(B.Semi),new Ra(B.Feedback),new Oa,new Ta,new Ia,new za,new qa,new Xa,new Dn,new _a];return t.set(e.StaveProfile.Tab,[new ba("tab-effects",i),new Mn(!0,!0,!0),new ba("tab-bottom-effects",[new Va])]),t.set(e.StaveProfile.TabMixed,[new ba("tab-effects",i),new Mn(!1,!1,!1),new ba("tab-bottom-effects",[new Va])]),t}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.LayoutMode.Page,new Zn(!0,(e=>new kr(e)))),t.set(e.LayoutMode.Horizontal,new Zn(!1,(e=>new Tr(e)))),t}static platformInit(){to.registerJQueryPlugin(),to.isRunningInWorker?(ms.init(),ns.init()):(to.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in globalThis||(globalThis.ResizeObserver=Kn),"IntersectionObserver"in to.globalThis||(to.globalThis.IntersectionObserver=$n))}}to.MusicFontSize=34,to.HighDpiFactor=1,to._globalThis=void 0,to.scriptFile=to.detectScriptFile(),to.bravuraFontChecker=new Vs("alphaTab"),to.renderEngines=to.createDefaultRenderEngines(),to.layoutEngines=to.createDefaultLayoutEngines(),to.staveProfiles=to.createDefaultStaveProfiles(),to.platformInit();class io{constructor(){if(this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=e.LogLevel.Info,this.useWorkers=!0,this.includeNoteBounds=!1,!to.isRunningInWorker&&to.globalThis.ALPHATAB_ROOT?(this.scriptFile=to.globalThis.ALPHATAB_ROOT,this.scriptFile=io.ensureFullUrl(this.scriptFile),this.scriptFile=io.appendScriptName(this.scriptFile)):this.scriptFile=to.scriptFile,!to.isRunningInWorker&&to.globalThis.ALPHATAB_FONT)this.fontDirectory=to.globalThis.ALPHATAB_FONT,this.fontDirectory=io.ensureFullUrl(this.fontDirectory);else if(this.fontDirectory=this.scriptFile,this.fontDirectory){let e=this.fontDirectory.lastIndexOf(String.fromCharCode(47));e>=0&&(this.fontDirectory=this.fontDirectory.substr(0,e)+"/font/")}}static ensureFullUrl(e){var t,i,s;if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let a="",r=to.globalThis.location;if(a+=null===(t=r.protocol)||void 0===t?void 0:t.toString(),a+="//".toString(),r.hostname&&(a+=null===(i=r.hostname)||void 0===i?void 0:i.toString()),r.port&&(a+=":".toString(),a+=null===(s=r.port)||void 0===s?void 0:s.toString()),!e.startsWith("/")){let e=r.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString())}return e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString(),a}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}}class so{constructor(e,t){this.loaded=e,this.total=t}}class ao{}ao.version="1.2.2",ao.date="2021-11-03T16:39:54.538Z";class ro{init(e,t){this.data=e,this.settings=t}export(e,t=null){const i=ot.withCapacity(1024);return this.init(i,null!=t?t:new Gi),this.writeScore(e),i.toArray()}}!function(e){e[e.SteelGuitar=1]="SteelGuitar",e[e.AcousticGuitar=2]="AcousticGuitar",e[e.TwelveStringGuitar=3]="TwelveStringGuitar",e[e.ElectricGuitar=4]="ElectricGuitar",e[e.Bass=5]="Bass",e[e.ClassicalGuitar=23]="ClassicalGuitar",e[e.UprightBass=6]="UprightBass",e[e.Ukulele=7]="Ukulele",e[e.Banjo=8]="Banjo",e[e.Mandolin=9]="Mandolin",e[e.Piano=10]="Piano",e[e.Synth=12]="Synth",e[e.Strings=11]="Strings",e[e.Brass=13]="Brass",e[e.Reed=14]="Reed",e[e.Woodwind=15]="Woodwind",e[e.Vocal=16]="Vocal",e[e.PitchedIdiophone=17]="PitchedIdiophone",e[e.Fx=21]="Fx",e[e.PercussionKit=18]="PercussionKit",e[e.Idiophone=19]="Idiophone",e[e.Membraphone=20]="Membraphone"}(le||(le={}));class no{constructor(e,t,i=null){if(this.icon=le.Piano,this.icon=e,this.instrumentSetName=t,i)this.instrumentSetType=i;else{const e=t.split(" ");e[0]=e[0].substr(0,1).toLowerCase()+e[0].substr(1),this.instrumentSetType=e.join("")}}}class oo{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new ft;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toString("",!0)}writeDom(e,t){const i=e.addElement("GPIF");i.addElement("GPVersion").innerText="7";const s=i.addElement("GPRevision");s.innerText="7",s.attributes.set("required","12021"),s.attributes.set("recommended","12023"),s.innerText="12025",i.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(i,t),this.writeMasterTrackNode(i,t),this.writeAudioTracksNode(i,t),this.writeTracksNode(i,t),this.writeMasterBarsNode(i,t);const a=i.addElement("Bars"),r=i.addElement("Voices"),n=i.addElement("Beats"),o=i.addElement("Notes"),h=i.addElement("Rhythms");for(const e of t.tracks)for(const t of e.staves)for(const e of t.bars){this.writeBarNode(a,e);for(const t of e.voices){this.writeVoiceNode(r,t);for(const e of t.beats){this.writeBeatNode(n,e,h);for(const t of e.notes)this.writeNoteNode(o,t)}}}}writeNoteNode(e,t){const s=e.addElement("Note");s.attributes.set("id",t.id.toString()),this.writeNoteProperties(s,t),t.isGhost&&(s.addElement("AntiAccent").innerText="normal"),t.isLetRing&&s.addElement("LetRing"),t.isTrill&&(s.addElement("Trill").innerText=t.trillValue.toString());let a=0;switch(t.isStaccato&&(a|=1),t.accentuated){case c.Normal:a|=8;break;case c.Heavy:a|=4}if(a>0&&(s.addElement("Accent").innerText=a.toString()),t.isTieOrigin||t.isTieDestination){const e=s.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case N.Slight:s.addElement("Vibrato").innerText="Slight";break;case N.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case i.Thumb:s.addElement("LeftFingering").innerText="P";break;case i.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case i.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case i.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case i.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case i.Thumb:s.addElement("RightFingering").innerText="P";break;case i.IndexFinger:s.addElement("RightFingering").innerText="I";break;case i.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case i.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case i.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0"}writeNoteProperties(e,t){const i=e.addElement("Properties");if(this.writeConcertPitch(i,t),this.writeTransposedPitch(i,t),t.isStringed&&(this.writeSimplePropertyNode(i,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(i,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(i,"Midi","Number",t.realValue.toString())),t.isPiano&&(this.writeSimplePropertyNode(i,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(i,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(i,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(i,"Tapped","Enable",null),t.harmonicType!==B.None){switch(t.harmonicType){case B.Natural:this.writeSimplePropertyNode(i,"HarmonicType","HType","Natural");break;case B.Artificial:this.writeSimplePropertyNode(i,"HarmonicType","HType","Artificial");break;case B.Pinch:this.writeSimplePropertyNode(i,"HarmonicType","HType","Pinch");break;case B.Tap:this.writeSimplePropertyNode(i,"HarmonicType","HType","Tap");break;case B.Semi:this.writeSimplePropertyNode(i,"HarmonicType","HType","Semi");break;case B.Feedback:this.writeSimplePropertyNode(i,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(i,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(i,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(i,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(i,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(i,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(i,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(i,"LeftHandTapped","Enable",null);let s=0;switch(t.slideInType){case k.IntoFromAbove:s|=32;break;case k.IntoFromBelow:s|=16}switch(t.slideOutType){case v.Shift:s|=1;break;case v.Legato:s|=2;break;case v.OutDown:s|=4;break;case v.OutUp:s|=8;break;case v.PickSlideDown:s|=64;break;case v.PickSlideUp:s|=128}s>0&&this.writeSimplePropertyNode(i,"Slide","Flags",s.toString())}writeTransposedPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"TransposedPitch",t.displayValueWithoutBend,t.accidentalMode)}writeConcertPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"ConcertPitch",t.realValueWithoutHarmonic,t.accidentalMode)}writePitchForValue(e,t,i,s){let a=0,r=0,n="",o="";const h=()=>{a=i%12,r=i/12|0,n=je.defaultSteps[a],o=je.defaultAccidentals[a]};switch(h(),s){case T.Default:break;case T.ForceNone:case T.ForceNatural:o="";break;case T.ForceSharp:o="#";break;case T.ForceDoubleSharp:"#"===o&&(i-=2,h()),o="x";break;case T.ForceFlat:"#"===o&&(i+=1,h()),o="b";break;case T.ForceDoubleFlat:"#"===o&&(i+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,i,s,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=i,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=s}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);var i,s,a=t[0],r=t[t.length-1];switch(t.length){case 4:i=t[1],s=t[2];break;case 3:i=t[1],s=t[1];break;case 2:default:s=i=new Pe((a.offset+r.offset)/2,(a.value+r.value)/2)}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(r.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(i.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(i.value).toString()),this.writeSimplePropertyNode(e,"BendOriginOffset","Float",this.toBendOffset(a.offset).toString()),this.writeSimplePropertyNode(e,"BendOriginValue","Float",this.toBendValue(a.value).toString())}toBendValue(e){return 25*e}toBendOffset(e){return e/Pe.MaxPosition*100}writeBeatNode(e,t,i){const s=e.addElement("Beat");if(s.attributes.set("id",t.id.toString()),s.addElement("Dynamic").innerText=w[t.dynamics],t.fadeIn&&(s.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case S.Eighth:s.addElement("Tremolo").innerText="1/2";break;case S.Sixteenth:s.addElement("Tremolo").innerText="1/4";break;case S.ThirtySecond:s.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&s.addElement("Chord").setCData(t.chordId),t.crescendo!==b.None&&(s.addElement("Hairpin").innerText=b[t.crescendo]),t.brushType){case y.ArpeggioUp:s.addElement("Arpeggio").innerText="Up";break;case y.ArpeggioDown:s.addElement("Arpeggio").innerText="Down"}switch(t.text&&s.addElement("FreeText").setCData(t.text),t.graceType){case _.OnBeat:case _.BeforeBeat:s.addElement("GraceNotes").innerText=_[t.graceType]}if(t.ottava!==p.Regular&&(s.addElement("Ottavia").innerText=p[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(s,t),t.isLegatoOrigin||t.isLegatoDestination){const e=s.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(s,t,i),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case U.Up:s.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case U.Down:s.addElement("TransposedPitchStemOrientation").innerText="Downward"}s.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.isRest||(s.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),this.writeBeatProperties(s,t),this.writeBeatXProperties(s,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(s,t.lyrics)}writeBeatLyrics(e,t){const i=e.addElement("Lyrics");for(const e of t){i.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const i=e.addElement("XProperties");t.brushDuration>0&&this.writeSimpleXPropertyNode(i,"687935489","Int",t.brushDuration.toString())}writeBeatProperties(e,t){const i=e.addElement("Properties");switch(t.brushType){case y.BrushUp:this.writeSimplePropertyNode(i,"Brush","Direction","Up");break;case y.BrushDown:this.writeSimplePropertyNode(i,"Brush","Direction","Down")}switch(t.pickStroke){case P.Up:this.writeSimplePropertyNode(i,"PickStroke","Direction","Up");break;case P.Down:this.writeSimplePropertyNode(i,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(i,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(i,"Popped","Enable",null),t.vibrato){case N.Wide:this.writeSimplePropertyNode(i,"VibratoWTremBar","Strength","Wide");break;case N.Slight:this.writeSimplePropertyNode(i,"VibratoWTremBar","Strength","Slight")}}writeRhythm(e,t,i){const s=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(s))a=this._rhythmIdLookup.get(s);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(s,a);const e=i.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const i=e.addElement("PrimaryTuplet");i.attributes.set("num",t.tupletNumerator.toString()),i.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case S.QuadrupleWhole:r="Long";break;case S.DoubleWhole:r="DoubleWhole";break;case S.Whole:r="Whole";break;case S.Half:r="Half";break;case S.Quarter:r="Quarter";break;case S.Eighth:r="Eighth";break;case S.Sixteenth:r="16th";break;case S.ThirtySecond:r="32nd";break;case S.SixtyFourth:r="64th";break;case S.OneHundredTwentyEighth:r="128th";break;case S.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const i=e.addElement("Whammy");var s,a,r=t[0],n=t[t.length-1];switch(t.length){case 4:s=t[1],a=t[2];break;case 3:s=t[1],a=t[1];break;case 2:default:a=s=new Pe((r.offset+n.offset)/2,(r.value+n.value)/2)}i.attributes.set("destinationOffset",this.toBendOffset(n.offset).toString()),i.attributes.set("destinationValue",this.toBendValue(n.value).toString()),i.attributes.set("middleOffset1",this.toBendOffset(s.offset).toString()),i.attributes.set("middleOffset2",this.toBendOffset(a.offset).toString()),i.attributes.set("middleValue",this.toBendValue(s.value).toString()),i.attributes.set("originOffset",this.toBendOffset(r.offset).toString()),i.attributes.set("originValue",this.toBendValue(r.value).toString())}writeScoreNode(e,t){const i=e.addElement("Score");i.addElement("Title").setCData(t.title),i.addElement("SubTitle").setCData(t.subTitle),i.addElement("Artist").setCData(t.artist),i.addElement("Album").setCData(t.album),i.addElement("Words").setCData(t.words),i.addElement("Music").setCData(t.music),i.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),i.addElement("Copyright").setCData(t.copyright),i.addElement("Tabber").setCData(t.tab),i.addElement("Instructions").setCData(t.instructions),i.addElement("Notices").setCData(t.notices),i.addElement("FirstPageHeader").setCData(""),i.addElement("FirstPageFooter").setCData(""),i.addElement("PageHeader").setCData(""),i.addElement("PageFooter").setCData(""),i.addElement("ScoreSystemsDefaultLayout").setCData("4"),i.addElement("ScoreSystemsLayout").setCData("4"),i.addElement("ScoreZoomPolicy").innerText="Value",i.addElement("ScoreZoom").innerText="1",i.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const i=e.addElement("MasterTrack");i.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const s=i.addElement("Automations");t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&i.addElement("Anacrusis");const a=s.addElement("Automation");a.addElement("Type").innerText="Tempo",a.addElement("Linear").innerText="false",a.addElement("Bar").innerText="0",a.addElement("Position").innerText="0",a.addElement("Visible").innerText="true",a.addElement("Value").innerText=t.tempo+" 2",t.tempoLabel&&(a.addElement("Text").innerText=t.tempoLabel);for(const e of t.masterBars)if(e.index>0&&e.tempoAutomation){const t=s.addElement("Automation");t.addElement("Type").innerText="Tempo",t.addElement("Linear").innerText=e.tempoAutomation.isLinear?"true":"false",t.addElement("Bar").innerText=e.index.toString(),t.addElement("Position").innerText=e.tempoAutomation.ratioPosition.toString(),t.addElement("Visible").innerText="true",t.addElement("Value").innerText=e.tempoAutomation.value+" 2",e.tempoAutomation.text&&(t.addElement("Text").innerText=e.tempoAutomation.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const i=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(i,e)}writeTrackNode(e,t){const i=e.addElement("Track");i.attributes.set("id",t.index.toString()),i.addElement("Name").setCData(t.name),i.addElement("ShortName").setCData(t.shortName),i.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,i.addElement("SystemsDefautLayout").innerText="3",i.addElement("SystemsLayout").innerText="1",i.addElement("AutoBrush"),i.addElement("PalmMute").innerText="0",i.addElement("PlayingStyle").innerText=ue.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",i.addElement("UseOneChannelPerString"),i.addElement("IconId").innerText=oo.getIconId(t.playbackInfo).toString(),this.writeInstrumentSetNode(i,t),this.writeTransposeNode(i,t),this.writeRseNode(i,t),i.addElement("ForcedSound").innerText="-1",this.writeMidiConnectionNode(i,t),t.playbackInfo.isSolo?i.addElement("PlaybackState").innerText="Solo":t.playbackInfo.isMute?i.addElement("PlaybackState").innerText="Mute":i.addElement("PlaybackState").innerText="Default",i.addElement("AudioEngineState").innerText="MIDI",this.writeLyricsNode(i,t),this.writeStavesNode(i,t),this.writeSoundsAndAutomations(i,t)}static getIconId(e){return 9===e.primaryChannel?oo.DrumKitProgramInfo.icon:oo.MidiProgramInfoLookup.has(e.program)?oo.MidiProgramInfoLookup.get(e.program).icon:le.SteelGuitar}writeSoundAndAutomation(e,t,i,s,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(i),h.addElement("Label").setCData(i),h.addElement("Path").setCData(s),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${s};${i};${a}`)}writeSoundsAndAutomations(e,t){const i=e.addElement("Sounds"),s=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,a="Midi/"+t.playbackInfo.program,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(i,s,e,a,r,t.staves[0].bars[0].index,t.playbackInfo.program),n=!0),this.writeSoundAndAutomation(i,s,d,u,p,h.index,o.value,o.ratioPosition),c&&(n=!0)}}}}writeMidiConnectionNode(e,t){const i=e.addElement("MidiConnection");i.addElement("Port").innerText=t.playbackInfo.port.toString(),i.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),i.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),i.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const i=e.addElement("RSE").addElement("ChannelStrip");i.attributes.set("version","E56");i.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const i=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(i,e)}writeStaffNode(e,t){const i=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(i,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(i,"FretCount","Fret","24"),t.tuning.length>0){const e=i.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(i,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(i,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(i,"TuningFlat","Enable",null),this.writeDiagramCollection(i,t,"DiagramCollection"),this.writeDiagramCollection(i,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const a=e.addElement("Property");a.attributes.set("name",s);const r=a.addElement("Items");for(const[e,s]of t.chords){const t=r.addElement("Item");t.attributes.set("id",e),t.attributes.set("name",s.name);const a=t.addElement("Diagram");a.attributes.set("stringCount",s.strings.length.toString()),a.attributes.set("fretCount","5"),a.attributes.set("baseFret",(s.firstFret-1).toString()),a.attributes.set("barStates",s.strings.map((e=>"1")).join(" "));const n=[],o=new Map;for(let e=0;e<s.strings.length;e++){let t=s.strings[e];if(-1!==t){const i=a.addElement("Fret"),r=s.strings.length-1-e;i.attributes.set("string",r.toString()),i.attributes.set("fret",(t-s.firstFret+1).toString()),o.has(t)||(o.set(t,[]),n.push(t)),o.get(t).push(r)}}n.sort();const h=a.addElement("Fingering");if(s.barreFrets.length>0){const e=[i.LittleFinger,i.AnnularFinger,i.MiddleFinger,i.IndexFinger];for(const t of n){const a=o.get(t);if(a.length>1&&s.barreFrets.indexOf(t)>=0){const r=e.length>0?e.pop():i.IndexFinger;for(const e of a){const a=h.addElement("Position");switch(r){case i.LittleFinger:a.attributes.set("finger","Pinky");break;case i.AnnularFinger:a.attributes.set("finger","Ring");break;case i.MiddleFinger:a.attributes.set("finger","Middle");break;case i.IndexFinger:a.attributes.set("finger","Index")}a.attributes.set("fret",(t-s.firstFret+1).toString()),a.attributes.set("string",e.toString())}}}}const l=a.addElement("Property");l.attributes.set("name","ShowName"),l.attributes.set("type","bool"),l.attributes.set("value",s.showName?"true":"false");const c=a.addElement("Property");c.attributes.set("name","ShowDiagram"),c.attributes.set("type","bool"),c.attributes.set("value",s.showDiagram?"true":"false");const d=a.addElement("Property");d.attributes.set("name","ShowFingering"),d.attributes.set("type","bool"),d.attributes.set("value",s.showFingering?"true":"false");const u=a.addElement("Chord"),p=u.addElement("KeyNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=u.addElement("BassNote");g.attributes.set("step","C"),g.attributes.set("accidental","Natural");const f=u.addElement("Degree");f.attributes.set("interval","Third"),f.attributes.set("alteration","Major"),f.attributes.set("omitted","false");const m=u.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,i,s){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(i);return null!==s&&(r.innerText=s),a}writeSimpleXPropertyNode(e,t,i,s){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(i);return null!==s&&(r.innerText=s),a}writeLyricsNode(e,t){const i=e.addElement("Lyrics");i.attributes.set("dispatched","true");let s=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const i of t.beats)if(i.lyrics)for(let t=0;t<i.lyrics.length;t++){for(;t>=s.length;){const t=new Ue;t.startBar=e.index,t.text="[Empty]",s.push(t)}const a=s[t];a.text="[Empty]"==a.text?i.lyrics[t]:a.text+" "+i.lyrics[t].split(" ").join("+")}for(let e=0;e<s.length;e++){const t=i.addElement("Line");t.addElement("Text").setCData(s[e].text),t.addElement("Offset").innerText=s[e].startBar.toString()}}writeTransposeNode(e,t){const i=e.addElement("Transpose"),s=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*s;i.addElement("Chromatic").innerText=a.toString(),i.addElement("Octave").innerText=s.toString()}writeInstrumentSetNode(e,t){const i=e.addElement("InstrumentSet"),s=t.staves[0];if(i.addElement("LineCount").innerText=s.standardNotationLineCount.toString(),t.percussionArticulations.length>0||s.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(Me.instrumentArticulations.values());i.addElement("Name").innerText=oo.DrumKitProgramInfo.instrumentSetName,i.addElement("Type").innerText=oo.DrumKitProgramInfo.instrumentSetType;let s="",r=null,n=new Map;const o=i.addElement("Elements");for(const t of e){{var a=o.addElement("Element");let e=t.elementType;if(n.has(e)){const t=n.get(e);e+=" "+t,n.set(e,t+1)}else n.set(e,1);s=e,a.addElement("Name").innerText=e,a.addElement("Type").innerText=t.elementType,r=a.addElement("Articulations")}const e=r.addElement("Articulation");switch(e.addElement("Name").innerText=s+" "+r.childNodes.length,e.addElement("StaffLine").innerText=t.staffLine.toString(),e.addElement("Noteheads").innerText=[this.mapMusicSymbol(t.noteHeadDefault),this.mapMusicSymbol(t.noteHeadHalf),this.mapMusicSymbol(t.noteHeadWhole)].join(" "),t.techniqueSymbolPlacement){case F.Top:e.addElement("TechniquePlacement").innerText="below";break;case F.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case F.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=oo.MidiProgramInfoLookup.has(t.playbackInfo.program)?oo.MidiProgramInfoLookup.get(t.playbackInfo.program):oo.MidiProgramInfoLookup.get(0);i.addElement("Name").innerText=e.instrumentSetName,i.addElement("Type").innerText=e.instrumentSetType;const s=i.addElement("Elements").addElement("Element");s.addElement("Pitched").innerText="Pitched",s.addElement("Type").innerText="pitched",s.addElement("SoundbankName").innerText="";const a=s.addElement("Articulations").addElement("Articulation");a.addElement("Name").innerText="",a.addElement("StaffLine").innerText="0",a.addElement("Noteheads").innerText="noteheadBlack noteheadHalf noteheadWhole",a.addElement("TechniquePlacement").innerText="outside",a.addElement("TechniqueSymbol").innerText="",a.addElement("InputMidiNumbers").innerText="",a.addElement("OutputRSESound").innerText="",a.addElement("OutputMidiNumber").innerText="0"}}mapMusicSymbol(e){if(e===E.None)return"";let t=E[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const i=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(i,e)}writeMasterBarNode(e,t){const i=e.addElement("MasterBar"),s=i.addElement("Key");s.addElement("AccidentalCount").innerText=t.keySignature.toString(),s.addElement("Mode").innerText=A[t.keySignatureType],s.addElement("Sharps").innerText="Sharps",i.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`;let a=[];for(const e of t.score.tracks)for(const i of e.staves)a.push(i.bars[t.index].id.toString());if(i.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&i.addElement("DoubleBar"),t.isSectionStart){const e=i.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=i.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const s=[];let a=0;for(;e>0;)1==(e>>a&1)&&(s.push(a+1),e&=~(1<<a)),a++;i.addElement("AlternateEndings").innerText=s.join(" ")}t.tripletFeel!==R.NoTripletFeel&&(i.addElement("TripletFeel").innerText=R[t.tripletFeel]),this.writeFermatas(i,t)}writeFermatas(e,t){if(0!==t.fermata.size&&t.fermata.size>0){const i=e.addElement("Fermatas");for(const[e,s]of t.fermata)this.writeFermata(i,e,s)}}writeFermata(e,t,i){let s=-1,a=1;if(t>0)for(;a<10&&(s=t/xe.QuarterTime*a,s!==Math.floor(s));)s=-1,a++;else s=0,a=1;if(-1===s)return;const r=e.addElement("Fermata");r.addElement("Type").innerText=V[i.type],r.addElement("Length").innerText=i.length.toString(),r.addElement("Offset").innerText=`${s}/${a}`}writeBarNode(e,t){const i=e.addElement("Bar");i.attributes.set("id",t.id.toString()),i.addElement("Voices").innerText=t.voices.map((e=>e.isEmpty?"-1":e.id.toString())).join(" "),i.addElement("Clef").innerText=u[t.clef],t.clefOttava!==p.Regular&&(i.addElement("Ottavia").innerText=p[t.clefOttava].substr(1)),t.simileMark!==g.None&&(i.addElement("SimileMark").innerText=g[t.simileMark])}writeVoiceNode(e,t){if(t.isEmpty)return;const i=e.addElement("Voice");i.attributes.set("id",t.id.toString()),i.addElement("Beats").innerText=t.beats.map((e=>e.id)).join(" ")}}oo.MidiProgramInfoLookup=new Map([[0,new no(le.Piano,"Acoustic Piano")],[1,new no(le.Piano,"Acoustic Piano")],[2,new no(le.Piano,"Electric Piano")],[3,new no(le.Piano,"Acoustic Piano")],[4,new no(le.Piano,"Electric Piano")],[5,new no(le.Piano,"Electric Piano")],[6,new no(le.Piano,"Harpsichord")],[7,new no(le.Piano,"Harpsichord")],[8,new no(le.PitchedIdiophone,"Celesta")],[9,new no(le.PitchedIdiophone,"Vibraphone")],[10,new no(le.PitchedIdiophone,"Vibraphone")],[11,new no(le.PitchedIdiophone,"Vibraphone")],[12,new no(le.PitchedIdiophone,"Xylophone")],[13,new no(le.PitchedIdiophone,"Xylophone")],[14,new no(le.PitchedIdiophone,"Vibraphone")],[15,new no(le.Banjo,"Banjo")],[16,new no(le.Piano,"Electric Organ")],[17,new no(le.Piano,"Electric Organ")],[18,new no(le.Piano,"Electric Organ")],[19,new no(le.Piano,"Electric Organ")],[20,new no(le.Piano,"Electric Organ")],[21,new no(le.Piano,"Electric Organ")],[22,new no(le.Woodwind,"Recorder")],[23,new no(le.Piano,"Electric Organ")],[24,new no(le.ClassicalGuitar,"Nylon Guitar")],[25,new no(le.SteelGuitar,"Steel Guitar")],[26,new no(le.SteelGuitar,"Electric Guitar")],[27,new no(le.ElectricGuitar,"Electric Guitar")],[28,new no(le.ElectricGuitar,"Electric Guitar")],[29,new no(le.ElectricGuitar,"Electric Guitar")],[30,new no(le.SteelGuitar,"Electric Guitar")],[31,new no(le.SteelGuitar,"Electric Guitar")],[32,new no(le.Bass,"Acoustic Bass")],[33,new no(le.Bass,"Electric Bass")],[34,new no(le.Bass,"Electric Bass")],[35,new no(le.Bass,"Acoustic Bass")],[36,new no(le.Bass,"Electric Bass")],[37,new no(le.Bass,"Electric Bass")],[38,new no(le.Synth,"Synth Bass")],[39,new no(le.Synth,"Synth Bass")],[40,new no(le.Strings,"Violin")],[41,new no(le.Strings,"Viola")],[42,new no(le.Strings,"Cello")],[43,new no(le.Strings,"Contrabass")],[44,new no(le.Strings,"Violin")],[45,new no(le.Strings,"Violin")],[46,new no(le.Piano,"Harp")],[47,new no(le.Membraphone,"Timpani")],[48,new no(le.Strings,"Violin")],[49,new no(le.Strings,"Violin")],[50,new no(le.Strings,"Violin")],[51,new no(le.Strings,"Violin")],[52,new no(le.Vocal,"Voice")],[53,new no(le.Vocal,"Voice")],[54,new no(le.Vocal,"Voice")],[55,new no(le.Synth,"Pad Synthesizer")],[56,new no(le.Brass,"Trumpet")],[57,new no(le.Brass,"Trombone")],[58,new no(le.Brass,"Tuba")],[59,new no(le.Brass,"Trumpet")],[60,new no(le.Brass,"French Horn")],[61,new no(le.Brass,"Trumpet")],[62,new no(le.Brass,"Trumpet")],[63,new no(le.Brass,"Trumpet")],[64,new no(le.Reed,"Saxophone")],[65,new no(le.Reed,"Saxophone")],[66,new no(le.Reed,"Saxophone")],[67,new no(le.Reed,"Saxophone")],[68,new no(le.Reed,"Oboe")],[69,new no(le.Reed,"English Horn")],[70,new no(le.Reed,"Bassoon")],[71,new no(le.Reed,"Clarinet")],[72,new no(le.Reed,"Piccolo")],[73,new no(le.Woodwind,"Flute")],[74,new no(le.Woodwind,"Recorder")],[75,new no(le.Woodwind,"Flute")],[76,new no(le.Woodwind,"Recorder")],[77,new no(le.Woodwind,"Flute")],[78,new no(le.Woodwind,"Recorder")],[79,new no(le.Woodwind,"Flute")],[80,new no(le.Synth,"Lead Synthesizer")],[81,new no(le.Synth,"Lead Synthesizer")],[82,new no(le.Synth,"Lead Synthesizer")],[83,new no(le.Synth,"Lead Synthesizer")],[84,new no(le.Synth,"Lead Synthesizer")],[85,new no(le.Synth,"Lead Synthesizer")],[86,new no(le.Synth,"Lead Synthesizer")],[87,new no(le.Synth,"Lead Synthesizer")],[88,new no(le.Synth,"Pad Synthesizer")],[89,new no(le.Synth,"Pad Synthesizer")],[90,new no(le.Synth,"Pad Synthesizer")],[91,new no(le.Synth,"Pad Synthesizer")],[92,new no(le.Synth,"Pad Synthesizer")],[93,new no(le.Synth,"Pad Synthesizer")],[94,new no(le.Synth,"Pad Synthesizer")],[95,new no(le.Synth,"Pad Synthesizer")],[96,new no(le.Fx,"Pad Synthesizer")],[97,new no(le.Fx,"Pad Synthesizer")],[98,new no(le.Fx,"Pad Synthesizer")],[99,new no(le.Fx,"Pad Synthesizer")],[100,new no(le.Fx,"Lead Synthesizer")],[101,new no(le.Fx,"Lead Synthesizer")],[102,new no(le.Fx,"Lead Synthesizer")],[103,new no(le.Fx,"Trumpet")],[104,new no(le.ElectricGuitar,"Banjo")],[105,new no(le.Banjo,"Banjo")],[106,new no(le.Ukulele,"Ukulele")],[107,new no(le.Banjo,"Banjo")],[108,new no(le.PitchedIdiophone,"Xylophone")],[109,new no(le.Reed,"Bassoon")],[110,new no(le.Strings,"Violin")],[111,new no(le.Woodwind,"Flute")],[112,new no(le.PitchedIdiophone,"Xylophone")],[113,new no(le.Idiophone,"Celesta")],[114,new no(le.PitchedIdiophone,"Vibraphone")],[115,new no(le.Idiophone,"Xylophone")],[116,new no(le.Membraphone,"Xylophone")],[117,new no(le.Membraphone,"Xylophone")],[118,new no(le.Membraphone,"Xylophone")],[119,new no(le.Idiophone,"Celesta")],[120,new no(le.Fx,"Steel Guitar")],[121,new no(le.Fx,"Recorder")],[122,new no(le.Fx,"Recorder")],[123,new no(le.Fx,"Recorder")],[124,new no(le.Fx,"Recorder")],[125,new no(le.Fx,"Recorder")],[126,new no(le.Fx,"Recorder")],[127,new no(le.Fx,"Timpani")]]),oo.DrumKitProgramInfo=new no(le.PercussionKit,"Drums","drumKit");class ho{constructor(){this._checkValue=ho.CrcInit,this.reset()}static buildCrc32Lookup(){const e=new Uint32Array(256);for(let t=0;t<e.length;t++){let i=t;for(let e=0;e<8;e++)i=1==(1&i)?i>>>1^3988292384:i>>>1;e[t]=i}return e}get value(){return~this._checkValue}update(e,t,i){for(let s=0;s<i;s++)this._checkValue=ho.Crc32Lookup[255&(this._checkValue^e[t+s])]^this._checkValue>>>8}reset(){this._checkValue=ho.CrcInit}}ho.Crc32Lookup=ho.buildCrc32Lookup(),ho.CrcInit=4294967295;class lo{}lo.MAX_WBITS=15,lo.WSIZE=1<<lo.MAX_WBITS,lo.WMASK=lo.WSIZE-1,lo.MIN_MATCH=3,lo.MAX_MATCH=258,lo.DEFAULT_MEM_LEVEL=8,lo.PENDING_BUF_SIZE=1<<lo.DEFAULT_MEM_LEVEL+8,lo.HASH_BITS=lo.DEFAULT_MEM_LEVEL+7,lo.HASH_SIZE=1<<lo.HASH_BITS,lo.HASH_SHIFT=(lo.HASH_BITS+lo.MIN_MATCH-1)/lo.MIN_MATCH,lo.HASH_MASK=lo.HASH_SIZE-1,lo.MIN_LOOKAHEAD=lo.MAX_MATCH+lo.MIN_MATCH+1,lo.MAX_DIST=lo.WSIZE-lo.MIN_LOOKAHEAD;class co{constructor(e,t,i,s){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=i,this.maxLength=s,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(s)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){let e=this.freqs.length,t=new Int32Array(e),i=0,s=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!=e){let r,n=i++;for(;n>0&&this.freqs[t[r=Math.floor((n-1)/2)]]>e;)t[n]=t[r],n=r;t[n]=a,s=a}}for(;i<2;){let e=s<2?++s:0;t[i++]=e}this.numCodes=Math.max(s+1,this.minNumCodes);let a=i,r=new Int32Array(4*i-2),n=new Int32Array(2*i-1),o=a;for(let e=0;e<i;e++){let i=t[e];r[2*e]=i,r[2*e+1]=-1,n[e]=this.freqs[i]<<8,t[e]=e}do{let e=t[0],s=t[--i],a=0,h=1;for(;h<i;)h+1<i&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[s];for(;(h=a)>0&&n[t[a=Math.floor((h-1)/2)]]>l;)t[h]=t[a];t[h]=s;let c=t[0];s=o++,r[2*s]=e,r[2*s+1]=c;let d=Math.min(255&n[e],255&n[c]);for(n[s]=l=n[e]+n[c]-d+1,a=0,h=1;h<i;)h+1<i&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;(h=a)>0&&n[t[a=Math.floor((h-1)/2)]]>l;)t[h]=t[a];t[h]=s}while(i>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);let t=Math.floor(e.length/2),i=Math.floor((t+1)/2),s=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let a=new Int32Array(t);a[t-1]=0;for(let i=t-1;i>=0;i--)if(-1!=e[2*i+1]){let t=a[i]+1;t>this.maxLength&&(t=this.maxLength,s++),a[e[2*i]]=a[e[2*i+1]]=t}else{let t=a[i];this.bitLengthCounts[t-1]++,this.length[e[2*i]]=a[i]}if(0==s)return;let r=this.maxLength-1;do{for(;0==this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,s-=1<<this.maxLength-1-r}while(s>0&&r<this.maxLength-1)}while(s>0);this.bitLengthCounts[this.maxLength-1]+=s,this.bitLengthCounts[this.maxLength-2]-=s;let n=2*i;for(let t=this.maxLength;0!=t;t--){let i=this.bitLengthCounts[t-1];for(;i>0;){let s=2*e[n++];-1==e[s+1]&&(this.length[e[s]]=t,i--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,i,s,a=-1,r=0;for(;r<this.numCodes;){s=1;let n=this.length[r];for(0==n?(t=138,i=3):(t=6,i=3,a!=n&&(e.freqs[n]++,s=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++s>=t)););s<i?e.freqs[a]+=s:0!=a?e.freqs[co.Repeat3To6]++:s<=10?e.freqs[co.Repeat3To10]++:e.freqs[co.Repeat11To138]++}}setStaticCodes(e,t){this.codes=e,this.length=t}buildCodes(){let e=new Int32Array(this.maxLength),t=0;this.codes=new Int16Array(this.freqs.length);for(let i=0;i<this.maxLength;i++)e[i]=t,t+=this.bitLengthCounts[i]<<15-i;for(let t=0;t<this.numCodes;t++){let i=this.length[t];i>0&&(this.codes[t]=uo.bitReverse(e[i-1]),e[i-1]+=1<<16-i)}}writeTree(e){let t,i,s,a=-1,r=0;for(;r<this.numCodes;){s=1;let n=this.length[r];for(0==n?(t=138,i=3):(t=6,i=3,a!=n&&(e.writeSymbol(n),s=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++s>=t)););if(s<i)for(;s-- >0;)e.writeSymbol(a);else 0!=a?(e.writeSymbol(co.Repeat3To6),this.huffman.pending.writeBits(s-3,2)):s<=10?(e.writeSymbol(co.Repeat3To10),this.huffman.pending.writeBits(s-3,3)):(e.writeSymbol(co.Repeat11To138),this.huffman.pending.writeBits(s-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}co.Repeat3To6=16,co.Repeat3To10=17,co.Repeat11To138=18;class uo{constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new co(this,uo.LITERAL_NUM,257,15),this.distTree=new co(this,uo.DIST_NUM,1,15),this.blTree=new co(this,uo.BITLEN_NUM,4,7),this.d_buf=new Int16Array(uo.BUFSIZE),this.l_buf=new Uint8Array(uo.BUFSIZE)}static staticInit(){uo.staticLCodes=new Int16Array(uo.LITERAL_NUM),uo.staticLLength=new Uint8Array(uo.LITERAL_NUM);let e=0;for(;e<144;)uo.staticLCodes[e]=uo.bitReverse(48+e<<8),uo.staticLLength[e++]=8;for(;e<256;)uo.staticLCodes[e]=uo.bitReverse(256+e<<7),uo.staticLLength[e++]=9;for(;e<280;)uo.staticLCodes[e]=uo.bitReverse(-256+e<<9),uo.staticLLength[e++]=7;for(;e<uo.LITERAL_NUM;)uo.staticLCodes[e]=uo.bitReverse(-88+e<<8),uo.staticLLength[e++]=8;for(uo.staticDCodes=new Int16Array(uo.DIST_NUM),uo.staticDLength=new Uint8Array(uo.DIST_NUM),e=0;e<uo.DIST_NUM;e++)uo.staticDCodes[e]=uo.bitReverse(e<<11),uo.staticDLength[e]=5}static bitReverse(e){return uo.bit4Reverse[15&e]<<12|uo.bit4Reverse[e>>4&15]<<8|uo.bit4Reverse[e>>8&15]<<4|uo.bit4Reverse[e>>12]}isFull(){return this.last_lit>=uo.BUFSIZE}reset(){this.last_lit=0,this.extra_bits=0,this.literalTree.reset(),this.distTree.reset(),this.blTree.reset()}flushStoredBlock(e,t,i,s){this.pending.writeBits((uo.STORED_BLOCK<<1)+(s?1:0),3),this.pending.alignToByte(),this.pending.writeShort(i),this.pending.writeShort(~i),this.pending.writeBlock(e,t,i),this.reset()}flushBlock(e,t,i,s){this.literalTree.freqs[uo.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[uo.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<uo.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*uo.staticLLength[e];for(let e=0;e<uo.DIST_NUM;e++)n+=this.distTree.freqs[e]*uo.staticDLength[e];r>=n&&(r=n),t>=0&&i+4<r>>3?this.flushStoredBlock(e,t,i,s):r==n?(this.pending.writeBits((uo.STATIC_TREES<<1)+(s?1:0),3),this.literalTree.setStaticCodes(uo.staticLCodes,uo.staticLLength),this.distTree.setStaticCodes(uo.staticDCodes,uo.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((uo.DYN_TREES<<1)+(s?1:0),3),this.sendAllTrees(a),this.compressBlock(),this.reset())}sendAllTrees(e){this.blTree.buildCodes(),this.literalTree.buildCodes(),this.distTree.buildCodes(),this.pending.writeBits(this.literalTree.numCodes-257,5),this.pending.writeBits(this.distTree.numCodes-1,5),this.pending.writeBits(e-4,4);for(let t=0;t<e;t++)this.pending.writeBits(this.blTree.length[uo.BL_ORDER[t]],3);this.literalTree.writeTree(this.blTree),this.distTree.writeTree(this.blTree)}compressBlock(){for(let e=0;e<this.last_lit;e++){let t=255&this.l_buf[e],i=this.d_buf[e];if(0!=i--){let e=uo.Lcode(t);this.literalTree.writeSymbol(e);let s=Math.floor((e-261)/4);s>0&&s<=5&&this.pending.writeBits(t&(1<<s)-1,s);let a=uo.Dcode(i);this.distTree.writeSymbol(a),s=Math.floor(a/2)-1,s>0&&this.pending.writeBits(i&(1<<s)-1,s)}else this.literalTree.writeSymbol(t)}this.literalTree.writeSymbol(uo.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let i=uo.Lcode(t-3);this.literalTree.freqs[i]++,i>=265&&i<285&&(this.extra_bits+=Math.floor((i-261)/4));let s=uo.Dcode(e-1);return this.distTree.freqs[s]++,s>=4&&(this.extra_bits+=Math.floor(s/2)-1),this.isFull()}tallyLit(e){return this.d_buf[this.last_lit]=0,this.l_buf[this.last_lit++]=e,this.literalTree.freqs[e]++,this.isFull()}static Lcode(e){if(255==e)return 285;let t=257;for(;e>=8;)t+=4,e>>=1;return t+e}static Dcode(e){let t=0;for(;e>=4;)t+=2,e>>=1;return t+e}}uo.BUFSIZE=1<<lo.DEFAULT_MEM_LEVEL+6,uo.LITERAL_NUM=286,uo.STORED_BLOCK=0,uo.STATIC_TREES=1,uo.DYN_TREES=2,uo.DIST_NUM=30,uo.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],uo.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),uo.BITLEN_NUM=19,uo.EOF_SYMBOL=256,uo.staticInit();class po{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 uo(e),this.inputCrc=new ho,this.window=new Uint8Array(2*lo.WSIZE),this.head=new Int16Array(lo.HASH_SIZE),this.prev=new Int16Array(lo.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=lo.MIN_MATCH-1;for(let e=0;e<lo.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<lo.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<lo.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd==this.inputOff}setInput(e,t,i){let s=t+i;this.inputBuf=e,this.inputOff=t,this.inputEnd=s}deflate(e,t){let i;do{this.fillWindow();let s=e&&this.inputOff==this.inputEnd;i=this.deflateSlow(s,t)}while(this.pending.isFlushed&&i);return i}deflateSlow(e,t){if(this.lookahead<lo.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=lo.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*lo.WSIZE-lo.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,i=this.matchLen;if(this.lookahead>=lo.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=lo.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==lo.MIN_MATCH&&this.strstart-this.matchStart>po.TooFar&&(this.matchLen=lo.MIN_MATCH-1)}if(i>=lo.MIN_MATCH&&this.matchLen<=i){this.huffman.tallyDist(this.strstart-1-e,i),i-=2;do{this.strstart++,this.lookahead--,this.lookahead>=lo.MIN_MATCH&&this.insertString()}while(--i>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=lo.MIN_MATCH-1}else this.prevAvailable&&this.huffman.tallyLit(255&this.window[this.strstart-1]),this.prevAvailable=!0,this.strstart++,this.lookahead--;if(this.huffman.isFull()){let e=this.strstart-this.blockStart;this.prevAvailable&&e--;let i=t&&0==this.lookahead&&!this.prevAvailable;return this.huffman.flushBlock(this.window,this.blockStart,e,i),this.blockStart+=e,!i}}return!0}findLongestMatch(e){let t,i=this.strstart,s=i+Math.min(lo.MAX_MATCH,this.lookahead)-1,a=Math.max(i-lo.MAX_DIST,0),r=this.window,n=this.prev,o=this.maxChain,h=Math.min(this.niceLength,this.lookahead);if(this.matchLen=Math.max(this.matchLen,lo.MIN_MATCH-1),i+this.matchLen>s)return!1;let l=r[i+this.matchLen-1],c=r[i+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,i=this.strstart,r[t+this.matchLen]==c&&r[t+this.matchLen-1]==l&&r[t]==r[i]&&r[++t]==r[++i]){switch((s-i)%8){case 1:if(r[++i]==r[++t])break;break;case 2:if(r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 3:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 4:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 5:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 6:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 7:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break}if(r[i]==r[t])do{if(i==s){++i,++t;break}}while(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]);if(i-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=i-this.strstart,this.matchLen>=h)break;l=r[i-1],c=r[i]}}}while((e=65535&n[e&lo.WMASK])>a&&0!=--o);return this.matchLen>=lo.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<lo.HASH_SHIFT^this.window[this.strstart+(lo.MIN_MATCH-1)])&lo.HASH_MASK;return this.prev[this.strstart&lo.WMASK]=e=this.head[t],this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=lo.WSIZE+lo.MAX_DIST&&this.slideWindow(),this.lookahead<lo.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*lo.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>=lo.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(lo.WSIZE,lo.WSIZE+lo.WSIZE),0),this.matchStart-=lo.WSIZE,this.strstart-=lo.WSIZE,this.blockStart-=lo.WSIZE;for(let e=0;e<lo.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=lo.WSIZE?t-lo.WSIZE:0}for(let e=0;e<lo.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=lo.WSIZE?t-lo.WSIZE:0}}}po.TooFar=4096;class go{constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}get isFlushed(){return 0===this._end}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,i){this._buffer.set(e.subarray(t,t+i),this._end),this._end+=i}flush(e,t,i){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),i>this._end-this._start?(i=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+i),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+i),t),this._start+=i),i}writeBits(e,t){this._bits|=e<<this.bitCount,this.bitCount+=t,this.bitCount>=16&&(this._buffer[this._end++]=255&this._bits,this._buffer[this._end++]=this._bits>>8&255,this._bits>>=16,this.bitCount-=16)}alignToByte(){this.bitCount>0&&(this._buffer[this._end++]=255&this._bits,this.bitCount>8&&(this._buffer[this._end++]=this._bits>>8&255)),this._bits=0,this.bitCount=0}}class fo{constructor(){this._state=0,this._pending=new go(lo.PENDING_BUF_SIZE),this._engine=new po(this._pending),this.reset()}get inputCrc(){return this._engine.inputCrc.value}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==fo.FinishedState&&this._pending.isFlushed}reset(){this._state=fo.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,i){this._engine.setInput(e,t,i)}deflate(e,t,i){let s=i;for(;;){let a=this._pending.flush(e,t,i);if(t+=a,0==(i-=a)||this._state==fo.FinishedState)break;if(!this._engine.deflate(0!=(this._state&fo.IsFlushing),0!=(this._state&fo.IsFinishing)))switch(this._state){case fo.BusyState:return s-i;case fo.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=fo.BusyState;break;case fo.FinishingState:this._pending.alignToByte(),this._state=fo.FinishedState}}return s-i}finish(){this._state|=fo.IsFlushing|fo.IsFinishing}}fo.IsFlushing=4,fo.IsFinishing=8,fo.BusyState=16,fo.FlushingState=20,fo.FinishingState=28,fo.FinishedState=30;class mo{constructor(e,t,i,s,a){this.entry=e,this.crc32=t,this.localHeaderOffset=i,this.compressionMode=s,this.compressedSize=a}}class yo{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new fo,this._data=e}writeEntry(e){const t=Et.CompressionMethodDeflate,i=ot.empty(),s=this.compress(i,e.data,t),a=i.toArray(),r=new mo(e,s,this._data.bytesWritten,t,i.length);this._centralDirectoryHeaders.push(r),st.writeInt32LE(this._data,Et.LocalFileHeaderSignature),st.writeUInt16LE(this._data,10),st.writeUInt16LE(this._data,2048),st.writeUInt16LE(this._data,t),st.writeInt16LE(this._data,0),st.writeInt16LE(this._data,0),st.writeInt32LE(this._data,s),st.writeInt32LE(this._data,a.length),st.writeInt32LE(this._data,e.data.length),st.writeInt16LE(this._data,e.fullName.length),st.writeInt16LE(this._data,0);const n=st.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,i){if(i!=Et.CompressionMethodDeflate){const i=new ho;return i.update(t,0,t.length),e.write(t,0,t.length),i.value}{let i=new Uint8Array(512);for(this._deflater.reset(),this._deflater.setInput(t,0,t.length);!this._deflater.isNeedingInput;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}for(this._deflater.finish();!this._deflater.isFinished;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}return this._deflater.inputCrc}}end(){const e=this._data.bytesWritten;for(const e of this._centralDirectoryHeaders)this.writeCentralDirectoryHeader(e);const t=this._data.bytesWritten;this.writeEndOfCentralDirectoryRecord(e,t)}writeEndOfCentralDirectoryRecord(e,t){st.writeInt32LE(this._data,Et.EndOfCentralDirSignature),st.writeInt16LE(this._data,0),st.writeInt16LE(this._data,0),st.writeInt16LE(this._data,this._centralDirectoryHeaders.length),st.writeInt16LE(this._data,this._centralDirectoryHeaders.length),st.writeInt32LE(this._data,t-e),st.writeInt32LE(this._data,e),st.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){st.writeInt32LE(this._data,Et.CentralFileHeaderSignature),st.writeUInt16LE(this._data,10),st.writeUInt16LE(this._data,10),st.writeUInt16LE(this._data,2048),st.writeUInt16LE(this._data,e.compressionMode),st.writeInt16LE(this._data,0),st.writeInt16LE(this._data,0),st.writeInt32LE(this._data,e.crc32),st.writeInt32LE(this._data,e.compressedSize),st.writeInt32LE(this._data,e.entry.data.length),st.writeInt16LE(this._data,e.entry.fullName.length),st.writeInt16LE(this._data,0),st.writeInt16LE(this._data,0),st.writeInt16LE(this._data,0),st.writeInt16LE(this._data,0),st.writeInt32LE(this._data,0),st.writeInt32LE(this._data,e.localHeaderOffset);const t=st.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}const bo=ao,So={ScoreImporter:Te,ScoreLoader:Rs,UnsupportedFormatError:ke},wo={ScoreExporter:ro,Gp7Exporter:class extends ro{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){Fe.debug(this.name,"Writing data entries");const t=(new oo).writeXml(e),i=lt.writeForScore(e),s=_t.writeForScore(e);Fe.debug(this.name,"Writing ZIP entries");let a=new yo(this.data);a.writeEntry(new Et("VERSION",st.stringToBytes("7.0"))),a.writeEntry(new Et("Content/",new Uint8Array(0))),a.writeEntry(new Et("Content/BinaryStylesheet",i)),a.writeEntry(new Et("Content/PartConfiguration",s)),a.writeEntry(new Et("Content/score.gpif",st.stringToBytes(t))),a.end()}}},_o={BeatTickLookup:Ss,MasterBarTickLookup:_s,MidiTickLookup:Ts,MidiTickLookupFindBeatResult:Bs,MidiFile:Ti,ControllerType:te,MetaDataEvent:ki,MetaEvent:Gt,MetaEventType:Y,MetaNumberEvent:vi,MidiEvent:Ot,MidiEventType:X,Midi20PerNotePitchBendEvent:Vi,SystemCommonEvent:Vt,SystemCommonType:q,SystemExclusiveEvent:Ht,MidiFileGenerator:Ns,AlphaSynthMidiFileHandler:bs},Bo={AccentuationType:c,AccidentalType:se,AutomationType:d,Automation:ve,Bar:Ne,Beat:He,BendPoint:Pe,BendStyle:f,BendType:m,BrushType:y,Chord:We,Clef:u,Color:me,CrescendoType:b,Duration:S,DynamicValue:w,FermataType:V,Fermata:ct,Fingers:i,FontStyle:o,Font:we,GraceType:_,HarmonicType:B,InstrumentArticulation:Le,JsonConverter:as,KeySignature:D,KeySignatureType:A,Lyrics:Ue,MasterBar:ze,MusicFontSymbol:E,Note:Ie,NoteAccidentalMode:T,Ottavia:p,PickStroke:P,PlaybackInformation:Qe,RenderStylesheet:Xe,RepeatGroup:Ye,Score:qe,Section:Je,SimileMark:g,SlideInType:k,SlideOutType:v,Staff:Ke,Track:$e,TripletFeel:R,Tuning:je,TupletGroup:De,VibratoType:N,Voice:Ze,WhammyType:L},To={ScoreRenderer:fs,RenderFinishedEventArgs:hs,BarBounds:ls,BeatBounds:cs,Bounds:ht,BoundsLookup:gs,MasterBarBounds:ds,NoteBounds:us,StaveGroupBounds:ps},ko={AlphaSynth:Bi,PlaybackRange:xs,PlayerState:Q,PlayerStateChangedEventArgs:qt,PositionChangedEventArgs:Jt,AlphaSynthWebWorkerApi:Us};e.AlphaTabApi=qs,e.AlphaTabError=ce,e.CoreSettings=io,e.DisplaySettings=Be,e.FileLoadError=As,e.FormatError=de,e.ImporterSettings=Ni,e.Logger=Fe,e.NotationSettings=pe,e.PlayerSettings=Ei,e.ProgressEventArgs=so,e.RenderingResources=_e,e.ResizeEventArgs=Is,e.Settings=Gi,e.VibratoPlaybackSettings=xi,e.exporter=wo,e.importer=So,e.meta=bo,e.midi=_o,e.model=Bo,e.rendering=To,e.synth=ko,Object.defineProperty(e,"__esModule",{value:!0})}));
17
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).alphaTab={})}(this,(function(e){"use strict";var t,i,s,a,r,n,o,h,l,d,c,u,p,g,f,m,y,b,S,_,w,B,T,k,v,N,x,P,E,C,F,L,M,D,I,R,A,O,G,H,V,W,z,U,X,Y,q,J,j,Q,$,K,Z,ee,te,ie;e.LayoutMode=void 0,(t=e.LayoutMode||(e.LayoutMode={}))[t.Page=0]="Page",t[t.Horizontal=1]="Horizontal",e.StaveProfile=void 0,(i=e.StaveProfile||(e.StaveProfile={}))[i.Default=0]="Default",i[i.ScoreTab=1]="ScoreTab",i[i.Score=2]="Score",i[i.Tab=3]="Tab",i[i.TabMixed=4]="TabMixed";class se{static getValue(e){return se._values||(se._values=new Map),e=e.toLowerCase().split(" ").join(""),se._values.has(e)?se._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}}se._values=new Map([["acousticgrandpiano",0],["brightacousticpiano",1],["electricgrandpiano",2],["honkytonkpiano",3],["electricpiano1",4],["electricpiano2",5],["harpsichord",6],["clavinet",7],["celesta",8],["glockenspiel",9],["musicbox",10],["vibraphone",11],["marimba",12],["xylophone",13],["tubularbells",14],["dulcimer",15],["drawbarorgan",16],["percussiveorgan",17],["rockorgan",18],["churchorgan",19],["reedorgan",20],["accordion",21],["harmonica",22],["tangoaccordion",23],["acousticguitarnylon",24],["acousticguitarsteel",25],["electricguitarjazz",26],["electricguitarclean",27],["electricguitarmuted",28],["overdrivenguitar",29],["distortionguitar",30],["guitarharmonics",31],["acousticbass",32],["electricbassfinger",33],["electricbasspick",34],["fretlessbass",35],["slapbass1",36],["slapbass2",37],["synthbass1",38],["synthbass2",39],["violin",40],["viola",41],["cello",42],["contrabass",43],["tremolostrings",44],["pizzicatostrings",45],["orchestralharp",46],["timpani",47],["stringensemble1",48],["stringensemble2",49],["synthstrings1",50],["synthstrings2",51],["choiraahs",52],["voiceoohs",53],["synthvoice",54],["orchestrahit",55],["trumpet",56],["trombone",57],["tuba",58],["mutedtrumpet",59],["frenchhorn",60],["brasssection",61],["synthbrass1",62],["synthbrass2",63],["sopranosax",64],["altosax",65],["tenorsax",66],["baritonesax",67],["oboe",68],["englishhorn",69],["bassoon",70],["clarinet",71],["piccolo",72],["flute",73],["recorder",74],["panflute",75],["blownbottle",76],["shakuhachi",77],["whistle",78],["ocarina",79],["lead1square",80],["lead2sawtooth",81],["lead3calliope",82],["lead4chiff",83],["lead5charang",84],["lead6voice",85],["lead7fifths",86],["lead8bassandlead",87],["pad1newage",88],["pad2warm",89],["pad3polysynth",90],["pad4choir",91],["pad5bowed",92],["pad6metallic",93],["pad7halo",94],["pad8sweep",95],["fx1rain",96],["fx2soundtrack",97],["fx3crystal",98],["fx4atmosphere",99],["fx5brightness",100],["fx6goblins",101],["fx7echoes",102],["fx8scifi",103],["sitar",104],["banjo",105],["shamisen",106],["koto",107],["kalimba",108],["bagpipe",109],["fiddle",110],["shanai",111],["tinklebell",112],["agogo",113],["steeldrums",114],["woodblock",115],["taikodrum",116],["melodictom",117],["synthdrum",118],["reversecymbal",119],["guitarfretnoise",120],["breathnoise",121],["seashore",122],["birdtweet",123],["telephonering",124],["helicopter",125],["applause",126],["gunshot",127]]);class ae{init(e,t){this.data=e,this.settings=t}}e.AlphaTabErrorType=void 0,(s=e.AlphaTabErrorType||(e.AlphaTabErrorType={}))[s.General=0]="General",s[s.Format=1]="Format",s[s.AlphaTex=2]="AlphaTex";class re extends Error{constructor(e,t="",i){super(null!=t?t:""),this.type=e,this.inner=null!=i?i:null,Object.setPrototypeOf(this,re.prototype)}}class ne extends re{constructor(t=null,i=null){super(e.AlphaTabErrorType.Format,null!=t?t:"Unsupported format"),this.inner=i,Object.setPrototypeOf(this,ne.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(a||(a={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(r||(r={}));class oe{constructor(){this.isLinear=!1,this.type=r.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,i,s){(s<1||s>5)&&(s=2);let a=new Float32Array([1,.5,1,1.5,2,3]),n=new oe;return n.type=r.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=i*a[s],n}static buildInstrumentAutomation(e,t,i){let s=new oe;return s.type=r.Instrument,s.isLinear=e,s.ratioPosition=t,s.value=i,s}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(n||(n={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(o||(o={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(h||(h={}));class he{constructor(){this.id=he._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}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1;for(let i=0,s=this.voices.length;i<s;i++){let s=this.voices[i];s.finish(e,t),i>0&&!s.isEmpty&&(this.isMultiVoice=!0)}}calculateDuration(){let e=0;for(let t of this.voices){let i=t.calculateDuration();i>e&&(e=i)}return e}}he._globalBarId=0;class le{static ticksToMillis(e,t){return e*(6e4/(t*le.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*le.QuarterTime))|0}static toTicks(e){return le.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),le.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,i){return e*i/t|0}static removeTuplet(e,t,i){return e*t/i|0}static dynamicToVelocity(e){return le.MinVelocity+e*le.VelocityIncrement}}le.QuarterTime=960,le.MinVelocity=15,le.VelocityIncrement=16;class de{constructor(e=0,t=0){this.offset=e,this.value=t}}de.MaxPosition=60,de.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(l||(l={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(d||(d={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(c||(c={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(u||(u={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(p||(p={})),function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF"}(g||(g={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(f||(f={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(m||(m={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(y||(y={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(b||(b={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(_||(_={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(w||(w={})),e.TabRhythmMode=void 0,(B=e.TabRhythmMode||(e.TabRhythmMode={}))[B.Hidden=0]="Hidden",B[B.ShowWithBeams=1]="ShowWithBeams",B[B.ShowWithBars=2]="ShowWithBars",e.FingeringMode=void 0,(T=e.FingeringMode||(e.FingeringMode={}))[T.ScoreDefault=0]="ScoreDefault",T[T.ScoreForcePiano=1]="ScoreForcePiano",T[T.SingleNoteEffectBand=2]="SingleNoteEffectBand",T[T.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano",e.NotationMode=void 0,(k=e.NotationMode||(e.NotationMode={}))[k.GuitarPro=0]="GuitarPro",k[k.SongBook=1]="SongBook",function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap"}(v||(v={}));class ce{constructor(){this.notationMode=e.NotationMode.GuitarPro,this.fingeringMode=e.FingeringMode.ScoreDefault,this.elements=new Map,this.rhythmMode=e.TabRhythmMode.Hidden,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!ce.defaultElements.has(e)||ce.defaultElements.get(e)}}ce.defaultElements=new Map([[v.ZerosOnDiveWhammys,!1]]);class ue{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}e.LogLevel=void 0,(N=e.LogLevel||(e.LogLevel={}))[N.None=0]="None",N[N.Debug=1]="Debug",N[N.Info=2]="Info",N[N.Warning=3]="Warning",N[N.Error=4]="Error";class pe{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...i){console.debug(pe.format(e,t),...i)}warning(e,t,...i){console.warn(pe.format(e,t),...i)}info(e,t,...i){console.info(pe.format(e,t),...i)}error(e,t,...i){console.error(pe.format(e,t),...i)}}pe.logLevel=e.LogLevel.Info;class ge{static shouldLog(t){return ge.logLevel!==e.LogLevel.None&&t>=ge.logLevel}static debug(t,i,...s){ge.shouldLog(e.LogLevel.Debug)&&ge.log.debug(t,i,...s)}static warning(t,i,...s){ge.shouldLog(e.LogLevel.Warning)&&ge.log.warning(t,i,...s)}static info(t,i,...s){ge.shouldLog(e.LogLevel.Info)&&ge.log.info(t,i,...s)}static error(t,i,...s){ge.shouldLog(e.LogLevel.Error)&&ge.log.error(t,i,...s)}}ge.logLevel=e.LogLevel.Info,ge.log=new pe;class fe{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class me{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let i=0;i<t.tracks.length;i++){if(i<e.notation.displayTranspositionPitches.length)for(let s of t.tracks[i].staves)s.displayTranspositionPitch=-e.notation.displayTranspositionPitches[i];if(i<e.notation.transpositionPitches.length)for(let s of t.tracks[i].staves)s.transpositionPitch=-e.notation.transpositionPitches[i]}}static fingerToString(t,i,s,a){if(t.notation.fingeringMode===e.FingeringMode.ScoreForcePiano||t.notation.fingeringMode===e.FingeringMode.SingleNoteEffectBandForcePiano||se.isPiano(i.voice.bar.staff.track.playbackInfo.program))switch(s){case m.Unknown:case m.NoOrDead:return null;case m.Thumb:return"1";case m.IndexFinger:return"2";case m.MiddleFinger:return"3";case m.AnnularFinger:return"4";case m.LittleFinger:return"5";default:return null}if(a)switch(s){case m.Unknown:case m.NoOrDead:return"0";case m.Thumb:return"T";case m.IndexFinger:return"1";case m.MiddleFinger:return"2";case m.AnnularFinger:return"3";case m.LittleFinger:return"4";default:return null}switch(s){case m.Unknown:case m.NoOrDead:return null;case m.Thumb:return"p";case m.IndexFinger:return"i";case m.MiddleFinger:return"m";case m.AnnularFinger:return"a";case m.LittleFinger:return"c";default:return null}}static isTuning(e){return!!me.parseTuning(e)}static parseTuning(e){let t="",i="";for(let s=0;s<e.length;s++){let a=e.charCodeAt(s);if(a>=48&&a<=57){if(!t)return null;i+=String.fromCharCode(a)}else{if(!(a>=65&&a<=90||a>=97&&a<=122||35===a))return null;t+=String.fromCharCode(a)}}if(!i||!t)return null;let s=new fe;return s.octave=parseInt(i)+1,s.note=t.toLowerCase(),s.noteValue=me.getToneForText(s.note),s}static getTuningForText(e){let t=me.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){let t=0;switch(e.toLowerCase()){case"c":t=0;break;case"c#":case"db":t=1;break;case"d":t=2;break;case"d#":case"eb":t=3;break;case"e":t=4;break;case"f":t=5;break;case"f#":case"gb":t=6;break;case"g":t=7;break;case"g#":case"ab":t=8;break;case"a":t=9;break;case"a#":case"bb":t=10;break;case"b":t=11;break;default:return 0}return t}static newGuid(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let i="";do{i=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+i,e>>=4}while(e>0);for(;i.length<t;)i="0"+i;return i}}!function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(x||(x={})),function(e){e[e.None=-1]="None",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(P||(P={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(E||(E={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(C||(C={}));class ye{constructor(e="",t=0,i=0,s=P.None,a=P.None,r=P.None,n=P.None,o=C.Middle){this.elementType=e,this.outputMidiNumber=i,this.staffLine=t,this.noteHeadDefault=s,this.noteHeadHalf=a!==P.None?a:s,this.noteHeadWhole=r!==P.None?r:s,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case p.Whole:return this.noteHeadWhole;case p.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class be{static articulationFromElementVariation(e,t){return e<be.gp6ElementAndVariationToArticulation.length?(t>=be.gp6ElementAndVariationToArticulation.length&&(t=0),be.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation,i=e.beat.voice.bar.staff.track.percussionArticulations;return t<i.length?i[t]:be.getArticulationByValue(t)}static getElementAndVariation(e){const t=be.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<be.gp6ElementAndVariationToArticulation.length;e++){const i=be.gp6ElementAndVariationToArticulation[e];for(let s=0;s<i.length;s++){const a=be.getArticulationByValue(i[s]);if((null==a?void 0:a.outputMidiNumber)===t.outputMidiNumber)return[e,s]}}return[-1,-1]}static getArticulationByValue(e){return be.instrumentArticulations.has(e)?be.instrumentArticulations.get(e):null}}be.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]],be.instrumentArticulations=new Map([[38,new ye("snare",3,38,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[37,new ye("snare",3,37,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[91,new ye("snare",3,38,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[42,new ye("hiHat",-1,42,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[92,new ye("hiHat",-1,46,P.NoteheadCircleSlash,P.NoteheadCircleSlash,P.NoteheadCircleSlash)],[46,new ye("hiHat",-1,46,P.NoteheadCircleX,P.NoteheadCircleX,P.NoteheadCircleX)],[44,new ye("hiHat",9,44,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[35,new ye("kickDrum",8,35,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[36,new ye("kickDrum",7,36,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[50,new ye("tom",1,50,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[48,new ye("tom",2,48,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[47,new ye("tom",4,47,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[45,new ye("tom",5,45,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[43,new ye("tom",6,43,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[93,new ye("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.PictEdgeOfCymbal,C.Bottom)],[51,new ye("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[53,new ye("ride",0,53,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[94,new ye("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Top)],[55,new ye("splash",-2,55,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[95,new ye("splash",-2,55,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Bottom)],[52,new ye("china",-3,52,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat)],[96,new ye("china",-3,52,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat)],[49,new ye("crash",-2,49,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX)],[97,new ye("crash",-2,49,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX,P.ArticStaccatoAbove,C.Bottom)],[57,new ye("crash",-1,57,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX)],[98,new ye("crash",-1,57,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX,P.ArticStaccatoAbove,C.Bottom)],[99,new ye("cowbell",1,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[100,new ye("cowbell",1,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[56,new ye("cowbell",0,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[101,new ye("cowbell",0,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[102,new ye("cowbell",-1,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[103,new ye("cowbell",-1,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[77,new ye("woodblock",-9,77,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[76,new ye("woodblock",-10,76,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[60,new ye("bongo",-4,60,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[104,new ye("bongo",-5,60,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[105,new ye("bongo",-6,60,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[61,new ye("bongo",-7,61,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[106,new ye("bongo",-8,61,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[107,new ye("bongo",-16,61,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[66,new ye("timbale",10,66,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[65,new ye("timbale",9,65,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[68,new ye("agogo",12,68,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[67,new ye("agogo",11,67,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[64,new ye("conga",17,64,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[108,new ye("conga",16,64,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[109,new ye("conga",15,64,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[63,new ye("conga",14,63,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[110,new ye("conga",13,63,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[62,new ye("conga",19,62,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[72,new ye("whistle",-11,72,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[71,new ye("whistle",-17,71,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[73,new ye("guiro",38,73,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[74,new ye("guiro",37,74,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[86,new ye("surdo",36,86,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[87,new ye("surdo",35,87,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadParenthesis,C.Middle)],[54,new ye("tambourine",3,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[111,new ye("tambourine",2,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.StringsUpBow,C.Bottom)],[112,new ye("tambourine",1,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.StringsDownBow,C.Bottom)],[113,new ye("tambourine",-7,54,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[79,new ye("cuica",30,79,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[78,new ye("cuica",29,78,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[58,new ye("vibraslap",28,58,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[81,new ye("triangle",27,81,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[80,new ye("triangle",26,80,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadParenthesis,C.Middle)],[114,new ye("grancassa",25,43,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[115,new ye("piatti",18,49,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[116,new ye("piatti",24,49,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[69,new ye("cabasa",23,69,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[117,new ye("cabasa",22,69,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[85,new ye("castanets",21,85,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[75,new ye("claves",20,75,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[70,new ye("maraca",-12,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[118,new ye("maraca",-13,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[119,new ye("maraca",-14,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[120,new ye("maraca",-15,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[82,new ye("shaker",-23,54,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[122,new ye("shaker",-24,54,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[84,new ye("bellTree",-18,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[123,new ye("bellTree",-19,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[83,new ye("jingleBell",-20,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[124,new ye("unpitched",-21,62,P.NoteheadNull,P.NoteheadNull,P.NoteheadNull,P.GuitarGolpe,C.Top)],[125,new ye("unpitched",-22,62,P.NoteheadNull,P.NoteheadNull,P.NoteheadNull,P.GuitarGolpe,C.Bottom)],[39,new ye("handClap",3,39,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[40,new ye("snare",3,40,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[31,new ye("snare",3,40,P.NoteheadSlashedBlack2,P.NoteheadSlashedBlack2,P.NoteheadSlashedBlack2)],[41,new ye("tom",5,41,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[59,new ye("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.PictEdgeOfCymbal,C.Bottom)],[126,new ye("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[127,new ye("ride",2,59,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[29,new ye("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Top)],[30,new ye("crash",-3,49,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[33,new ye("snare",3,37,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[34,new ye("snare",3,38,P.NoteheadBlack,P.NoteheadBlack,P.NoteheadBlack)]]);class Se{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class _e{constructor(){this.id=_e.GlobalNoteId++,this.index=0,this.accentuated=a.None,this.bendType=d.None,this.bendStyle=l.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=[],this.maxBendPoint=null,this.fret=-1,this.string=-1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=y.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=S.None,this.slideOutType=_.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=w.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=m.Unknown,this.rightHandFinger=m.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=p.ThirtySecond,this.durationPercent=1,this.accidentalMode=b.Default,this.dynamics=g.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return this.bendType!==d.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?be.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?be.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==y.None}get isTieOrigin(){return null!==this.tieDestination}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+_e.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){let e=this.realValueWithoutHarmonic;return this.isStringed&&(this.harmonicType===y.Natural?e=this.harmonicPitch+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:e+=this.harmonicPitch),e}get realValueWithoutHarmonic(){return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:this.isPiano?12*this.octave+this.tone-this.beat.voice.bar.staff.transpositionPitch:0}get harmonicPitch(){if(this.harmonicType===y.None||!this.isStringed)return 0;let e=this.harmonicValue;return me.isAlmostEqualTo(e,2.4)?36:me.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==y.Natural&&this.harmonicType!==y.None&&(e-=this.harmonicPitch),this.beat.ottava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){this.bendPoints.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===d.None&&(this.bendType=d.Custom)}finish(t,i=null){let s=new ue((()=>_e.nextNoteOnSameLine(this))),a=t&&t.notation.notationMode===e.NotationMode.SongBook;if(this.isTieDestination&&(this.chain(i),a&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,a&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(s.value&&s.value.isPalmMute?this.palmMuteDestination=s.value:this.palmMuteDestination=this),this.isHammerPullOrigin){let e=_e.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case _.Shift:case _.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=_.None}let r=null;this.isHammerPullOrigin&&this.hammerPullDestination?r=this.hammerPullDestination:this.slideOutType===_.Legato&&this.slideTarget&&(r=this.slideTarget),r&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===x.None?(this.effectSlurOrigin.effectSlurDestination=r,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=r,this.effectSlurDestination.effectSlurOrigin=this));const n=this.bendPoints;if(n.length>0&&this.bendType===d.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===n.length){let t=n[0],i=n[1],s=n[2],a=n[3];i.value===s.value?a.value>t.value?i.value>a.value?this.bendType=d.BendRelease:!e&&t.value>0?(this.bendType=d.PrebendBend,n.splice(2,1),n.splice(1,1)):(this.bendType=d.Bend,n.splice(2,1),n.splice(1,1)):a.value<t.value?e?(this.bendType=d.Release,n.splice(2,1),n.splice(1,1)):(this.bendType=d.PrebendRelease,n.splice(2,1),n.splice(1,1)):i.value>t.value?this.bendType=d.BendRelease:t.value>0&&!e?(this.bendType=d.Prebend,n.splice(2,1),n.splice(1,1)):(this.bendType=d.Hold,n.splice(2,1),n.splice(1,1)):ge.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===n.length){let t=n[0],i=n[1];i.value>t.value?!e&&t.value>0?this.bendType=d.PrebendBend:this.bendType=d.Bend:i.value<t.value?this.bendType=e?d.Release:d.PrebendRelease:this.bendType=d.Hold}}else 0===n.length&&(this.bendType=d.None);this.initialBendValue>0&&(this.accidentalMode=b.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+_e.MaxOffsetForSameLineSearch;){let i=t.getNoteOnString(e.string);if(i)return i;t=t.nextBeat}return null}static findHammerPullDestination(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+_e.MaxOffsetForSameLineSearch;){let i=t.getNoteOnString(e.string);if(i)return i;for(let s=e.string;s>0;s--)if(i=t.getNoteOnString(s),i){if(i.isLeftHandTapped)return i;break}for(let s=e.string;s<=e.beat.voice.bar.staff.tuning.length;s++)if(i=t.getNoteOnString(s),i){if(i.isLeftHandTapped)return i;break}t=t.nextBeat}return null}static findTieOrigin(e){let t=e.beat.previousBeat;for(;t&&t.voice.bar.index>=e.beat.voice.bar.index-_e.MaxOffsetForSameLineSearch;){if(e.isStringed){let i=t.getNoteOnString(e.string);if(i)return i}else if(-1===e.octave&&-1===e.tone){if(e.index<t.notes.length)return t.notes[e.index]}else{let i=t.getNoteWithRealValue(e.realValue);if(i)return i}t=t.previousBeat}return null}chain(e=null){if(null!==e)if(null!==this._noteIdBag){let t;e.has(_e.NoteIdLookupKey)?t=e.get(_e.NoteIdLookupKey):(t=new Map,e.set(_e.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId||t.set(this.id,this),-1!==this._noteIdBag.hammerPullOriginNoteId&&(this.hammerPullOrigin=t.get(this._noteIdBag.hammerPullOriginNoteId),this.hammerPullOrigin.hammerPullDestination=this),-1!==this._noteIdBag.tieOriginNoteId&&(this.tieOrigin=t.get(this._noteIdBag.tieOriginNoteId),this.tieOrigin.tieDestination=this),-1!==this._noteIdBag.slurOriginNoteId&&(this.slurOrigin=t.get(this._noteIdBag.slurOriginNoteId),this.slurOrigin.slurDestination=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;let e=_e.findTieOrigin(this);e?(e.tieDestination=this,this.tieOrigin=e,this.fret=e.fret,this.octave=e.octave,this.tone=e.tone,e.hasBend&&(this.bendOrigin=this.tieOrigin)):this.isTieDestination=!1}}toJson(e){null!==this.tieDestination&&e.set("tiedestinationnoteid",this.tieDestination.id),null!==this.tieOrigin&&e.set("tieoriginnoteid",this.tieOrigin.id),null!==this.slurDestination&&e.set("slurdestinationnoteid",this.slurDestination.id),null!==this.slurOrigin&&e.set("sluroriginnoteid",this.slurOrigin.id),null!==this.hammerPullOrigin&&e.set("hammerpulloriginnoteid",this.hammerPullOrigin.id),null!==this.hammerPullDestination&&e.set("hammerpulldestinationnoteid",this.hammerPullDestination.id)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null===this._noteIdBag&&(this._noteIdBag=new Se),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null===this._noteIdBag&&(this._noteIdBag=new Se),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null===this._noteIdBag&&(this._noteIdBag=new Se),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null===this._noteIdBag&&(this._noteIdBag=new Se),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null===this._noteIdBag&&(this._noteIdBag=new Se),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null===this._noteIdBag&&(this._noteIdBag=new Se),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}_e.GlobalNoteId=0,_e.MaxOffsetForSameLineSearch=3,_e.NoteIdLookupKey="NoteIdLookup";class we{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==f.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of we.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}we.HalfTicks=1920,we.QuarterTicks=960,we.EighthTicks=480,we.SixteenthTicks=240,we.ThirtySecondTicks=120,we.SixtyFourthTicks=60,we.OneHundredTwentyEighthTicks=30,we.TwoHundredFiftySixthTicks=15,we.AllTicks=[we.HalfTicks,we.QuarterTicks,we.EighthTicks,we.SixteenthTicks,we.ThirtySecondTicks,we.SixtyFourthTicks,we.OneHundredTwentyEighthTicks,we.TwoHundredFiftySixthTicks],function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Dive=2]="Dive",e[e.Dip=3]="Dip",e[e.Hold=4]="Hold",e[e.Predive=5]="Predive",e[e.PrediveDive=6]="PrediveDive"}(F||(F={}));class Be{static clone(e){const t=new de;return t.offset=e.offset,t.value=e.value,t}}class Te{static clone(e){const t=new _e;t.index=e.index,t.accentuated=e.accentuated,t.bendType=e.bendType,t.bendStyle=e.bendStyle,t.isContinuedBend=e.isContinuedBend,t.bendPoints=[];for(const i of e.bendPoints)t.addBendPoint(Be.clone(i));return t.fret=e.fret,t.string=e.string,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.isFingering=e.isFingering,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t}}class ke{static clone(e){const t=new oe;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class ve{static clone(e){const t=new xe;t.index=e.index,t.notes=[];for(const i of e.notes)t.addNote(Te.clone(i));t.isEmpty=e.isEmpty,t.whammyStyle=e.whammyStyle,t.ottava=e.ottava,t.isLegatoOrigin=e.isLegatoOrigin,t.duration=e.duration,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.automations=[];for(const i of e.automations)t.automations.push(ke.clone(i));t.dots=e.dots,t.fadeIn=e.fadeIn,t.lyrics=e.lyrics?e.lyrics.slice():null,t.hasRasgueado=e.hasRasgueado,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,t.whammyBarPoints=[];for(const i of e.whammyBarPoints)t.addWhammyBarPoint(Be.clone(i));return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t}}class Ne{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=this.beats[0].absoluteDisplayStart+"_"+this.beats[0].voice.index)}}!function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext"}(L||(L={}));class 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=l.Default,this.ottava=o.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=p.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=c.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=F.None,this.whammyBarPoints=[],this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=w.None,this.chordId=null,this.graceType=f.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=x.None,this.tremoloSpeed=null,this.crescendo=u.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=g.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=L.Auto}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===p.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return this.whammyBarType!==F.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}addWhammyBarPoint(e){this.whammyBarPoints.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===F.None&&(this.whammyBarType=F.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(e<0||e>=t.length)return;t.splice(e,1);let i=t[e];if(i===this.maxWhammyPoint){this.maxWhammyPoint=null;for(let e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(i===this.minWhammyPoint){this.minWhammyPoint=null;for(let e of t)(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e)}}addNote(e){e.beat=this,e.index=this.notes.length,this.notes.push(e),e.isStringed&&this.noteStringLookup.set(e.string,e)}removeNote(e){let t=this.notes.indexOf(e);t>=0&&(this.notes.splice(t,1),e.isStringed&&this.noteStringLookup.delete(e.string))}getAutomation(e){for(let t=0,i=this.automations.length;t<i;t++){let i=this.automations[t];if(i.type===e)return i}return null}getNoteOnString(e){return this.noteStringLookup.has(e)?this.noteStringLookup.get(e):null}calculateDuration(){if(this.isFullBarRest)return this.voice.bar.masterBar.calculateDuration();let e=le.toTicks(this.duration);return 2===this.dots?e=le.applyDot(e,!0):1===this.dots&&(e=le.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=le.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case f.BeforeBeat:case f.OnBeat:switch(this.duration){case p.Sixteenth:this.playbackDuration=le.toTicks(p.SixtyFourth);break;case p.ThirtySecond:this.playbackDuration=le.toTicks(p.OneHundredTwentyEighth);break;default:this.playbackDuration=le.toTicks(p.ThirtySecond)}this.displayDuration=0;break;case f.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===f.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==f.None&&t)&&(e&&t&&t.check(this)||(t=new we(this.voice),t.check(this)),this.tupletGroup=t)}finish(t,i=null){switch(null===this.getAutomation(r.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(oe.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case f.OnBeat:case f.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?p.Eighth:2===e?p.Sixteenth:p.ThirtySecond}let s=t?t.notation.notationMode:e.NotationMode.GuitarPro,a="grad"===this.text||"grad."===this.text;a&&s===e.NotationMode.SongBook&&(this.text="");let n=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let o=0,h=!1;for(let r=0,c=this.notes.length;r<c;r++){let c=this.notes[r];if(c.dynamics=this.dynamics,c.finish(t,i),c.isLetRing&&(this.isLetRing=!0),c.isPalmMute&&(this.isPalmMute=!0),s===e.NotationMode.SongBook&&c.hasBend&&this.graceType!==f.BendGrace){if(!c.isTieOrigin)switch(c.bendType){case d.Bend:case d.PrebendRelease:case d.PrebendBend:n=!0}a||c.bendStyle===l.Gradual?(a=!0,c.bendStyle=l.Gradual,n=!1):c.bendStyle=l.Fast}c.isVisible&&(o++,(!this.minNote||c.realValue<this.minNote.realValue)&&(this.minNote=c),(!this.maxNote||c.realValue>this.maxNote.realValue)&&(this.maxNote=c),(!this.minStringNote||c.string<this.minStringNote.string)&&(this.minStringNote=c),(!this.maxStringNote||c.string>this.maxStringNote.string)&&(this.maxStringNote=c),c.hasEffectSlur&&(h=!0))}if(h&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===o&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&t&&t.notation.notationMode===e.NotationMode.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const c=this.whammyBarPoints;if(c.length>0&&this.whammyBarType===F.Custom){s===e.NotationMode.SongBook&&(this.whammyStyle=a?l.Gradual:l.Fast);let t=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=t,4===c.length){let i=c[0],a=c[1],r=c[2],n=c[3];a.value===r.value?i.value<a.value&&a.value<n.value||i.value>a.value&&a.value>n.value?(0===i.value||t?this.whammyBarType=F.Dive:this.whammyBarType=F.PrediveDive,c.splice(2,1),c.splice(1,1)):i.value>a.value&&a.value<n.value||i.value<a.value&&a.value>n.value?(this.whammyBarType=F.Dip,a.offset!==r.offset&&s!==e.NotationMode.SongBook||c.splice(2,1)):i.value===a.value&&a.value===n.value?(0===i.value||t?this.whammyBarType=F.Hold:this.whammyBarType=F.Predive,c.splice(2,1),c.splice(1,1)):ge.warning("Model","Unsupported whammy type detected, fallback to custom",null):ge.warning("Model","Unsupported whammy type detected, fallback to custom",null)}}if(this.updateDurations(),n){let e=ve.clone(this);e.id=xe._globalBeatId++,e.pickStroke=x.None;for(let t=0,i=e.notes.length;t<i;t++){let i=e.notes[t],s=this.notes[t];if(i.bendType=d.None,i.maxBendPoint=null,i.bendPoints=[],i.bendStyle=l.Default,i.id=_e.GlobalNoteId++,s.isTieOrigin&&(i.tieDestination=s.tieDestination,s.tieDestination.tieOrigin=i),s.isTieDestination&&(i.tieOrigin=s.tieOrigin?s.tieOrigin:null,s.tieOrigin.tieDestination=i),s.hasBend&&s.isTieOrigin){let e=_e.findTieOrigin(s);if(e&&e.hasBend){i.bendType=d.Hold;let e=s.bendPoints[s.bendPoints.length-1];i.addBendPoint(new de(0,e.value)),i.addBendPoint(new de(de.MaxPosition,e.value))}}i.isTieDestination=!0}this.graceType=f.BendGrace,this.graceGroup=new Ne,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new Ne,e.graceGroup.addBeat(this),e.graceGroup.isComplete=!0,e.graceGroup.finish()}}isBefore(e){return this.voice.bar.index<e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index<e.index}isAfter(e){return this.voice.bar.index>e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index>e.index}hasNoteOnString(e){return this.noteStringLookup.has(e)}getNoteWithRealValue(e){return this.noteValueLookup.has(e)?this.noteValueLookup.get(e):null}chain(e=null){for(const t of this.notes)this.noteValueLookup.set(t.realValue,t),t.chain(e)}}xe._globalBeatId=0;class Pe{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}}!function(e){e[e.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(M||(M={})),function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(D||(D={}));class Ee{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,i,s){if(!e)return;let a=D.Begin,r=D.Begin,n=!1,o=0;for(;t<e.length;){let i=e.charCodeAt(t);switch(a){case D.IgnoreSpaces:switch(i){case Ee.CharCodeLF:case Ee.CharCodeCR:case Ee.CharCodeTab:break;case Ee.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case D.Begin:if(i!==Ee.CharCodeBrackedOpen){o=t,a=D.Text;continue}a=D.Comment;break;case D.Comment:if(i===Ee.CharCodeBrackedClose)a=D.Begin;break;case D.Text:switch(i){case Ee.CharCodeDash:a=D.Dash;break;case Ee.CharCodeCR:case Ee.CharCodeLF:case Ee.CharCodeSpace:let i=e.substr(o,t-o);this.addChunk(i,s),a=D.IgnoreSpaces,r=D.Begin}break;case D.Dash:if(i!==Ee.CharCodeDash){let i=e.substr(o,t-o);this.addChunk(i,s),n=!0,a=D.IgnoreSpaces,r=D.Begin;continue}}t+=1}a===D.Text&&t!==o&&this.addChunk(e.substr(o,t-o),s)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){let t=e.split("+").join(" "),i=t.length;for(;i>0&&"_"===t.charAt(i-1);)i--;return i!==t.length?t.substr(0,i):t}}Ee.CharCodeLF=10,Ee.CharCodeTab=9,Ee.CharCodeCR=13,Ee.CharCodeSpace=32,Ee.CharCodeBrackedClose=93,Ee.CharCodeBrackedOpen=91,Ee.CharCodeDash=45,function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(I||(I={})),function(e){e[e.NoTripletFeel=0]="NoTripletFeel",e[e.Triplet16th=1]="Triplet16th",e[e.Triplet8th=2]="Triplet8th",e[e.Dotted16th=3]="Dotted16th",e[e.Dotted8th=4]="Dotted8th",e[e.Scottish16th=5]="Scottish16th",e[e.Scottish8th=6]="Scottish8th"}(R||(R={}));class Ce{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=M.C,this.keySignatureType=I.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.tripletFeel=R.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=new Map,this.start=0,this.isAnacrusis=!1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let i of t.staves){let t=this.index<i.bars.length?i.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*le.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){this.fermata.set(e,t)}getFermata(e){const t=this.fermata;return t.has(e.playbackStart)?t.get(e.playbackStart):null}}Ce.MaxAlternateEndings=8;class Fe{constructor(){this.hideDynamics=!1}}class Le{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){var e;return!0===(null===(e=this.opening)||void 0===e?void 0:e.isRepeatStart)}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class Me{constructor(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0,this.album="",this.artist="",this.copyright="",this.instructions="",this.music="",this.notices="",this.subTitle="",this.title="",this.words="",this.tab="",this.tempo=120,this.tempoLabel="",this.masterBars=[],this.tracks=[],this.stylesheet=new Fe}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){var t;e.isRepeatStart?((null===(t=this._currentRepeatGroup)||void 0===t?void 0:t.isClosed)&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new Le,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new Le,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let i=0,s=this.tracks.length;i<s;i++)this.tracks[i].finish(e,t)}}class De{constructor(){this.marker="",this.text=""}}class Ie extends re{constructor(t){super(e.AlphaTabErrorType.Format,t),Object.setPrototypeOf(this,Ie.prototype)}}class Re{constructor(e,t,i,s=255){this.raw=0,this.raw=(255&s)<<24|(255&e)<<16|(255&t)<<8|255&i,this.updateRgba()}updateRgba(){255===this.a?this.rgba="#"+me.toHexString(this.r,2)+me.toHexString(this.g,2)+me.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 Re(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new Re(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 Re(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new Re(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16),17*parseInt(t[4],16));if(7===t.length)return new Re(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new Re(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16),parseInt(t.substring(7,9),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),i=t.lastIndexOf(")");if(-1===e||-1===i)throw new Ie("No values specified for rgb/rgba function");const s=t.substring(e+1,i).split(",");if(3===s.length)return new Re(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]));if(4===s.length)return new Re(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]),255*parseFloat(s[3]))}return null}}throw new Ie("Unsupported format for color")}static toJson(e){return e.raw}}Re.BlackRgb="#000000";class Ae{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 Oe{constructor(e="",t=null,i=!1){this.isStandard=i,this.name=e,this.tunings=null!=t?t:[]}static getTextForTuning(e,t){let i=Oe.getTextPartsForTuning(e);return t?i.join(""):i[0]}static getTextPartsForTuning(e,t=-1){return[["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"][e%12],((e/12|0)+t).toString()]}static getDefaultTuningFor(e){return Oe._defaultTunings.has(e)?Oe._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return Oe._sevenStrings;case 6:return Oe._sixStrings;case 5:return Oe._fiveStrings;case 4:return Oe._fourStrings}return[]}static initialize(){Oe._defaultTunings.set(7,new Oe("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),Oe._sevenStrings.push(Oe._defaultTunings.get(7)),Oe._defaultTunings.set(6,new Oe("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),Oe._sixStrings.push(Oe._defaultTunings.get(6)),Oe._sixStrings.push(new Oe("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),Oe._sixStrings.push(new Oe("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),Oe._sixStrings.push(new Oe("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),Oe._sixStrings.push(new Oe("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),Oe._sixStrings.push(new Oe("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),Oe._sixStrings.push(new Oe("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),Oe._sixStrings.push(new Oe("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),Oe._sixStrings.push(new Oe("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),Oe._sixStrings.push(new Oe("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),Oe._sixStrings.push(new Oe("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),Oe._sixStrings.push(new Oe("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),Oe._sixStrings.push(new Oe("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),Oe._sixStrings.push(new Oe("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),Oe._sixStrings.push(new Oe("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),Oe._sixStrings.push(new Oe("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),Oe._sixStrings.push(new Oe("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),Oe._sixStrings.push(new Oe("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),Oe._sixStrings.push(new Oe("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),Oe._sixStrings.push(new Oe("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),Oe._sixStrings.push(new Oe("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),Oe._sixStrings.push(new Oe("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),Oe._sixStrings.push(new Oe("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),Oe._defaultTunings.set(5,new Oe("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),Oe._fiveStrings.push(Oe._defaultTunings.get(5)),Oe._fiveStrings.push(new Oe("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),Oe._fiveStrings.push(new Oe("Banjo Open D Tuning",[62,57,54,50,69],!1)),Oe._fiveStrings.push(new Oe("Banjo Open G Tuning",[62,59,55,50,67],!1)),Oe._fiveStrings.push(new Oe("Banjo G Minor Tuning",[62,58,55,50,67],!1)),Oe._fiveStrings.push(new Oe("Banjo G Modal Tuning",[62,57,55,50,67],!1)),Oe._defaultTunings.set(4,new Oe("Bass Standard Tuning",[43,38,33,28],!0)),Oe._fourStrings.push(Oe._defaultTunings.get(4)),Oe._fourStrings.push(new Oe("Bass Tune down ½ step",[42,37,32,27],!1)),Oe._fourStrings.push(new Oe("Bass Tune down 1 step",[41,36,31,26],!1)),Oe._fourStrings.push(new Oe("Bass Tune down 2 step",[39,34,29,24],!1)),Oe._fourStrings.push(new Oe("Bass Dropped D Tuning",[43,38,33,26],!1)),Oe._fourStrings.push(new Oe("Ukulele C Tuning",[45,40,36,43],!1)),Oe._fourStrings.push(new Oe("Ukulele G Tuning",[52,47,43,38],!1)),Oe._fourStrings.push(new Oe("Mandolin Standard Tuning",[64,57,50,43],!1)),Oe._fourStrings.push(new Oe("Mandolin or Violin Tuning",[76,69,62,55],!1)),Oe._fourStrings.push(new Oe("Viola Tuning",[69,62,55,48],!1)),Oe._fourStrings.push(new Oe("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=Oe.getPresetsFor(e.length);for(let i=0,s=t.length;i<s;i++){let s=t[i],a=!0;for(let t=0,i=e.length;t<i;t++)if(e[t]!==s.tunings[t]){a=!1;break}if(a)return s}return null}finish(){const e=Oe.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}Oe._sevenStrings=[],Oe._sixStrings=[],Oe._fiveStrings=[],Oe._fourStrings=[],Oe._defaultTunings=new Map,Oe.defaultAccidentals=["","#","","#","","","#","","#","","#",""],Oe.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],Oe.initialize();class Ge{constructor(){this.index=0,this.bars=[],this.chords=new Map,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new Oe("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let i=0,s=this.bars.length;i<s;i++)this.bars[i].finish(e,t)}addChord(e,t){t.staff=this,this.chords.set(e,t)}hasChord(e){return this.chords.has(e)}getChord(e){return this.chords.get(e)}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}class He{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Ae,this.color=new Re(200,0,0,255),this.name="",this.shortName="",this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new Ge)}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>He.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,He.ShortNameMaxLength)));for(let i=0,s=this.staves.length;i<s;i++)this.staves[i].finish(e,t)}applyLyrics(e){for(let t of e)t.finish();let t=this.staves[0];for(let i=0;i<e.length;i++){let s=e[i];if(s.startBar>=0&&s.startBar<t.bars.length){let a=t.bars[s.startBar].voices[0].beats[0];for(let t=0;t<s.chunks.length&&a;t++){for(;a&&(a.isEmpty||a.isRest);)a=a.nextBeat;a&&(a.lyrics||(a.lyrics=new Array(e.length)),a.lyrics[i]=s.chunks[t],a=a.nextBeat)}}}}}He.ShortNameMaxLength=10;class Ve{constructor(){this.id=Ve._globalBarId++,this.index=0,this.beats=[],this.isEmpty=!0}insertBeat(e,t){t.nextBeat=e.nextBeat,t.nextBeat&&(t.nextBeat.previousBeat=t),t.previousBeat=e,t.voice=this,e.nextBeat=t,this.beats.splice(e.index+1,0,t)}addBeat(e){e.voice=this,e.index=this.beats.length,this.beats.push(e),e.isEmpty||(this.isEmpty=!1)}chain(e,t=null){if(this.bar){if(e.index<this.beats.length-1)e.nextBeat=this.beats[e.index+1],e.nextBeat.previousBeat=e;else if(e.isLastOfVoice&&e.voice.bar.nextBar){let t=this.bar.nextBar.voices[this.index];t.beats.length>0?(e.nextBeat=t.beats[0],e.nextBeat.previousBeat=e):e.nextBeat.previousBeat=e}e.chain(t)}}addGraceBeat(e){if(0===this.beats.length)return void this.addBeat(e);let t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this.isEmpty=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._beatLookup=new Map;let i=null;for(let e=0;e<this.beats.length;e++){let s=this.beats[e];s.index=e,this.chain(s,t),s.graceType===f.None?(s.graceGroup=i,i&&(i.isComplete=!0),i=null):(i||(i=new Ne),i.addBeat(s))}let s=0,a=0;for(let i=0;i<this.beats.length;i++){let r=this.beats[i];if(r.index=i,r.finish(e,t),r.graceType===f.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==f.BendGrace){let i=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case f.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=i,a=e.previousBeat.voice==this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-i):a=-i;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case f.OnBeat:r.playbackDuration-=i,a=t.voice===this?t.playbackStart+t.playbackDuration:-i}}}r.displayStart=s,r.playbackStart=a,r.fermata?this.bar.masterBar.addFermata(r.playbackStart,r.fermata):r.fermata=this.bar.masterBar.getFermata(r),this._beatLookup.set(r.playbackStart,r)}else r.displayStart=s,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),s+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;let e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}}Ve._globalBarId=0;class We{static float64ToBytes(e){return We._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw We._conversionByteArray.set(e,0),We._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return We._dataView.setUint16(0,e,!0),We._dataView.getInt16(0,!0)}static int16ToUint32(e){return We._dataView.setInt16(0,e,!0),We._dataView.getUint32(0,!0)}static int32ToUint16(e){return We._dataView.setInt32(0,e,!0),We._dataView.getUint16(0,!0)}static int32ToInt16(e){return We._dataView.setInt32(0,e,!0),We._dataView.getInt16(0,!0)}static int32ToUint32(e){return We._dataView.setInt32(0,e,!0),We._dataView.getUint32(0,!0)}static uint8ToInt8(e){return We._dataView.setUint8(0,e),We._dataView.getInt8(0)}}We._conversionBuffer=new ArrayBuffer(8),We._conversionByteArray=new Uint8Array(We._conversionBuffer),We._dataView=new DataView(We._conversionBuffer);class ze{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readInt32LE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte();return e.readByte()<<24|s<<16|i<<8|t}static readUInt32LE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte();return e.readByte()<<24|s<<16|i<<8|t}static decodeUInt32LE(e,t){let i=e[t],s=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|s<<8|i}static readUInt16LE(e){let t=e.readByte(),i=e.readByte();return We.int32ToUint16(i<<8|t)}static readInt16LE(e){let t=e.readByte(),i=e.readByte();return We.int32ToInt16(i<<8|t)}static readUInt32BE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte(),a=e.readByte();return We.int32ToUint32(t<<24|i<<16|s<<8|a)}static readUInt16BE(e){let t=e.readByte(),i=e.readByte();return We.int32ToInt16(t<<8|i)}static readInt16BE(e){let t=e.readByte(),i=e.readByte();return We.int32ToInt16(t<<8|i)}static readByteArray(e,t){let i=new Uint8Array(t);return e.read(i,0,t),i}static read8BitChars(e,t){let i=new Uint8Array(t);return e.read(i,0,i.length),ze.toString(i,"utf-8")}static read8BitString(e){let t="",i=e.readByte();for(;0!==i;)t+=String.fromCharCode(i),i=e.readByte();return t}static read8BitStringLength(e,t){let i="",s=-1;for(let a=0;a<t;a++){let t=e.readByte();0===t&&-1===s&&(s=a),i+=String.fromCharCode(t)}let a=i;return s>=0?a.substr(0,s):a}static readSInt8(e){let t=e.readByte();return-256*((255&t)>>7)+(255&t)}static readInt24(e,t){let i=e[t]|e[t+1]<<8|e[t+2]<<16;return 8388608==(8388608&i)&&(i|=255<<24),i}static readInt16(e,t){return We.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let i=ze.detectEncoding(e);return i&&(t=i),t||(t="utf-8"),new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(t>>0&255)}static writeInt32LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}}class Ue{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Ue.withCapacity(0)}static withCapacity(e){let t=new Ue;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new Ue;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=ze.stringToBytes(e);return Ue.fromBuffer(t)}reset(){this.position=0}skip(e){this.position+=e}readByte(){return this.length-this.position<=0?-1:this._buffer[this.position++]}read(e,t,i){let s=this.length-this.position;return s>i&&(s=i),s<=0?0:(e.set(this._buffer.subarray(this.position,this.position+s),t),this.position+=s,s)}writeByte(e){let t=this.position+1;this.ensureCapacity(t),this._buffer[this.position]=255&e,t>this.length&&(this.length=t),this.position=t}write(e,t,i){let s=this.position+i;this.ensureCapacity(s);let a=Math.min(i,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),s>this.length&&(this.length=s),this.position=s}ensureCapacity(e){if(e>this._buffer.length){let t=e;t<256&&(t=256),t<2*this._buffer.length&&(t=2*this._buffer.length);let i=new Uint8Array(t);this.length>0&&i.set(this._buffer.subarray(0,0+this.length),0),this._buffer=i}}readAll(){return this.toArray()}toArray(){let e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}}!function(e){e[e.No=0]="No",e[e.Eof=1]="Eof",e[e.Number=2]="Number",e[e.DoubleDot=3]="DoubleDot",e[e.Dot=4]="Dot",e[e.String=5]="String",e[e.Tuning=6]="Tuning",e[e.LParensis=7]="LParensis",e[e.RParensis=8]="RParensis",e[e.LBrace=9]="LBrace",e[e.RBrace=10]="RBrace",e[e.Pipe=11]="Pipe",e[e.MetaCommand=12]="MetaCommand",e[e.Multiply=13]="Multiply",e[e.LowerThan=14]="LowerThan",e[e.Property=15]="Property"}(A||(A={}));class Xe extends re{constructor(t){super(e.AlphaTabErrorType.AlphaTex,t),this.position=0,this.nonTerm="",this.expected=A.No,this.symbol=A.No,this.symbolData=null,Object.setPrototypeOf(this,Xe.prototype)}static symbolError(e,t,i,s,a=null){let r;r=i!==s?`MalFormed AlphaTex: @${e}: Error on block ${t}, expected a ${A[i]} found a ${A[s]}: '${a}'`:`MalFormed AlphaTex: @${e}: Error on block ${t}, invalid value: '${a}'`;let n=new Xe(r);return n.position=e,n.nonTerm=t,n.expected=i,n.symbol=s,n.symbolData=a,n}static errorMessage(e,t){let i=new Xe(t=`MalFormed AlphaTex: @${e}: ${t}`);return i.position=e,i}}class Ye extends ae{constructor(){super(),this._trackChannel=0,this._input="",this._ch=0,this._curChPos=0,this._sy=A.No,this._syData="",this._allowNegatives=!1,this._allowTuning=!1,this._currentDuration=p.QuadrupleWhole,this._currentDynamics=g.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Ue.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=ze.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._currentDuration=p.Quarter,this._currentDynamics=g.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===A.LowerThan)throw new ne("Unknown start sign <");this.score(),this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);return this._score}catch(e){throw e instanceof Xe?new ne(e.message):e}}consolidate(){for(let e of this._score.tracks)for(let t of e.staves)for(;t.bars.length<this._score.masterBars.length;){let e=this.newBar(t),i=new xe;i.isEmpty=!0,e.voices[0].addBeat(i)}}error(e,t,i=!0){let s;throw s=i?Xe.symbolError(this._curChPos,e,t,this._sy,this._syData):Xe.symbolError(this._curChPos,e,t,t,this._syData),this.logErrors&&ge.error(this.name,s.message),s}errorMessage(e){let t=Xe.errorMessage(this._curChPos,e);throw this.logErrors&&ge.error(this.name,t.message),t}createDefaultScore(){this._score=new Me,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new He,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++,this._currentStaff=this._currentTrack.staves[0],this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=Oe.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=g.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return n.G2;case"f4":case"bass":return n.F4;case"c3":case"tenor":return n.C3;case"c4":case"alto":return n.C4;case"n":case"neutral":return n.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return n.G2;case 65:return n.F4;case 48:return n.C3;case 60:return n.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return R.NoTripletFeel;case"t16":case"triplet-16th":return R.Triplet16th;case"t8":case"triplet-8th":return R.Triplet8th;case"d16":case"dotted-16th":return R.Dotted16th;case"d8":case"dotted-8th":return R.Dotted8th;case"s16":case"scottish-16th":return R.Scottish16th;case"s8":case"scottish-8th":return R.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return R.NoTripletFeel;case 1:return R.Triplet16th;case 2:return R.Triplet8th;case 3:return R.Dotted16th;case 4:return R.Dotted8th;case 5:return R.Scottish16th;case 6:return R.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":return M.Cb;case"gb":case"gbmajor":case"d#minor":return M.Gb;case"db":case"dbmajor":case"bbminor":return M.Db;case"ab":case"abmajor":case"fminor":return M.Ab;case"eb":case"ebmajor":case"cminor":return M.Eb;case"bb":case"bbmajor":case"gminor":return M.Bb;case"f":case"fmajor":case"dminor":return M.F;case"c":case"cmajor":case"aminor":default:return M.C;case"g":case"gmajor":case"eminor":return M.G;case"d":case"dmajor":case"bminor":return M.D;case"a":case"amajor":case"f#minor":return M.A;case"e":case"emajor":case"c#minor":return M.E;case"b":case"bmajor":case"g#minor":return M.B;case"f#":case"f#major":case"ebminor":return M.FSharp;case"c#":case"c#major":return M.CSharp}}nextChar(){return this._curChPos<this._input.length?this._ch=this._input.charCodeAt(this._curChPos++):this._ch=0,this._ch}newSy(){this._sy=A.No;do{if(this._ch===Ye.Eof)this._sy=A.Eof;else if(32===this._ch||11===this._ch||13===this._ch||10===this._ch||9===this._ch)this._ch=this.nextChar();else if(47===this._ch)if(this._ch=this.nextChar(),47===this._ch)for(;13!==this._ch&&10!==this._ch&&this._ch!==Ye.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==Ye.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("symbol",A.String,!1);else if(34===this._ch||39===this._ch){let e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=A.String;this._ch!==e&&this._ch!==Ye.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives&&this.isDigit(this._ch)?(this._sy=A.Number,this._syData=this.readNumber()):(this._sy=A.String,this._syData=this.readName());else if(46===this._ch)this._sy=A.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=A.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=A.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=A.MetaCommand,this._syData=this.readName();else if(41===this._ch)this._sy=A.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=A.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=A.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=A.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=A.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=A.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this._sy=A.Number,this._syData=this.readNumber();else if(Ye.isLetter(this._ch)){let e=this.readName(),t=this._allowTuning?me.parseTuning(e):null;t?(this._sy=A.Tuning,this._syData=t):(this._sy=A.String,this._syData=e)}else this.error("symbol",A.String,!1)}while(this._sy===A.No);return this._sy}static isLetter(e){return!Ye.isTerminal(e)&&(e>=33&&e<=47||e>=58&&e<=126||e>128)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||92===e}isDigit(e){return e>=48&&e<=57||45===e&&this._allowNegatives}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(Ye.isLetter(this._ch)||this.isDigit(this._ch)||35===this._ch);return e}readNumber(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(this.isDigit(this._ch));return parseInt(e)}score(){if(this._sy===A.Eof)throw new ne("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new ne("No alphaTex data found")}metaData(){let e=!1,t=!0;for(;this._sy===A.MetaCommand&&t;){switch(this._syData.toLowerCase()){case"title":this._sy=this.newSy(),this._sy===A.String?this._score.title=this._syData:this.error("title",A.String,!0),this._sy=this.newSy(),e=!0;break;case"subtitle":this._sy=this.newSy(),this._sy===A.String?this._score.subTitle=this._syData:this.error("subtitle",A.String,!0),this._sy=this.newSy(),e=!0;break;case"artist":this._sy=this.newSy(),this._sy===A.String?this._score.artist=this._syData:this.error("artist",A.String,!0),this._sy=this.newSy(),e=!0;break;case"album":this._sy=this.newSy(),this._sy===A.String?this._score.album=this._syData:this.error("album",A.String,!0),this._sy=this.newSy(),e=!0;break;case"words":this._sy=this.newSy(),this._sy===A.String?this._score.words=this._syData:this.error("words",A.String,!0),this._sy=this.newSy(),e=!0;break;case"music":this._sy=this.newSy(),this._sy===A.String?this._score.music=this._syData:this.error("music",A.String,!0),this._sy=this.newSy(),e=!0;break;case"copyright":this._sy=this.newSy(),this._sy===A.String?this._score.copyright=this._syData:this.error("copyright",A.String,!0),this._sy=this.newSy(),e=!0;break;case"tempo":this._sy=this.newSy(),this._sy===A.Number?this._score.tempo=this._syData:this.error("tempo",A.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",A.String,!1):t=!1}}return e?(this._sy!==A.Dot&&this.error("song",A.Dot,!0),this._sy=this.newSy()):this._sy===A.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===A.Number?this._currentStaff.capo=this._syData:this.error("capo",A.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case A.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",A.Tuning,!0),this._sy=this.newSy();break;case A.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===A.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",A.Tuning,!0)}return e!==this._currentStaff.tuning.length&&this._currentStaff.chords.size>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===A.Number){let e=this._syData;e>=0&&e<=128?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",A.Number,!1)}else if(this._sy===A.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=se.getValue(e)}else this.error("instrument",A.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let t=new Ee;return t.startBar=0,t.text="",this._sy===A.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===A.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",A.String,!0),this._lyrics.get(this._currentTrack.index).push(t),!0;case"chord":this._sy=this.newSy();let i=new Pe;this.chordProperties(i),this._sy===A.String?(i.name=this._syData,this._sy=this.newSy()):this.error("chord-name",A.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===A.Number?i.strings.push(this._syData):this._sy===A.String&&"x"===this._syData.toLowerCase()&&i.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,i.name),i),!0;default:return!1}}chordProperties(e){if(this._sy===A.LBrace){for(this._sy=this.newSy();this._sy===A.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===A.Number)e.firstFret=this._syData;else this.error("chord-firstfret",A.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case A.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case A.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",A.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case A.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case A.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",A.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case A.String:e.showName="false"!==this._syData.toLowerCase();break;case A.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",A.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===A.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",A.String,!1)}this._sy!==A.RBrace&&this.error("chord-properties",A.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==A.Eof;)if(this._sy===A.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==A.MetaCommand)break;this.bar()}return e}trackStaffMeta(){let e=!1;if(this._sy===A.MetaCommand){e=!0;let t=this._syData.toLowerCase();"track"===t&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===A.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===A.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===A.MetaCommand&&(t=this._syData.toLowerCase(),"staff"===t&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=g.F),this.staffProperties()))}return e}staffProperties(){if(this._sy!==A.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===A.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy();break;case"tabs":t=!0,this._sy=this.newSy();break;default:this.error("staff-properties",A.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==A.RBrace&&this.error("staff-properties",A.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta();let t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){let e=new Ce;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const i=this.barMeta(t);if(!this._staffTuningApplied&&!this._staffHasExplicitTuning){const e=this._currentTrack.playbackInfo.program;this._currentStaff.displayTranspositionPitch=0,this._currentStaff.stringTuning.tunings=[],15==e||e>=24&&e<=31?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=Oe.getDefaultTuningFor(6).tunings):e>=32&&e<=39?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):40==e||44==e||45==e||48==e||49==e||50==e||51==e?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==e?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==e?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==e?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):105==e?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==e?this._currentStaff.stringTuning.tunings=[57,52,45]:107==e?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==e&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0}let s=!1,a=t.voices[0];for(;this._sy!==A.Pipe&&this._sy!==A.Eof&&this.beat(a);)s=!0;if(0===a.beats.length){let e=new xe;e.isEmpty=!0,a.addBeat(e)}return e||i||s}newBar(e){let t=new he;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let i=new Ve;return t.addVoice(i),t}beat(e){this.beatDuration();let t=new xe;if(e.addBeat(t),this._sy===A.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==A.RParensis&&this._sy!==A.Eof&&this.note(t););this._sy!==A.RParensis&&this.error("note-list",A.RParensis,!0),this._sy=this.newSy()}else if(this._sy===A.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===A.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==A.Number&&this.error("duration",A.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._sy=this.newSy()),t.duration=this._currentDuration,t.dynamics=this._currentDynamics,1===this._currentTuplet||t.hasTuplet||this.applyTuplet(t,this._currentTuplet);let i=1;this._sy===A.Multiply&&(this._sy=this.newSy(),this._sy!==A.Number?this.error("multiplier",A.Number,!0):i=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let s=0;s<i-1;s++)e.addBeat(ve.clone(t));return!0}beatDuration(){if(this._sy===A.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==A.Number&&this.error("duration",A.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===A.LBrace)){for(this._sy=this.newSy();this._sy===A.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==A.Number&&this.error("duration-tuplet",A.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",A.String,!1)}this._sy!==A.RBrace&&this.error("beat-duration",A.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===A.LBrace){for(this._sy=this.newSy();this._sy===A.String;)this._syData=this._syData.toLowerCase(),this.applyBeatEffect(e)||this.error("beat-effects",A.String,!1);this._sy!==A.RBrace&&this.error("beat-effects",A.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)return e.fadeIn=!0,this._sy=this.newSy(),!0;if("v"===t)return e.vibrato=w.Slight,this._sy=this.newSy(),!0;if("s"===t)return e.slap=!0,this._sy=this.newSy(),!0;if("p"===t)return e.pop=!0,this._sy=this.newSy(),!0;if("tt"===t)return e.tap=!0,this._sy=this.newSy(),!0;if("dd"===t)return e.dots=2,this._sy=this.newSy(),!0;if("d"===t)return e.dots=1,this._sy=this.newSy(),!0;if("su"===t)return e.pickStroke=x.Up,this._sy=this.newSy(),!0;if("sd"===t)return e.pickStroke=x.Down,this._sy=this.newSy(),!0;if("tu"===t)return this._sy=this.newSy(),this._sy!==A.Number?(this.error("tuplet",A.Number,!0),!1):(this.applyTuplet(e,this._syData),this._sy=this.newSy(),!0);if("tb"===t||"tbe"===t){let i="tbe"===t;if(this._sy=this.newSy(),this._sy!==A.LParensis)return this.error("tremolobar-effect",A.LParensis,!0),!1;for(this._allowNegatives=!0,this._sy=this.newSy();this._sy!==A.RParensis&&this._sy!==A.Eof;){let t=0,s=0;if(i){if(this._sy!==A.Number)return this.error("tremolobar-effect",A.Number,!0),!1;if(t=this._syData,this._sy=this.newSy(),this._sy!==A.Number)return this.error("tremolobar-effect",A.Number,!0),!1;s=this._syData}else{if(this._sy!==A.Number)return this.error("tremolobar-effect",A.Number,!0),!1;t=0,s=this._syData}e.addWhammyBarPoint(new de(t,s)),this._sy=this.newSy()}for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(i)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{let t=e.whammyBarPoints.length,i=60/t|0,s=0;for(;s<t;)e.whammyBarPoints[s].offset=Math.min(60,s*i),s++}return this._allowNegatives=!1,this._sy!==A.RParensis?(this.error("tremolobar-effect",A.RParensis,!0),!1):(this._sy=this.newSy(),!0)}if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=c.BrushUp;break;case"bd":e.brushType=c.BrushDown;break;case"au":e.brushType=c.ArpeggioUp;break;case"ad":e.brushType=c.ArpeggioDown}return this._sy=this.newSy(),this._sy===A.Number?(e.brushDuration=this._syData,this._sy=this.newSy(),!0):(e.updateDurations(),"bu"===t||"bd"===t?e.brushDuration=e.playbackDuration/4/e.notes.length:"au"!==t&&"ad"!==t||(e.brushDuration=e.playbackDuration/e.notes.length),!0)}if("ch"===t){this._sy=this.newSy();let t=this._syData,i=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(i)){let e=new Pe;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(i,e)}return e.chordId=i,this._sy=this.newSy(),!0}if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=f.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=f.BendGrace,this._sy=this.newSy()):e.graceType=f.BeforeBeat,!0;if("dy"===t){switch(this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=g.PPP;break;case"pp":e.dynamics=g.PP;break;case"p":e.dynamics=g.P;break;case"mp":e.dynamics=g.MP;break;case"mf":e.dynamics=g.MF;break;case"f":e.dynamics=g.F;break;case"ff":e.dynamics=g.FF;break;case"fff":e.dynamics=g.FFF}return this._currentDynamics=e.dynamics,this.newSy(),!0}if("cre"===t)return e.crescendo=u.Crescendo,this.newSy(),!0;if("dec"===t)return e.crescendo=u.Decrescendo,this.newSy(),!0;if("tp"===t){this._sy=this.newSy();let t=p.Eighth;if(this._sy===A.Number){switch(this._syData){case 8:default:t=p.Eighth;break;case 16:t=p.Sixteenth;break;case 32:t=p.ThirtySecond}this._sy=this.newSy()}return e.tremoloSpeed=t,!0}return!1}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,i=!1,s=-1,a=-1,r=-1;switch(this._sy){case A.Number:s=this._syData;break;case A.String:t="x"===this._syData,i="-"===this._syData,i||t?s=0:this.error("note-fret",A.Number,!0);break;case A.Tuning:let e=this._syData;a=e.octave,r=e.noteValue;break;default:return!1}this._sy=this.newSy();let n=-1===a&&this._currentStaff.tuning.length>0,o=-1;n&&(this._sy!==A.Dot&&this.error("note",A.Dot,!0),this._sy=this.newSy(),this._sy!==A.Number&&this.error("note-string",A.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",A.Number,!1),this._sy=this.newSy());let h=new _e;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=i,i||(h.fret=s)):(h.octave=a,h.tone=r,h.isTieDestination=i),e.addNote(h),this.noteEffects(h),!0}noteEffects(e){if(this._sy===A.LBrace){for(this._sy=this.newSy();this._sy===A.String;){let t=this._syData.toLowerCase();if(this._syData=t,"b"===t||"be"===t){let t="be"===this._syData;for(this._sy=this.newSy(),this._sy!==A.LParensis&&this.error("bend-effect",A.LParensis,!0),this._sy=this.newSy();this._sy!==A.RParensis&&this._sy!==A.Eof;){let i=0,s=0;t?(this._sy!==A.Number&&this.error("bend-effect-value",A.Number,!0),i=this._syData,this._sy=this.newSy(),this._sy!==A.Number&&this.error("bend-effect-value",A.Number,!0),s=this._syData):(this._sy!==A.Number&&this.error("bend-effect-value",A.Number,!0),s=this._syData),e.addBendPoint(new de(i,s)),this._sy=this.newSy()}const i=e.bendPoints;for(;i.length>60;)i.splice(i.length-1,1);if(t)i.sort(((e,t)=>e.offset-t.offset));else{let e=i.length,t=60/(e-1)|0,s=0;for(;s<e;)i[s].offset=Math.min(60,s*t),s++}this._sy!==A.RParensis&&this.error("bend-effect",A.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=y.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=y.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=y.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=y.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=y.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==A.Number&&this.error("trill-effect",A.Number,!0);let t=this._syData;this._sy=this.newSy();let i=p.Sixteenth;if(this._sy===A.Number){switch(this._syData){case 16:default:i=p.Sixteenth;break;case 32:i=p.ThirtySecond;break;case 64:i=p.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=i}else if("v"===t)this._sy=this.newSy(),e.vibrato=w.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=_.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=_.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=_.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=_.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=_.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=_.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=a.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=a.Heavy;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=m.Thumb;this._sy===A.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=m.Thumb;this._sy===A.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,A.String,!1)}this._sy!==A.RBrace&&this.error("note-effect",A.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return m.Thumb;case 2:return m.IndexFinger;case 3:return m.MiddleFinger;case 4:return m.AnnularFinger;case 5:return m.LittleFinger}return m.Thumb}parseDuration(e){switch(e){case-4:return p.QuadrupleWhole;case-2:return p.DoubleWhole;case 1:return p.Whole;case 2:return p.Half;case 4:return p.Quarter;case 8:return p.Eighth;case 16:return p.Sixteenth;case 32:return p.ThirtySecond;case 64:return p.SixtyFourth;case 128:return p.OneHundredTwentyEighth;case 256:return p.TwoHundredFiftySixth;default:return p.Quarter}}barMeta(e){let t=!1,i=e.masterBar;for(;this._sy===A.MetaCommand;){t=!0;let s=this._syData.toLowerCase();if("ts"===s)this._sy=this.newSy(),this._sy!==A.Number&&this.error("timesignature-numerator",A.Number,!0),i.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==A.Number&&this.error("timesignature-denominator",A.Number,!0),i.timeSignatureDenominator=this._syData,this._sy=this.newSy();else if("ro"===s)i.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===s)this._sy=this.newSy(),this._sy!==A.Number&&this.error("repeatclose",A.Number,!0),this._syData>2048&&this.error("repeatclose",A.Number,!1),i.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===s)if(this._sy=this.newSy(),this._sy===A.LParensis){for(this._sy=this.newSy(),this._sy!==A.Number&&this.error("alternateending",A.Number,!0),this.applyAlternateEnding(i);this._sy===A.Number;)this.applyAlternateEnding(i);this._sy!==A.RParensis&&this.error("alternateending-list",A.RParensis,!0),this._sy=this.newSy()}else this._sy!==A.Number&&this.error("alternateending",A.Number,!0),this.applyAlternateEnding(i);else if("ks"===s)this._sy=this.newSy(),this._sy!==A.String&&this.error("keysignature",A.String,!0),i.keySignature=this.parseKeySignature(this._syData),this._sy=this.newSy();else if("clef"===s){switch(this._sy=this.newSy(),this._sy){case A.String:e.clef=this.parseClefFromString(this._syData);break;case A.Number:e.clef=this.parseClefFromInt(this._syData);break;case A.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",A.String,!0)}this._sy=this.newSy()}else if("tempo"===s){this._sy=this.newSy(),this._sy!==A.Number&&this.error("tempo",A.Number,!0);let e=new oe;e.isLinear=!1,e.type=r.Tempo,e.value=this._syData,i.tempoAutomation=e,this._sy=this.newSy()}else if("section"===s){this._sy=this.newSy(),this._sy!==A.String&&this.error("section",A.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==A.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let s=new De;s.marker=t,s.text=e,i.section=s}else if("tf"===s){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case A.String:i.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case A.Number:i.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",A.String,!0)}this._sy=this.newSy()}else"ac"===s?(i.isAnacrusis=!0,this._sy=this.newSy()):0===e.index&&this.handleStaffMeta()||this.error("measure-effects",A.String,!1)}if(0===i.index&&!i.tempoAutomation){let e=new oe;e.isLinear=!1,e.type=r.Tempo,e.value=this._score.tempo,i.tempoAutomation=e}return t}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",A.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}}Ye.Eof=0;class qe extends ae{constructor(){super(),this._versionNumber=0,this._globalTripletFeel=R.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map}get name(){return"Guitar Pro 3-5"}readScore(){return this.readVersion(),this._score=new Me,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=Je.gpReadBool(this.data)?R.Triplet8th:R.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=Je.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=ze.readInt32LE(this.data),this._versionNumber>=510&&Je.gpReadBool(this.data),ze.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=ze.readInt32LE(this.data),this._trackCount=ze.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=oe.buildTempoAutomation(!1,0,this._score.tempo,2),this._score.masterBars[0].tempoAutomation.text=this._score.tempoLabel),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readVersion(){let e=Je.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(qe.VersionString))throw new ne("Unsupported format");e=e.substr(qe.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),ge.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){var e;this._score.title=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let t=ze.readInt32LE(this.data),i="";for(let s=0;s<t;s++)s>0&&(i+="\r\n"),i+=null===(e=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding))||void 0===e?void 0:e.toString();this._score.notices=i}readLyrics(){this._lyrics=[],this._lyricsTrack=ze.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new Ee;e.startBar=ze.readInt32LE(this.data)-1,e.text=Je.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)Je.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Ae;t.primaryChannel=e,t.secondaryChannel=e,t.program=ze.readInt32LE(this.data),t.volume=this.data.readByte(),t.balance=this.data.readByte(),this.data.skip(6),this._playbackInfos.push(t)}}readMasterBars(){for(let e=0;e<this._barCount;e++)this.readMasterBar()}readMasterBar(){let e=null;this._score.masterBars.length>0&&(e=this._score.masterBars[this._score.masterBars.length-1]);let t=new Ce,i=this.data.readByte();if(0!=(1&i)?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),0!=(2&i)?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=0!=(4&i),0!=(8&i)&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),0!=(16&i))if(this._versionNumber<500){let i=e,s=0;for(;i&&(!i.isRepeatEnd||i===e)&&!i.isRepeatStart;)s|=i.alternateEndings,i=i.previousMasterBar;let a=0,r=this.data.readByte();for(let e=0;e<8;e++){let t=1<<e;r>e&&0==(s&t)&&(a|=t)}t.alternateEndings=a}else t.alternateEndings=this.data.readByte();if(0!=(32&i)){let e=new De;e.text=Je.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",Je.gpReadColor(this.data,!1),t.section=e}if(0!=(64&i)?(t.keySignature=ze.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&0!=(3&i)&&this.data.skip(4),this._versionNumber>=500&&0==(16&i)&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=R.Triplet8th;break;case 2:t.tripletFeel=R.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=0!=(128&i),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new He;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],i=this.data.readByte();e.name=Je.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),0!=(1&i)&&(t.isPercussion=!0);let s=ze.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=ze.readInt32LE(this.data);s>e&&a.push(t)}t.stringTuning.tunings=a;let r=ze.readInt32LE(this.data),n=ze.readInt32LE(this.data)-1,o=ze.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){let s=this._playbackInfos[n];s.port=r,s.isSolo=0!=(16&i),s.isMute=0!=(32&i),s.secondaryChannel=o,se.isGuitar(s.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=s}t.capo=ze.readInt32LE(this.data),e.color=Je.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),Je.gpReadStringIntByte(this.data,this.settings.importer.encoding),Je.gpReadStringIntByte(this.data,this.settings.importer.encoding))}readBars(){for(let e=0;e<this._barCount;e++)for(let e=0;e<this._trackCount;e++)this.readBar(this._score.tracks[e])}readBar(e){let t=new he,i=e.staves[0];i.isPercussion&&(t.clef=n.Neutral),i.addBar(t);let s=1;this._versionNumber>=500&&(this.data.readByte(),s=2);for(let i=0;i<s;i++)this.readVoice(e,t)}readVoice(e,t){let i=ze.readInt32LE(this.data);if(0===i)return;let s=new Ve;t.addVoice(s);for(let a=0;a<i;a++)this.readBeat(e,t,s)}readBeat(e,t,i){let s=new xe,a=this.data.readByte();if(0!=(1&a)&&(s.dots=1),0!=(64&a)){let e=this.data.readByte();s.isEmpty=0==(2&e)}switch(i.addBeat(s),ze.readSInt8(this.data)){case-2:s.duration=p.Whole;break;case-1:s.duration=p.Half;break;case 0:s.duration=p.Quarter;break;case 1:s.duration=p.Eighth;break;case 2:s.duration=p.Sixteenth;break;case 3:s.duration=p.ThirtySecond;break;case 4:s.duration=p.SixtyFourth;break;default:s.duration=p.Quarter}if(0!=(32&a))switch(s.tupletNumerator=ze.readInt32LE(this.data),s.tupletNumerator){case 1:s.tupletDenominator=1;break;case 3:s.tupletDenominator=2;break;case 5:case 6:case 7:s.tupletDenominator=4;break;case 9:case 10:case 11:case 12:case 13:s.tupletDenominator=8;break;case 2:case 4:case 8:break;default:s.tupletNumerator=1,s.tupletDenominator=1}0!=(2&a)&&this.readChord(s);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(0!=(4&a)){const t=Je.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const i=new Ee;i.text=t.trim(),i.finish(!0);const s=[];for(let e=i.chunks.length-1;e>=0;e--)s.push(i.chunks[e]);this._beatTextChunksByTrack.set(e.index,s)}else s.text=t}let n=y.None;0!=(8&a)&&(n=this.readBeatEffects(s)),0!=(16&a)&&this.readMixTableChange(s);let o=this.data.readByte();for(let a=6;a>=0;a--)if(0!=(o&1<<a)&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,i,s,6-a);n!==y.None&&(r.harmonicType=n,r.harmonicType===y.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),0!=(8&this.data.readByte())&&this.data.readByte()}r&&!s.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(s.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){let t=new Pe,i=me.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=Je.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=ze.readInt32LE(this.data);for(let i=0;i<7;i++){let s=ze.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}let i=this.data.readByte(),s=new Uint8Array(5);this.data.read(s,0,s.length);for(let e=0;e<i;e++)t.barreFrets.push(s[e]);this.data.skip(26)}else if(0!==this.data.readByte())if(this._versionNumber>=400){this.data.skip(16),t.name=Je.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=ze.readInt32LE(this.data);for(let i=0;i<7;i++){let s=ze.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}let i=this.data.readByte(),s=new Uint8Array(5);this.data.read(s,0,s.length);for(let e=0;e<i;e++)t.barreFrets.push(s[e]);this.data.skip(26)}else{this.data.skip(25),t.name=Je.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=ze.readInt32LE(this.data);for(let i=0;i<6;i++){let s=ze.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}this.data.skip(36)}else{let i=this._versionNumber>=406?7:6;if(t.name=Je.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=ze.readInt32LE(this.data),t.firstFret>0)for(let s=0;s<i;s++){let i=ze.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}}t.name&&(e.chordId=i,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){let t=this.data.readByte(),i=0;if(this._versionNumber>=400&&(i=this.data.readByte()),e.fadeIn=0!=(16&t),(this._versionNumber<400&&0!=(1&t)||0!=(2&t))&&(e.vibrato=w.Slight),e.hasRasgueado=0!=(1&i),0!=(32&t)&&this._versionNumber>=400){switch(ze.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(0!=(32&t)){switch(ze.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(0!=(4&i)&&this.readTremoloBarEffect(e),0!=(64&t)){let t=0,i=0;this._versionNumber<500?(i=this.data.readByte(),t=this.data.readByte()):(t=this.data.readByte(),i=this.data.readByte()),t>0?(e.brushType=c.BrushUp,e.brushDuration=qe.toStrokeValue(t)):i>0&&(e.brushType=c.BrushDown,e.brushDuration=qe.toStrokeValue(i))}if(0!=(2&i))switch(ze.readSInt8(this.data)){case 0:e.pickStroke=x.None;break;case 1:e.pickStroke=x.Up;break;case 2:e.pickStroke=x.Down}if(this._versionNumber<400){if(0!=(4&t))return y.Natural;if(0!=(8&t))return y.Artificial}return y.None}readTremoloBarEffect(e){this.data.readByte(),ze.readInt32LE(this.data);let t=ze.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new de(0,0);t.offset=ze.readInt32LE(this.data),t.value=ze.readInt32LE(this.data)/qe.BendStep|0,Je.gpReadBool(this.data),e.addWhammyBarPoint(t)}}static toStrokeValue(e){switch(e){case 1:case 2:return 30;case 3:return 60;case 4:return 120;case 5:return 240;case 6:return 480;default:return 0}}readMixTableChange(e){let t=new je;t.instrument=ze.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=ze.readSInt8(this.data),t.balance=ze.readSInt8(this.data);let i=ze.readSInt8(this.data),s=ze.readSInt8(this.data),a=ze.readSInt8(this.data),n=ze.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=Je.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=ze.readInt32LE(this.data),t.volume>=0&&this.data.readByte(),t.balance>=0&&this.data.readByte(),i>=0&&this.data.readByte(),s>=0&&this.data.readByte(),a>=0&&this.data.readByte(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=ze.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(Je.gpReadStringIntByte(this.data,this.settings.importer.encoding),Je.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let i=new oe;i.isLinear=!0,i.type=r.Volume,i.value=t.volume,e.automations.push(i)}if(t.balance>=0){let i=new oe;i.isLinear=!0,i.type=r.Balance,i.value=t.balance,e.automations.push(i)}if(t.instrument>=0){let i=new oe;i.isLinear=!0,i.type=r.Instrument,i.value=t.instrument,e.automations.push(i)}if(t.tempo>=0){let i=new oe;i.isLinear=!0,i.type=r.Tempo,i.value=t.tempo,e.automations.push(i),e.voice.bar.masterBar.tempoAutomation=i}}readNote(e,t,i,s,r){let n=new _e;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(0!=(2&o)?n.accentuated=a.Heavy:0!=(64&o)&&(n.accentuated=a.Normal),n.isGhost=0!=(4&o),0!=(32&o)){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(0!=(1&o)&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),0!=(16&o)){let e=ze.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),s.dynamics=n.dynamics}0!=(32&o)&&(n.fret=ze.readSInt8(this.data)),0!=(128&o)&&(n.leftHandFinger=ze.readSInt8(this.data),n.rightHandFinger=ze.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){0!=(1&o)&&(n.durationPercent=Je.gpReadDouble(this.data)),h=0!=(2&this.data.readByte())}if(s.addNote(n),0!=(8&o)&&this.readNoteEffects(e,i,s,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=Oe.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=b.ForceFlat:"b"===e&&(n.accidentalMode=b.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return g.PPP;case 2:return g.PP;case 3:return g.P;case 4:return g.MP;case 5:return g.MF;case 6:default:return g.F;case 7:return g.FF;case 8:return g.FFF}}readNoteEffects(e,t,i,s){let a=this.data.readByte(),r=0;this._versionNumber>=400&&(r=this.data.readByte()),0!=(1&a)&&this.readBend(s),0!=(16&a)&&this.readGrace(t,s),0!=(4&r)&&this.readTremoloPicking(i),0!=(8&r)?this.readSlide(s):this._versionNumber<400&&0!=(4&a)&&(s.slideOutType=_.Shift),0!=(16&r)&&this.readArtificialHarmonic(s),0!=(32&r)&&this.readTrill(s),s.isLetRing=0!=(8&a),s.isHammerPullOrigin=0!=(2&a),0!=(64&r)&&(s.vibrato=w.Slight),s.isPalmMute=0!=(2&r),s.isStaccato=0!=(1&r)}readBend(e){this.data.readByte(),ze.readInt32LE(this.data);let t=ze.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new de(0,0);t.offset=ze.readInt32LE(this.data),t.value=ze.readInt32LE(this.data)/qe.BendStep|0,Je.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let i=new xe,s=new _e;switch(s.string=t.string,s.fret=ze.readSInt8(this.data),i.duration=p.ThirtySecond,i.dynamics=this.toDynamicValue(ze.readSInt8(this.data)),ze.readSInt8(this.data)){case 0:case 2:break;case 1:s.slideOutType=_.Legato,s.slideTarget=t;break;case 3:s.isHammerPullOrigin=!0}if(s.dynamics=i.dynamics,this.data.skip(1),this._versionNumber<500)i.graceType=f.BeforeBeat;else{let e=this.data.readByte();s.isDead=0!=(1&e),i.graceType=0!=(2&e)?f.OnBeat:f.BeforeBeat}e.addGraceBeat(i),i.addNote(s)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=p.Eighth;break;case 2:e.tremoloSpeed=p.Sixteenth;break;case 3:e.tremoloSpeed=p.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=ze.readSInt8(this.data);0!=(1&t)?e.slideOutType=_.Shift:0!=(2&t)?e.slideOutType=_.Legato:0!=(4&t)?e.slideOutType=_.OutDown:0!=(8&t)&&(e.slideOutType=_.OutUp),0!=(16&t)?e.slideInType=S.IntoFromBelow:0!=(32&t)&&(e.slideInType=S.IntoFromAbove)}else{switch(ze.readSInt8(this.data)){case 1:e.slideOutType=_.Shift;break;case 2:e.slideOutType=_.Legato;break;case 3:e.slideOutType=_.OutDown;break;case 4:e.slideOutType=_.OutUp;break;case-1:e.slideInType=S.IntoFromBelow;break;case-2:e.slideInType=S.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=y.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=y.Artificial;break;case 3:e.harmonicType=y.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=y.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=y.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=y.Natural;break;case 3:e.harmonicType=y.Tap;break;case 4:e.harmonicType=y.Pinch;break;case 5:e.harmonicType=y.Semi;break;case 15:case 17:case 22:e.harmonicType=y.Artificial}}deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=p.Sixteenth;break;case 2:e.trillSpeed=p.ThirtySecond;break;case 3:e.trillSpeed=p.SixtyFourth}}}qe.VersionString="FICHIER GUITAR PRO ",qe.BendStep=25;class Je{static gpReadDouble(e){let t=new Uint8Array(8);return e.read(t,0,t.length),new Float64Array(t.buffer)[0]}static gpReadFloat(e){let t=new Uint8Array(4);return t[3]=e.readByte(),t[2]=e.readByte(),t[2]=e.readByte(),t[1]=e.readByte(),new Float32Array(t.buffer)[0]}static gpReadColor(e,t=!1){let i=e.readByte(),s=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new Re(i,s,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),Je.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return Je.gpReadString(e,ze.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let i=ze.readInt32LE(e)-1;return e.readByte(),Je.gpReadString(e,i,t)}static gpReadString(e,t,i){let s=new Uint8Array(t);return e.read(s,0,s.length),ze.toString(s,i)}static gpWriteString(e,t){const i=ze.stringToBytes(t);e.writeByte(t.length),e.write(i,0,i.length)}static gpReadStringByteLength(e,t,i){let s=e.readByte(),a=Je.gpReadString(e,s,i);return s<t&&e.skip(t-s),a}}class je{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class Qe{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(O||(O={}));class $e{constructor(e){this.raw=new Map;let t=Ue.fromBuffer(e),i=ze.readInt32BE(t);for(let e=0;e<i;e++){let e=Je.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case O.Boolean:let i=1===t.readByte();this.addValue(e,i);break;case O.Integer:let s=ze.readInt32BE(t);this.addValue(e,s);break;case O.Float:let a=Je.gpReadFloat(t);this.addValue(e,a);break;case O.String:let r=Je.gpReadString(t,ze.readInt16BE(t),"utf-8");this.addValue(e,r);break;case O.Point:let n=ze.readInt32BE(t),o=ze.readInt32BE(t);this.addValue(e,new de(n,o));break;case O.Size:let h=ze.readInt32BE(t),l=ze.readInt32BE(t);this.addValue(e,new de(h,l));break;case O.Rectangle:let d=new Qe;d.x=ze.readInt32BE(t),d.y=ze.readInt32BE(t),d.w=ze.readInt32BE(t),d.h=ze.readInt32BE(t),this.addValue(e,d);break;case O.Color:let c=Je.gpReadColor(t,!0);this.addValue(e,c)}}}apply(e){for(const[t,i]of this.raw)if("StandardNotation/hideDynamics"===t)e.stylesheet.hideDynamics=i}addValue(e,t){this.raw.set(e,t)}static writeForScore(e){const t=Ue.withCapacity(128);return ze.writeInt32BE(t,1),$e.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,i){Je.gpWriteString(e,t),e.writeByte(O.Boolean),e.writeByte(i?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(G||(G={}));class Ke{constructor(){this.type=G.Short,this.length=0}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(H||(H={}));class Ze{constructor(){this.nodeType=H.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==H.Element&&e.nodeType!==H.CDATA||(this.firstElement=e)}getAttribute(e){return this.attributes.has(e)?this.attributes.get(e):""}getElementsByTagName(e,t=!1){let i=[];return this.searchElementsByTagName(this.childNodes,i,e,t),i}searchElementsByTagName(e,t,i,s=!1){for(let a of e)a&&a.nodeType===H.Element&&a.localName===i&&t.push(a),s&&this.searchElementsByTagName(a.childNodes,t,i,!0)}findChildElement(e){for(let t of this.childNodes)if(t&&t.nodeType===H.Element&&t.localName===e)return t;return null}addElement(e){const t=new Ze;return t.nodeType=H.Element,t.localName=e,this.addChild(t),t}get innerText(){var e,t;if(this.nodeType===H.Element||this.nodeType===H.Document){if(this.firstElement&&this.firstElement.nodeType===H.CDATA)return this.firstElement.innerText;let t="";for(let i of this.childNodes)t+=null===(e=i.innerText)||void 0===e?void 0:e.toString();return t.trim()}return null!==(t=this.value)&&void 0!==t?t:""}set innerText(e){const t=new Ze;t.nodeType=H.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new Ze;t.nodeType=H.CDATA,t.value=e,this.childNodes=[t]}}class et extends re{constructor(t,i,s){super(e.AlphaTabErrorType.Format,t),this.pos=0,this.xml=i,this.pos=s,Object.setPrototypeOf(this,et.prototype)}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.BeginNode=2]="BeginNode",e[e.TagName=3]="TagName",e[e.Body=4]="Body",e[e.AttribName=5]="AttribName",e[e.Equals=6]="Equals",e[e.AttvalBegin=7]="AttvalBegin",e[e.AttribVal=8]="AttribVal",e[e.Childs=9]="Childs",e[e.Close=10]="Close",e[e.WaitEnd=11]="WaitEnd",e[e.WaitEndRet=12]="WaitEndRet",e[e.Pcdata=13]="Pcdata",e[e.Header=14]="Header",e[e.Comment=15]="Comment",e[e.Doctype=16]="Doctype",e[e.Cdata=17]="Cdata",e[e.Escape=18]="Escape"}(V||(V={}));class tt{static parse(e,t,i){var s;let a=e.charCodeAt(t),r=V.Begin,n=V.Begin,o=0,h="",l=V.Begin,d=null,c=null,u=0,p=0;for(;t<e.length;){switch(a=e.charCodeAt(t),r){case V.IgnoreSpaces:switch(a){case tt.CharCodeLF:case tt.CharCodeCR:case tt.CharCodeTab:case tt.CharCodeSpace:break;default:r=n;continue}break;case V.Begin:if(a!==tt.CharCodeLowerThan){o=t,r=V.Pcdata;continue}r=V.IgnoreSpaces,n=V.BeginNode;break;case V.Pcdata:if(a===tt.CharCodeLowerThan){h+=e.substr(o,t-o);let s=new Ze;s.nodeType=H.Text,s.value=h,h="",i.addChild(s),r=V.IgnoreSpaces,n=V.BeginNode}else a===tt.CharCodeAmp&&(h+=e.substr(o,t-o),r=V.Escape,l=V.Pcdata,o=t+1);break;case V.Cdata:if(a===tt.CharCodeBrackedClose&&e.charCodeAt(t+1)===tt.CharCodeBrackedClose&&e.charCodeAt(t+2)===tt.CharCodeGreaterThan){let s=new Ze;s.nodeType=H.CDATA,s.value=e.substr(o,t-o),i.addChild(s),t+=2,r=V.Begin}break;case V.BeginNode:switch(a){case tt.CharCodeExclamation:if(e.charCodeAt(t+1)===tt.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new et("Expected <![CDATA[",e,t);t+=5,r=V.Cdata,o=t+1}else if(e.charCodeAt(t+1)===tt.CharCodeUpperD||e.charCodeAt(t+1)===tt.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new et("Expected <!DOCTYPE",e,t);t+=8,r=V.Doctype,o=t+1}else{if(e.charCodeAt(t+1)!==tt.CharCodeMinus||e.charCodeAt(t+2)!==tt.CharCodeMinus)throw new et("Expected \x3c!--",e,t);t+=2,r=V.Comment,o=t+1}break;case tt.CharCodeQuestion:r=V.Header,o=t;break;case tt.CharCodeSlash:if(!i)throw new et("Expected node name",e,t);o=t+1,r=V.IgnoreSpaces,n=V.Close;break;default:r=V.TagName,o=t;continue}break;case V.TagName:if(!tt.isValidChar(a)){if(t===o)throw new et("Expected node name",e,t);d=new Ze,d.nodeType=H.Element,d.localName=e.substr(o,t-o),i.addChild(d),r=V.IgnoreSpaces,n=V.Body;continue}break;case V.Body:switch(a){case tt.CharCodeSlash:r=V.WaitEnd;break;case tt.CharCodeGreaterThan:r=V.Childs;break;default:r=V.AttribName,o=t;continue}break;case V.AttribName:if(!tt.isValidChar(a)){if(o===t)throw new et("Expected attribute name",e,t);if(c=e.substr(o,t-o),d.attributes.has(c))throw new et(`Duplicate attribute [${c}]`,e,t);r=V.IgnoreSpaces,n=V.Equals;continue}break;case V.Equals:if(a!==tt.CharCodeEquals)throw new et("Expected =",e,t);r=V.IgnoreSpaces,n=V.AttvalBegin;break;case V.AttvalBegin:switch(a){case tt.CharCodeDoubleQuote:case tt.CharCodeSingleQuote:h="",r=V.AttribVal,o=t+1,p=a}break;case V.AttribVal:if(a===tt.CharCodeAmp)h+=e.substr(o,t-o),r=V.Escape,l=V.AttribVal,o=t+1;else if(a===p){h+=e.substr(o,t-o);let i=h;h="",d.attributes.set(c,i),r=V.IgnoreSpaces,n=V.Body}break;case V.Childs:o=t=tt.parse(e,t,d),r=V.Begin;break;case V.WaitEnd:if(a!==tt.CharCodeGreaterThan)throw new et("Expected >",e,t);r=V.Begin;break;case V.WaitEndRet:if(a===tt.CharCodeGreaterThan)return t;throw new et("Expected >",e,t);case V.Close:if(!tt.isValidChar(a)){if(o===t)throw new et("Expected node name",e,t);if(e.substr(o,t-o)!==i.localName)throw new et("Expected </"+i.localName+">",e,t);r=V.IgnoreSpaces,n=V.WaitEndRet;continue}break;case V.Comment:a===tt.CharCodeMinus&&e.charCodeAt(t+1)===tt.CharCodeMinus&&e.charCodeAt(t+2)===tt.CharCodeGreaterThan&&(t+=2,r=V.Begin);break;case V.Doctype:if(a===tt.CharCodeBrackedOpen)u++;else if(a===tt.CharCodeBrackedClose)u--;else if(a===tt.CharCodeGreaterThan&&0===u){let s=new Ze;s.nodeType=H.DocumentType,s.value=e.substr(o,t-o),i.addChild(s),r=V.Begin}break;case V.Header:a===tt.CharCodeQuestion&&e.charCodeAt(t+1)===tt.CharCodeGreaterThan&&(t++,r=V.Begin);break;case V.Escape:if(a===tt.CharCodeSemi){let i=e.substr(o,t-o);if(i.charCodeAt(0)===tt.CharCodeSharp){let e=i.charCodeAt(1)===tt.CharCodeLowerX?parseInt("0"+i.substr(1,i.length-1)):parseInt(i.substr(1,i.length-1));h+=String.fromCharCode(e)}else tt.Escapes.has(i)?h+=tt.Escapes.get(i):h+=null===(s="&"+i+";")||void 0===s?void 0:s.toString();o=t+1,r=l}else tt.isValidChar(a)||a===tt.CharCodeSharp||(h+="&",h+=e.substr(o,t-o),o=--t+1,r=l)}t++}if(r===V.Begin&&(o=t,r=V.Pcdata),r===V.Pcdata){if(t!==o){h+=e.substr(o,t-o);let s=new Ze;s.nodeType=H.Text,s.value=h,i.addChild(s)}return t}if(r===V.Escape&&l===V.Pcdata){h+="&",h+=e.substr(o,t-o);let s=new Ze;return s.nodeType=H.Text,s.value=h,i.addChild(s),t}throw new et("Unexpected end",e,t)}static isValidChar(e){return e>=tt.CharCodeLowerA&&e<=tt.CharCodeLowerZ||e>=tt.CharCodeUpperA&&e<=tt.CharCodeUpperZ||e>=tt.CharCode0&&e<=tt.CharCode9||e===tt.CharCodeColon||e===tt.CharCodeDot||e===tt.CharCodeUnderscore||e===tt.CharCodeMinus}}tt.CharCodeLF=10,tt.CharCodeTab=9,tt.CharCodeCR=13,tt.CharCodeSpace=32,tt.CharCodeLowerThan=60,tt.CharCodeAmp=38,tt.CharCodeBrackedClose=93,tt.CharCodeBrackedOpen=91,tt.CharCodeGreaterThan=62,tt.CharCodeExclamation=33,tt.CharCodeUpperD=68,tt.CharCodeLowerD=100,tt.CharCodeMinus=45,tt.CharCodeQuestion=63,tt.CharCodeSlash=47,tt.CharCodeEquals=61,tt.CharCodeDoubleQuote=34,tt.CharCodeSingleQuote=39,tt.CharCodeSharp=35,tt.CharCodeLowerX=120,tt.CharCodeLowerA=97,tt.CharCodeLowerZ=122,tt.CharCodeUpperA=65,tt.CharCodeUpperZ=90,tt.CharCode0=48,tt.CharCode9=57,tt.CharCodeColon=58,tt.CharCodeDot=46,tt.CharCodeUnderscore=95,tt.CharCodeSemi=59,tt.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class it{constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}static write(e,t,i){const s=new it(t,i);return s.writeNode(e),s.toString()}writeNode(e){switch(e.nodeType){case H.None:break;case H.Element:this._result.length>0&&this.writeLine(),this.write(`<${e.localName}`);for(const[t,i]of e.attributes)this.write(` ${t}="`),this.writeAttributeValue(i),this.write('"');if(0===e.childNodes.length)this.write("/>");else{if(this.write(">"),1!==e.childNodes.length||e.firstElement){this.indent();for(const t of e.childNodes)t.nodeType===H.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case H.Text:e.value&&this.write(e.value);break;case H.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case H.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case H.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const i=e.charAt(t);switch(i){case"<":this._result.push("&lt;");break;case">":this._result.push("&gt;");break;case"&":this._result.push("&amp;");break;case"'":this._result.push("&apos;");break;case'"':this._result.push("&quot;");break;default:this._result.push(i)}}}write(e){this._isStartOfLine&&this._result.push(this._currentIndention),this._result.push(e),this._isStartOfLine=!1}writeLine(e=null){e&&this.write(e),this._indention.length>0&&!this._isStartOfLine&&(this._result.push("\n"),this._isStartOfLine=!0)}toString(){return this._result.join("").trimRight()}}class st extends Ze{constructor(){super(),this.nodeType=H.Document}parse(e){tt.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return it.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(W||(W={}));class at{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=p.Quarter}}class rt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class nt{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;let i=new st;try{i.parse(e)}catch(e){throw new ne("Could not parse XML",e)}if(this.parseDom(i),this.buildModel(),this.score.finish(t),!this._skipApplyLyrics&&this._lyricsByTrack.size>0)for(const[e,t]of this._lyricsByTrack){this._tracksById.get(e).applyLyrics(t)}}parseDom(e){let t=e.firstElement;if(t){if("GPIF"!==t.localName)throw new ne("Root node of XML was not GPIF");this.score=new Me;for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Score":this.parseScoreNode(e);break;case"MasterTrack":this.parseMasterTrackNode(e);break;case"Tracks":this.parseTracksNode(e);break;case"MasterBars":this.parseMasterBarsNode(e);break;case"Bars":this.parseBars(e);break;case"Voices":this.parseVoices(e);break;case"Beats":this.parseBeats(e);break;case"Notes":this.parseNotes(e);break;case"Rhythms":this.parseRhythms(e)}}}parseScoreNode(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Title":this.score.title=t.firstChild.innerText;break;case"SubTitle":this.score.subTitle=t.firstChild.innerText;break;case"Artist":this.score.artist=t.firstChild.innerText;break;case"Album":this.score.album=t.firstChild.innerText;break;case"Words":this.score.words=t.firstChild.innerText;break;case"Music":this.score.music=t.firstChild.innerText;break;case"WordsAndMusic":if(t.firstChild&&""!==t.firstChild.innerText){let e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,i){for(let s of e.childNodes)if(s.nodeType===H.Element&&"Automation"===s.localName)this.parseAutomation(s,t,i)}parseAutomation(e,t,i){let s=null,a=!1,r=-1,n=0,o=0,h=null,l=0,d=null;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Type":s=t.innerText;break;case"Linear":a="true"===t.innerText.toLowerCase();break;case"Bar":r=parseInt(t.innerText);break;case"Position":n=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===H.CDATA)h=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(o=parseFloat(e[0]),l=1):(o=parseFloat(e[0]),l=parseInt(e[1]))}break;case"Text":d=t.innerText}if(!s)return;let c=null;switch(s){case"Tempo":c=oe.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&i&&i.has(h)&&(c=oe.buildInstrumentAutomation(a,n,i.get(h).program))}c&&(d&&(c.text=d),r>=0&&(t.has(r)||t.set(r,[]),t.get(r).push(c)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new He;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Name":t.name=s.innerText;break;case"Color":let e=s.innerText.split(" ");if(e.length>=3){let i=parseInt(e[0]),s=parseInt(e[1]),a=parseInt(e[2]);t.color=new Re(i,s,a,255)}break;case"Instrument":let a=s.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,s);break;case"NotationPatch":this.parseNotationPatch(t,s);break;case"ShortName":t.shortName=s.innerText;break;case"Lyrics":this.parseLyrics(i,s);break;case"Properties":this.parseTrackProperties(t,s);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,s);break;case"Sounds":this.parseSounds(i,t,s);break;case"PlaybackState":let r=s.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,s);break;case"Staves":this.parseStaves(t,s);break;case"Transpose":this.parseTranspose(t,s);break;case"RSE":this.parseRSE(t,s);break;case"Automations":this.parseTrackAutomations(i,s)}this._tracksById.set(i,t)}parseTrackAutomations(e,t){const i=new Map;this._automationsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,i,this._soundsByTrack.get(e))}parseNotationPatch(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"LineCount":const t=parseInt(i.innerText);for(let i of e.staves)i.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,i)}}parseInstrumentSet(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Type":if("drumKit"===i.innerText)for(let t of e.staves)t.isPercussion=!0;if("drumKit"===i.innerText)for(let t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,i);break;case"LineCount":const t=parseInt(i.innerText);for(let i of e.staves)i.standardNotationLineCount=t}}parseElements(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"Element"===i.localName)this.parseElement(e,i)}parseElement(e,t){const i=t.findChildElement("Type"),s=i?i.innerText:"";for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Name":case"Articulations":this.parseArticulations(e,i,s)}}parseArticulations(e,t,i){for(let s of t.childNodes)if(s.nodeType===H.Element&&"Articulation"===s.localName)this.parseArticulation(e,s,i)}parseArticulation(e,t,i){const s=new ye;s.outputMidiNumber=-1,s.elementType=i;let a="";for(let e of t.childNodes)if(e.nodeType===H.Element){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(s.outputMidiNumber=parseInt(t));break;case"TechniqueSymbol":s.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":s.techniqueSymbolPlacement=C.Bottom;break;case"inside":s.techniqueSymbolPlacement=C.Middle;break;case"below":s.techniqueSymbolPlacement=C.Top}break;case"Noteheads":const i=t.split(" ");i.length>=1&&(s.noteHeadDefault=this.parseNoteHead(i[0])),i.length>=2&&(s.noteHeadHalf=this.parseNoteHead(i[1])),i.length>=3&&(s.noteHeadWhole=this.parseNoteHead(i[2])),s.noteHeadHalf==P.None&&(s.noteHeadHalf=s.noteHeadDefault),s.noteHeadWhole==P.None&&(s.noteHeadWhole=s.noteHeadDefault);break;case"StaffLine":t.length>0&&(s.staffLine=parseInt(t))}}-1!==s.outputMidiNumber?(e.percussionArticulations.push(s),a.length>0&&this._articulationByName.set(a,s)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=s.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return P.PictEdgeOfCymbal;case"articStaccatoAbove":return P.ArticStaccatoAbove;case"noteheadParenthesis":return P.NoteheadParenthesis;case"stringsUpBow":return P.StringsUpBow;case"stringsDownBow":return P.StringsDownBow;case"guitarGolpe":return P.GuitarGolpe;default:return P.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return P.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return P.NoteheadDoubleWhole;case"noteheadWhole":return P.NoteheadWhole;case"noteheadHalf":return P.NoteheadHalf;case"noteheadBlack":return P.NoteheadBlack;case"noteheadNull":return P.NoteheadNull;case"noteheadXOrnate":return P.NoteheadXOrnate;case"noteheadTriangleUpWhole":return P.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return P.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return P.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return P.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return P.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return P.NoteheadDiamondWhiteWide;case"noteheadCircleX":return P.NoteheadCircleX;case"noteheadXWhole":return P.NoteheadXWhole;case"noteheadXHalf":return P.NoteheadXHalf;case"noteheadXBlack":return P.NoteheadXBlack;case"noteheadParenthesis":return P.NoteheadParenthesis;case"noteheadSlashedBlack2":return P.NoteheadSlashedBlack2;case"noteheadCircleSlash":return P.NoteheadCircleSlash;case"noteheadHeavyX":return P.NoteheadHeavyX;case"noteheadHeavyXHat":return P.NoteheadHeavyXHat;default:return ge.warning("GPIF","Unknown notehead symbol",e),P.None}}parseStaves(e,t){let i=0;for(let s of t.childNodes)if(s.nodeType===H.Element&&"Staff"===s.localName){e.ensureStaveCount(i+1);let t=e.staves[i];this.parseStaff(t,s),i++}}parseStaff(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"Properties"===i.localName)this.parseStaffProperties(e,i)}parseStaffProperties(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"Property"===i.localName)this.parseStaffProperty(e,i)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Pitches":let s=t.findChildElement("Pitches").innerText.split(" "),a=new Array(s.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=parseInt(s[e]);e.stringTuning.tunings=a;break;case"Label":e.stringTuning.name=i.innerText}e.isPercussion||(e.showTablature=!0);break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForStaff(e,t);break;case"CapoFret":let i=parseInt(t.findChildElement("Fret").innerText);e.capo=i}}parseLyrics(e,t){let i=[];for(let e of t.childNodes)if(e.nodeType===H.Element&&"Line"===e.localName)i.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,i)}parseLyricsLine(e){let t=new Ee;for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Offset":t.startBar=parseInt(i.innerText);break;case"Text":t.text=i.innerText}return t}parseDiagramCollectionForTrack(e,t){let i=t.findChildElement("Items");for(let t of i.childNodes)if(t.nodeType===H.Element&&"Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){let i=t.findChildElement("Items");for(let t of i.childNodes)if(t.nodeType===H.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let i=new Pe,s=t.getAttribute("id");for(let t of e.staves)t.addChord(s,i);this.parseDiagramItemForChord(i,t)}parseDiagramItemForStaff(e,t){let i=new Pe,s=t.getAttribute("id");e.addChord(s,i),this.parseDiagramItemForChord(i,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");let i=t.findChildElement("Diagram"),s=parseInt(i.getAttribute("stringCount")),a=parseInt(i.getAttribute("baseFret"));e.firstFret=a+1;for(let t=0;t<s;t++)e.strings.push(-1);for(let t of i.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"Fret":let i=parseInt(t.getAttribute("string"));e.strings[s-i-1]=a+parseInt(t.getAttribute("fret"));break;case"Fingering":let r=new Map;for(let i of t.childNodes)if(i.nodeType===H.Element&&"Position"===i.localName){let t=m.Unknown,s=a+parseInt(i.getAttribute("fret"));switch(i.getAttribute("finger")){case"Index":t=m.IndexFinger;break;case"Middle":t=m.MiddleFinger;break;case"Rank":t=m.AnnularFinger;break;case"Pinky":t=m.LittleFinger;break;case"Thumb":t=m.Thumb}t!==m.Unknown&&(r.has(t)?e.barreFrets.push(s):r.set(t,!0))}break;case"Property":switch(t.getAttribute("name")){case"ShowName":e.showName="true"===t.getAttribute("value");break;case"ShowDiagram":e.showDiagram="true"===t.getAttribute("value");break;case"ShowFingering":e.showFingering="true"===t.getAttribute("value")}}}parseTrackProperties(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"Property"===i.localName)this.parseTrackProperty(e,i)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":let i=t.findChildElement("Pitches").innerText.split(" "),s=new Array(i.length);for(let e=0;e<s.length;e++)s[s.length-1-e]=parseInt(i[e]);for(let t of e.staves)t.stringTuning.tunings=s,t.showStandardNotation=!0,t.showTablature=!0;break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForTrack(e,t);break;case"CapoFret":let a=parseInt(t.findChildElement("Fret").innerText);for(let t of e.staves)t.capo=a}}parseGeneralMidi(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Program":e.playbackInfo.program=parseInt(i.innerText);break;case"Port":e.playbackInfo.port=parseInt(i.innerText);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=parseInt(i.innerText);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=parseInt(i.innerText)}if("Percussion"===t.getAttribute("table"))for(let t of e.staves)t.isPercussion=!0}parseSounds(e,t,i){for(let s of i.childNodes)if(s.nodeType===H.Element&&"Sound"===s.localName)this.parseSound(e,t,s)}parseSound(e,t,i){const s=new rt;for(let e of i.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Name":s.name=e.innerText;break;case"Path":s.path=e.innerText;break;case"Role":s.role=e.innerText;break;case"MIDI":this.parseSoundMidi(s,e)}"Factory"!==s.role&&0!==t.playbackInfo.program||(t.playbackInfo.program=s.program),this._soundsByTrack.has(e)||this._soundsByTrack.set(e,new Map),this._soundsByTrack.get(e).set(s.uniqueId,s)}parseSoundMidi(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"Program"===i.localName)e.program=parseInt(i.innerText)}parsePartSounding(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"TranspositionPitch"===i.localName)for(let t of e.staves)t.displayTranspositionPitch=parseInt(i.innerText)}parseTranspose(e,t){let i=0,s=0;for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Chromatic":s=parseInt(e.innerText);break;case"Octave":i=parseInt(e.innerText)}for(let t of e.staves)t.displayTranspositionPitch=12*i+s}parseRSE(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"ChannelStrip"===i.localName)this.parseChannelStrip(e,i)}parseChannelStrip(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"Parameters"===i.localName)this.parseChannelStripParameters(e,i)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){let i=t.firstChild.value.split(" ");i.length>=12&&(e.playbackInfo.balance=Math.floor(16*parseFloat(i[11])),e.playbackInfo.volume=Math.floor(16*parseFloat(i[12])))}}parseMasterBarsNode(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new Ce;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"Time":let e=i.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new De,t.section.marker=i.findChildElement("Letter").innerText,t.section.text=i.findChildElement("Text").innerText;break;case"Repeat":"true"===i.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===i.getAttribute("end").toLowerCase()&&i.getAttribute("count")&&(t.repeatCount=parseInt(i.getAttribute("count")));break;case"AlternateEndings":let s=i.innerText.split(" "),a=0;for(let e=0;e<s.length;e++)a|=1<<-1+parseInt(s[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(i.innerText.split(" "));break;case"TripletFeel":switch(i.innerText){case"NoTripletFeel":t.tripletFeel=R.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=R.Triplet8th;break;case"Triplet16th":t.tripletFeel=R.Triplet16th;break;case"Dotted8th":t.tripletFeel=R.Dotted8th;break;case"Dotted16th":t.tripletFeel=R.Dotted16th;break;case"Scottish8th":t.tripletFeel=R.Scottish8th;break;case"Scottish16th":t.tripletFeel=R.Scottish16th}break;case"Key":t.keySignature=parseInt(i.findChildElement("AccidentalCount").innerText);let r=i.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=I.Major;break;case"minor":t.keySignatureType=I.Minor}break;case"Fermatas":this.parseFermatas(t,i)}this._masterBars.push(t)}parseFermatas(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"Fermata"===i.localName)this.parseFermata(e,i)}parseFermata(e,t){let i=0,s=new Ke;for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":s.type=G.Short;break;case"Medium":s.type=G.Medium;break;case"Long":s.type=G.Long}break;case"Length":s.length=parseFloat(e.innerText);break;case"Offset":let t=e.innerText.split("/");if(2===t.length){i=parseInt(t[0])/parseInt(t[1])*le.QuarterTime|0}}e.addFermata(i,s)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new he,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Voices":this._voicesOfBar.set(i,s.innerText.split(" "));break;case"Clef":switch(s.innerText){case"Neutral":t.clef=n.Neutral;break;case"G2":t.clef=n.G2;break;case"F4":t.clef=n.F4;break;case"C4":t.clef=n.C4;break;case"C3":t.clef=n.C3}break;case"Ottavia":switch(s.innerText){case"8va":t.clefOttava=o._8va;break;case"15ma":t.clefOttava=o._15ma;break;case"8vb":t.clefOttava=o._8vb;break;case"15mb":t.clefOttava=o._15mb}break;case"SimileMark":switch(s.innerText){case"Simple":t.simileMark=h.Simple;break;case"FirstOfDouble":t.simileMark=h.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=h.SecondOfDouble}}this._barsById.set(i,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new Ve,i=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===H.Element&&"Beats"===t.localName)this._beatsOfVoice.set(i,t.innerText.split(" "));this._voiceById.set(i,t)}parseBeats(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new xe,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Notes":this._notesOfBeat.set(i,s.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(i,s.getAttribute("ref"));break;case"Fadding":"FadeIn"===s.innerText&&(t.fadeIn=!0);break;case"Tremolo":switch(s.innerText){case"1/2":t.tremoloSpeed=p.Eighth;break;case"1/4":t.tremoloSpeed=p.Sixteenth;break;case"1/8":t.tremoloSpeed=p.ThirtySecond}break;case"Chord":t.chordId=s.innerText;break;case"Hairpin":switch(s.innerText){case"Crescendo":t.crescendo=u.Crescendo;break;case"Decrescendo":t.crescendo=u.Decrescendo}break;case"Arpeggio":"Up"===s.innerText?t.brushType=c.ArpeggioUp:t.brushType=c.ArpeggioDown;break;case"Properties":this.parseBeatProperties(s,t);break;case"XProperties":this.parseBeatXProperties(s,t);break;case"FreeText":t.text=s.innerText;break;case"TransposedPitchStemOrientation":switch(s.innerText){case"Upward":t.preferredBeamDirection=W.Up;break;case"Downward":t.preferredBeamDirection=W.Down}break;case"Dynamic":switch(s.innerText){case"PPP":t.dynamics=g.PPP;break;case"PP":t.dynamics=g.PP;break;case"P":t.dynamics=g.P;break;case"MP":t.dynamics=g.MP;break;case"MF":t.dynamics=g.MF;break;case"F":t.dynamics=g.F;break;case"FF":t.dynamics=g.FF;break;case"FFF":t.dynamics=g.FFF}break;case"GraceNotes":switch(s.innerText){case"OnBeat":t.graceType=f.OnBeat;break;case"BeforeBeat":t.graceType=f.BeforeBeat}break;case"Legato":"true"===s.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new de(0,0);e.value=this.toBendValue(parseFloat(s.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(s.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new de(0,0);a.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new de(0,0);r.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let n=new de(0,0);n.value=this.toBendValue(parseFloat(s.getAttribute("destinationValue"))),n.offset=this.toBendOffset(parseFloat(s.getAttribute("destinationOffset"))),t.addWhammyBarPoint(n);break;case"Ottavia":switch(s.innerText){case"8va":t.ottava=o._8va;break;case"8vb":t.ottava=o._8vb;break;case"15ma":t.ottava=o._15ma;break;case"15mb":t.ottava=o._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(s),this._skipApplyLyrics=!0}this._beatById.set(i,t)}parseBeatLyrics(e){const t=[];for(let i of e.childNodes)if(i.nodeType===H.Element&&"Line"===i.localName)t.push(i.innerText);return t}parseBeatXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element&&"XProperty"===i.localName){let e=0;switch(i.getAttribute("id")){case"1124204545":e=parseInt(i.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(i.findChildElement("Int").innerText),t.brushDuration=e}}}parseBeatProperties(e,t){let i=!1,s=null,a=null,r=null,n=null,o=null;for(let h of e.childNodes)if(h.nodeType===H.Element&&"Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=c.BrushUp:t.brushType=c.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=x.Up:t.pickStroke=x.Down;break;case"Slapped":h.findChildElement("Enable")&&(t.slap=!0);break;case"Popped":h.findChildElement("Enable")&&(t.pop=!0);break;case"VibratoWTremBar":switch(h.findChildElement("Strength").innerText){case"Wide":t.vibrato=w.Wide;break;case"Slight":t.vibrato=w.Slight}break;case"WhammyBar":i=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":s||(s=new de(0,0)),s.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":s||(s=new de(0,0)),s.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleValue":a=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset1":r=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset2":n=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationValue":o||(o=new de(de.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new de(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}i&&(s||(s=new de(0,0)),o||(o=new de(de.MaxPosition,0)),t.addWhammyBarPoint(s),r&&a&&t.addWhammyBarPoint(new de(r,a)),n&&a&&t.addWhammyBarPoint(new de(n,a)),r||n||!a||t.addWhammyBarPoint(new de(de.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new _e,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"Properties":this.parseNoteProperties(s,t,i);break;case"AntiAccent":"normal"===s.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(s.innerText),t.trillSpeed=p.Sixteenth;break;case"Accent":let e=parseInt(s.innerText);0!=(1&e)&&(t.isStaccato=!0),0!=(4&e)&&(t.accentuated=a.Heavy),0!=(8&e)&&(t.accentuated=a.Normal);break;case"Tie":"true"===s.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(s.innerText){case"Slight":t.vibrato=w.Slight;break;case"Wide":t.vibrato=w.Wide}break;case"LeftFingering":switch(t.isFingering=!0,s.innerText){case"P":t.leftHandFinger=m.Thumb;break;case"I":t.leftHandFinger=m.IndexFinger;break;case"M":t.leftHandFinger=m.MiddleFinger;break;case"A":t.leftHandFinger=m.AnnularFinger;break;case"C":t.leftHandFinger=m.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,s.innerText){case"P":t.rightHandFinger=m.Thumb;break;case"I":t.rightHandFinger=m.IndexFinger;break;case"M":t.rightHandFinger=m.MiddleFinger;break;case"A":t.rightHandFinger=m.AnnularFinger;break;case"C":t.rightHandFinger=m.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(s.innerText)}this._noteById.set(i,t)}parseNoteProperties(e,t,i){let s=!1,a=null,r=null,n=null,o=null,h=null,l=-1,d=-1;for(let c of e.childNodes)if(c.nodeType===H.Element&&"Property"===c.localName){switch(c.getAttribute("name")){case"String":t.string=parseInt(c.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(c.findChildElement("Fret").innerText);break;case"Element":l=parseInt(c.findChildElement("Element").innerText);break;case"Variation":d=parseInt(c.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(i,!0);break;case"HarmonicType":let e=c.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=y.None;break;case"Natural":t.harmonicType=y.Natural;break;case"Artificial":t.harmonicType=y.Artificial;break;case"Pinch":t.harmonicType=y.Pinch;break;case"Tap":t.harmonicType=y.Tap;break;case"Semi":t.harmonicType=y.Semi;break;case"Feedback":t.harmonicType=y.Feedback}break;case"HarmonicFret":let u=c.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":c.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":c.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(c.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(c.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(c,t);break;case"Bended":s=!0;break;case"BendOriginValue":a||(a=new de(0,0)),a.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new de(0,0)),a.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new de(de.MaxPosition,0)),h.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new de(0,0)),h.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"HopoOrigin":c.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(c.findChildElement("Flags").innerText);0!=(1&p)?t.slideOutType=_.Shift:0!=(2&p)?t.slideOutType=_.Legato:0!=(4&p)?t.slideOutType=_.OutDown:0!=(8&p)&&(t.slideOutType=_.OutUp),0!=(16&p)?t.slideInType=S.IntoFromBelow:0!=(32&p)&&(t.slideInType=S.IntoFromAbove),0!=(64&p)?t.slideOutType=_.PickSlideDown:0!=(128&p)&&(t.slideOutType=_.PickSlideUp)}}s&&(a||(a=new de(0,0)),h||(h=new de(de.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new de(n,r)),o&&r&&t.addBendPoint(new de(o,r)),n||o||!r||t.addBendPoint(new de(de.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==d&&(t.percussionArticulation=be.articulationFromElementVariation(l,d))}parseConcertPitch(e,t){const i=e.findChildElement("Pitch");if(i)for(let e of i.childNodes)if(e.nodeType===H.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=b.ForceDoubleSharp;break;case"#":t.accidentalMode=b.ForceSharp;break;case"b":t.accidentalMode=b.ForceFlat;break;case"bb":t.accidentalMode=b.ForceDoubleFlat}}toBendValue(e){return e*nt.BendPointValueFactor|0}toBendOffset(e){return e*nt.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new at,i=e.getAttribute("id");t.id=i;for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"NoteValue":switch(i.innerText){case"Long":t.value=p.QuadrupleWhole;break;case"DoubleWhole":t.value=p.DoubleWhole;break;case"Whole":t.value=p.Whole;break;case"Half":t.value=p.Half;break;case"Quarter":t.value=p.Quarter;break;case"Eighth":t.value=p.Eighth;break;case"16th":t.value=p.Sixteenth;break;case"32nd":t.value=p.ThirtySecond;break;case"64th":t.value=p.SixtyFourth;break;case"128th":t.value=p.OneHundredTwentyEighth;break;case"256th":t.value=p.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(i.getAttribute("num")),t.tupletDenominator=parseInt(i.getAttribute("den"));break;case"AugmentationDot":t.dots=parseInt(i.getAttribute("count"))}this._rhythmById.set(i,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){let t=this._masterBars[e];this.score.addMasterBar(t)}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e);this.score.addTrack(t)}for(let e of this._barsOfMasterBar){let t=0;for(let i=0,s=0;i<e.length&&s<this.score.tracks.length;i++){let a=e[i];if(a!==nt.InvalidId){let e=this._barsById.get(a),i=this.score.tracks[s],r=i.staves[t];if(r.addBar(e),this._voicesOfBar.has(a))for(let t of this._voicesOfBar.get(a))if(t!==nt.InvalidId){let i=this._voiceById.get(t);if(e.addVoice(i),this._beatsOfVoice.has(t))for(let e of this._beatsOfVoice.get(t))if(e!==nt.InvalidId){let t=ve.clone(this._beatById.get(e));i.addBeat(t);let s=this._rhythmOfBeat.get(e),a=this._rhythmById.get(s);if(t.duration=a.value,t.dots=a.dots,t.tupletNumerator=a.tupletNumerator,t.tupletDenominator=a.tupletDenominator,this._notesOfBeat.has(e))for(let i of this._notesOfBeat.get(e))if(i!==nt.InvalidId){const e=Te.clone(this._noteById.get(i));r.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(i)&&(t.tap=!0)}}}else{let t=new Ve;e.addVoice(t);let i=new xe;i.isEmpty=!0,i.duration=p.Quarter,t.addBeat(i)}t===i.staves.length-1?(s++,t=0):t++}else s++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),i=!1;for(const e of t.staves)if(e.isPercussion){i=!0;break}if(i||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const i=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,s]of i)if(t.staves.length>0&&e<t.staves[0].bars.length){const i=t.staves[0].bars[e];if(i.voices.length>0&&i.voices[0].beats.length>0){const e=i.voices[0].beats[0];for(const t of s)e.automations.push(t)}}}}for(const[e,t]of this._masterTrackAutomations){let i=this.score.masterBars[e];for(let s=0,a=t.length;s<a;s++){let a=t[s];a.type===r.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),i.tempoAutomation=a)}}}}nt.InvalidId="-1",nt.BendPointPositionFactor=de.MaxPosition/100,nt.BendPointValueFactor=.04;class ot{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class ht{constructor(){this.isMultiRest=!1,this.tracks=[]}}class lt{constructor(e){this.parts=[],this.zoomLevel=0,this.layout=0;let t=Ue.fromBuffer(e),i=ze.readInt32BE(t);for(let e=0;e<i;e++){let e=new ht;this.parts.push(e),e.isMultiRest=Je.gpReadBool(t);let i=ze.readInt32BE(t);for(let s=0;s<i;s++){let i=t.readByte();0===i&&(i=1);let s=new ot;s.showStandardNotation=0!=(1&i),s.showTablature=0!=(2&i),s.showSlash=0!=(4&i),e.tracks.push(s)}}}apply(e){let t=0,i=0;for(let s of this.parts)for(let a of s.tracks){if(i<e.tracks.length){let s=e.tracks[i];if(t<s.staves.length){let e=s.staves[t];e.showTablature=a.showTablature,e.showStandardNotation=a.showStandardNotation}}i++,i>=e.tracks.length&&(t++,i=0)}}static writeForScore(e){const t=Ue.withCapacity(128),i=[new ht];for(const t of e.tracks)for(const e of t.staves){const t=new ot;if(t.showStandardNotation=e.showStandardNotation,t.showTablature=e.showTablature,0===e.index)i[0].tracks.push(t);else{let e=new ht;e.tracks.push(t),i.push(e)}}ze.writeInt32BE(t,i.length);for(const e of i){t.writeByte(e.isMultiRest?1:0),ze.writeInt32BE(t,e.tracks.length);for(const i of e.tracks){let e=0;i.showStandardNotation&&(e|=1),i.showTablature&&(e|=2),i.showSlash&&(e|=4),t.writeByte(e)}}return t.toArray()}}class dt{}class ct extends dt{constructor(e){super(),this.n=e}}class ut extends dt{constructor(e,t){super(),this.left=e,this.right=t}}class pt extends dt{constructor(e,t){super(),this.n=e,this.table=t}}class gt{static make(e,t,i,s){let a=[],r=[];if(s>32)throw new Ie("Invalid huffman");for(let e=0;e<s;e++)a.push(0),r.push(0);for(let r=0;r<i;r++){let i=e[r+t];if(i>=s)throw new Ie("Invalid huffman");a[i]++}let n=0;for(let e=1;e<s-1;e++)n=n+a[e]<<1,r[e]=n;let o=new Map;for(let s=0;s<i;s++){let i=e[s+t];if(0!==i){let e=r[i-1];r[i-1]=e+1,o.set(e<<5|i,s)}}return gt.treeCompress(new ut(gt.treeMake(o,s,0,1),gt.treeMake(o,s,1,1)))}static treeMake(e,t,i,s){if(s>t)throw new Ie("Invalid huffman");let a=i<<5|s;return e.has(a)?new ct(e.get(a)):(i<<=1,s+=1,new ut(gt.treeMake(e,t,i,s),gt.treeMake(e,t,1|i,s)))}static treeCompress(e){let t=gt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof ut)return new ut(gt.treeCompress(e.left),gt.treeCompress(e.right));throw new Ie("assert")}let i=1<<t,s=[];for(let e=0;e<i;e++)s.push(new ct(-1));return gt.treeWalk(s,0,0,t,e),new pt(t,s)}static treeWalk(e,t,i,s,a){a instanceof ut&&s>0?(gt.treeWalk(e,t,i+1,s-1,a.left),gt.treeWalk(e,t|1<<i,i+1,s-1,a.right)):e[t]=gt.treeCompress(a)}static treeDepth(e){if(e instanceof ct)return 0;if(e instanceof pt)throw new Ie("assert");if(e instanceof ut){let t=gt.treeDepth(e.left),i=gt.treeDepth(e.right);return 1+(t<i?t:i)}return 0}}!function(e){e[e.Head=0]="Head",e[e.Block=1]="Block",e[e.CData=2]="CData",e[e.Flat=3]="Flat",e[e.Crc=4]="Crc",e[e.Dist=5]="Dist",e[e.DistOne=6]="DistOne",e[e.Done=7]="Done"}(z||(z={}));class ft{constructor(){this.buffer=new Uint8Array(ft.BufferSize),this.pos=0}slide(){let e=new Uint8Array(ft.BufferSize);this.pos-=ft.Size,e.set(this.buffer.subarray(ft.Size,ft.Size+this.pos),0),this.buffer=e}addBytes(e,t,i){this.pos+i>ft.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+i),this.pos),this.pos+=i}addByte(e){this.pos===ft.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}ft.Size=32768,ft.BufferSize=65536;class mt{constructor(e){this._nbits=0,this._bits=0,this._state=z.Block,this._isFinal=!1,this._huffman=mt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new ft,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return gt.make(e,0,288,10)}readBytes(e,t,i){if(this._needed=i,this._outpos=t,this._output=e,i>0)for(;this.inflateLoop(););return i-this._needed}inflateLoop(){switch(this._state){case z.Head:let e=this._input.readByte();if(8!==(15&e))throw new Ie("Invalid data");let t=this._input.readByte(),i=0!=(32&t);if(((e<<8)+t)%31!=0)throw new Ie("Invalid data");if(i)throw new Ie("Unsupported dictionary");return this._state=z.Block,!0;case z.Crc:return this._state=z.Done,!0;case z.Done:return!1;case z.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=ze.readUInt16LE(this._input),ze.readUInt16LE(this._input)!==65535-this._len)throw new Ie("Invalid data");this._state=z.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=mt._fixedHuffman,this._huffdist=null,this._state=z.CData,!0;case 2:let t=this.getBits(5)+257,i=this.getBits(5)+1,s=this.getBits(4)+4;for(let e=0;e<s;e++)this._lengths[mt.CodeLengthsPos[e]]=this.getBits(3);for(let e=s;e<19;e++)this._lengths[mt.CodeLengthsPos[e]]=0;this._huffman=gt.make(this._lengths,0,19,8);let a=[];for(let e=0;e<t+i;e++)a.push(0);return this.inflateLengths(a,t+i),this._huffdist=gt.make(a,t,i,16),this._huffman=gt.make(a,0,t,16),this._state=z.CData,!0;default:throw new Ie("Invalid data")}case z.Flat:{let e=this._len<this._needed?this._len:this._needed,t=ze.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?z.Crc:z.Block),this._needed>0}case z.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=z.CData),this._needed>0}case z.Dist:for(;this._len>0&&this._needed>0;){let e=this._len<this._dist?this._len:this._dist,t=this._needed<e?this._needed:e;this.addDist(this._dist,t),this._len-=t}return 0===this._len&&(this._state=z.CData),this._needed>0;case z.CData:let s=this.applyHuffman(this._huffman);if(s<256)return this.addByte(s),this._needed>0;if(256===s)return this._state=this._isFinal?z.Crc:z.Block,!0;{s=s-257&255;let e=mt.LenExtraBitsTbl[s];if(-1===e)throw new Ie("Invalid data");this._len=mt.LenBaseValTbl[s]+this.getBits(e);let t=this._huffdist,i=t?this.applyHuffman(t):this.getRevBits(5);if(e=mt.DistExtraBitsTbl[i],-1===e)throw new Ie("Invalid data");if(this._dist=mt.DistBaseValTbl[i]+this.getBits(e),this._dist>this._window.available())throw new Ie("Invalid data");return this._state=1===this._dist?z.DistOne:z.Dist,!0}}return!1}addDistOne(e){let t=this._window.getLastChar();for(let i=0;i<e;i++)this.addByte(t)}addByte(e){this._window.addByte(e),this._output[this._outpos]=e,this._needed--,this._outpos++}addDist(e,t){this.addBytes(this._window.buffer,this._window.pos-e,t)}getBit(){0===this._nbits&&(this._nbits=8,this._bits=this._input.readByte());let e=1==(1&this._bits);return this._nbits--,this._bits=this._bits>>1,e}getBits(e){for(;this._nbits<e;)this._bits=this._bits|this._input.readByte()<<this._nbits,this._nbits+=8;let t=this._bits&(1<<e)-1;return this._nbits-=e,this._bits=this._bits>>e,t}getRevBits(e){return 0===e?0:this.getBit()?1<<e-1|this.getRevBits(e-1):this.getRevBits(e-1)}resetBits(){this._bits=0,this._nbits=0}addBytes(e,t,i){this._window.addBytes(e,t,i),this._output.set(e.subarray(t,t+i),this._outpos),this._needed-=i,this._outpos+=i}inflateLengths(e,t){let i=0,s=0;for(;i<t;){let a=this.applyHuffman(this._huffman);switch(a){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:s=a,e[i]=a,i++;break;case 16:let r=i+3+this.getBits(2);if(r>t)throw new Ie("Invalid data");for(;i<r;)e[i]=s,i++;break;case 17:if(i+=3+this.getBits(3),i>t)throw new Ie("Invalid data");break;case 18:if(i+=11+this.getBits(7),i>t)throw new Ie("Invalid data");break;default:throw new Ie("Invalid data")}}}applyHuffman(e){if(e instanceof ct)return e.n;if(e instanceof ut)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof pt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new Ie("Invalid data")}}mt.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],mt.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],mt.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],mt.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],mt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],mt._fixedHuffman=mt.buildFixedHuffman();class yt{constructor(e,t){this.fullName=e;let i=e.lastIndexOf("/");this.fileName=-1===i||i===e.length-1?this.fullName:e.substr(i+1),this.data=t}}yt.OptionalDataDescriptorSignature=134695760,yt.CompressionMethodDeflate=8,yt.LocalFileHeaderSignature=67324752,yt.CentralFileHeaderSignature=33639248,yt.EndOfCentralDirSignature=101010256;class bt{constructor(e){this._readable=e}read(){let e=[];for(;;){let t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){let e=this._readable;if(ze.readInt32LE(e)!==yt.LocalFileHeaderSignature)return null;ze.readUInt16LE(e);let t=ze.readUInt16LE(e),i=ze.readUInt16LE(e),s=0!==i;if(s&&i!==yt.CompressionMethodDeflate)return null;ze.readInt16LE(this._readable),ze.readInt16LE(this._readable),ze.readInt32LE(e),ze.readInt32LE(e);let a,r=ze.readInt32LE(e),n=ze.readInt16LE(e),o=ze.readInt16LE(e),h=ze.toString(ze.readByteArray(e,n),"utf-8");if(e.skip(o),s){let e=Ue.empty(),t=new mt(this._readable),i=new Uint8Array(65536);for(;;){let s=t.readBytes(i,0,i.length);if(e.write(i,0,s),s<i.length)break}a=e.toArray()}else a=ze.readByteArray(this._readable,r);if(0!=(8&t)){ze.readInt32LE(this._readable)===yt.OptionalDataDescriptorSignature&&ze.readInt32LE(this._readable),ze.readInt32LE(this._readable),ze.readInt32LE(this._readable)}return new yt(h,a)}}class St extends ae{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){ge.debug(this.name,"Loading ZIP entries");let e,t=new bt(this.data);try{e=t.read()}catch(e){throw new ne("No Zip archive",e)}ge.debug(this.name,"Zip entries loaded");let i=null,s=null,a=null;for(let t of e)switch(t.fileName){case"score.gpif":i=ze.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=t.data;break;case"PartConfiguration":a=t.data}if(!i)throw new ne("No score.gpif found in zip archive");ge.debug(this.name,"Start Parsing score.gpif");let r=new nt;r.parseXml(i,this.settings),ge.debug(this.name,"score.gpif parsed");let n=r.score;if(s){ge.debug(this.name,"Start Parsing BinaryStylesheet"),new $e(s).apply(n),ge.debug(this.name,"BinaryStylesheet parsed")}if(a){ge.debug(this.name,"Start Parsing Part Configuration"),new lt(a).apply(n),ge.debug(this.name,"Part Configuration parsed")}return n}}class _t extends re{constructor(){super(e.AlphaTabErrorType.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,_t.prototype)}}class wt{constructor(e){this._currentByte=0,this._position=wt.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=255&this.readByte();return t}readBits(e){let t=0,i=e-1;for(;i>=0;)t|=this.readBit()<<i,i--;return t}readBitsReversed(e){let t=0;for(let i=0;i<e;i++)t|=this.readBit()<<i;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new _t;this._position=0}const e=this._currentByte>>wt.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=Ue.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof _t))throw e}return e.toArray()}}wt.ByteSize=8;class Bt{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Tt{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new wt(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let i,s=Ue.empty(),a=this.getInteger(e.readBytes(4),0);try{for(;s.length<a;){if(1===e.readBits(1)){let t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=s.length-a,o=Math.min(a,r);i=s.getBuffer(),s.write(i,n,o)}else{let t=e.readBitsReversed(2);for(let i=0;i<t;i++)s.writeByte(e.readByte())}}}catch(e){if(!(e instanceof _t))throw e}i=s.getBuffer();let r=t?4:0,n=s.length-r,o=new Uint8Array(n),h=n;return o.set(i.subarray(r,r+h),0),o}readBlock(e){let t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new ne("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){let t=4096,i=t;for(;i+3<e.length;){if(2===this.getInteger(e,i)){let s=new Bt;s.fileName=this.getString(e,i+4,127),s.fileSize=this.getInteger(e,i+140);let a=!this.fileFilter||this.fileFilter(s.fileName);a&&this.files.push(s);let r=i+148,n=0,o=0,h=a?Ue.withCapacity(s.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)i=n*t,a&&h.write(e,i,t);if(a){s.data=new Uint8Array(Math.min(s.fileSize,h.length));let e=h.toArray();s.data.set(e.subarray(0,0+s.data.length),0)}}i+=t}}getString(e,t,i){let s="";for(let a=0;a<i;a++){let i=255&e[t+a];if(0===i)break;s+=String.fromCharCode(i)}return s}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}Tt.HeaderBcFs="BCFS",Tt.HeaderBcFz="BCFZ",Tt.ScoreGpif="score.gpif",Tt.BinaryStylesheet="BinaryStylesheet",Tt.PartConfiguration="PartConfiguration";class kt extends ae{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){ge.debug(this.name,"Loading GPX filesystem");let e=new Tt;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),ge.debug(this.name,"GPX filesystem loaded");let t=null,i=null,s=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=ze.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=a.data;break;case"PartConfiguration":s=a.data}if(!t)throw new ne("No score.gpif found in GPX");ge.debug(this.name,"Start Parsing score.gpif");let a=new nt;a.parseXml(t,this.settings),ge.debug(this.name,"score.gpif parsed");let r=a.score;if(i){ge.debug(this.name,"Start Parsing BinaryStylesheet"),new $e(i).apply(r),ge.debug(this.name,"BinaryStylesheet parsed")}if(s){ge.debug(this.name,"Start Parsing Part Configuration"),new lt(s).apply(r),ge.debug(this.name,"Part Configuration parsed")}return r}}class vt extends ae{constructor(){super(),this._currentPartGroup=null,this._trackFirstMeasureNumber=0,this._maxVoices=0,this._currentDirection=null,this._currentChord=null,this._divisionsPerQuarterNote=0,this._voiceOfStaff=new Map,this._isBeamContinue=!1,this._previousBeatWasPulled=!1,this._previousBeat=null}get name(){return"MusicXML"}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=ze.toString(this.data.readAll(),this.settings.importer.encoding),t=new st;try{t.parse(e)}catch(e){throw new ne("Unsupported format")}return this._score=new Me,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let i=1;i<e.length;i++){let s=e[i];for(let e of s.staves)t.addStaff(e);let a=this._score.tracks.indexOf(s);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new ne("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new ne("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"work":this.parseWork(t);break;case"movement-title":this._score.title=t.innerText;break;case"identification":this.parseIdentification(t);break;case"part-list":this.parsePartList(t);break;case"part":this.parsePart(t)}}parseWork(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"work-title"===t.localName)this._score.title=t.innerText}parsePart(e){let t=e.getAttribute("id");if(!this._trackById.has(t)){if(1!==this._trackById.size)return;for(const[e,i]of this._trackById)0!==i.staves.length&&0!==i.staves[0].bars.length||(t=e);if(!this._trackById.has(t))return}let i=this._trackById.get(t),s=!0;this._maxVoices=0;for(let t of e.childNodes)if(t.nodeType===H.Element&&"measure"===t.localName)this.parseMeasure(t,i,s)&&(s=!1);for(let e of i.staves)for(let t of e.bars)this.ensureVoices(t)}parseMeasure(e,t,i){if("yes"===e.getAttribute("implicit")&&0===e.getElementsByTagName("note",!1).length)return!1;let s=0;if(i)this._divisionsPerQuarterNote=0,this._trackFirstMeasureNumber=parseInt(e.getAttribute("number")),this._trackFirstMeasureNumber||(this._trackFirstMeasureNumber=0),s=0;else{if(s=parseInt(e.getAttribute("number")),!s)return!1;s-=this._trackFirstMeasureNumber}if(i){let i=e.getElementsByTagName("attributes",!1);if(i.length>0){let e=i[0].getElementsByTagName("staves",!1);if(e.length>0){let i=parseInt(e[0].innerText);t.ensureStaveCount(i)}}}let a=new Array(t.staves.length),r=null;for(let e=t.staves[0].bars.length;e<=s;e++)for(let e=0;e<t.staves.length;e++){let i=new he;if(a[e]=i,t.staves[e].bars.length>0){let s=t.staves[e].bars[t.staves[e].bars.length-1];i.clef=s.clef}r=this.getOrCreateMasterBar(s),t.staves[e].addBar(i),this.ensureVoices(i)}if(r){let i=!1;for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"note":this.parseNoteBeat(s,a);break;case"forward":this.parseForward(s,a);break;case"direction":this.parseDirection(s,r);break;case"attributes":i||(this.parseAttributes(s,a,r,t),i=!0);break;case"harmony":this.parseHarmony(s,t);break;case"sound":break;case"barline":this.parseBarline(s,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new Ve;e.addVoice(t);let i=new xe;i.isEmpty=!0,i.chordId=this._currentChord,t.addBeat(i)}}getOrCreateBeat(e,t,i){let s=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(s=parseInt(a[0].innerText)-1);let r=this._previousBeatWasPulled;this._previousBeatWasPulled=!1;let n,o,h=e.getElementsByTagName("staff",!1),l=1;if(h.length>0){l=parseInt(h[0].innerText),(this._isBeamContinue||r)&&this._previousBeat.voice.bar.staff.index!==l-1&&(l=this._previousBeat.voice.bar.staff.index+1,this._previousBeatWasPulled=!0);let e=t[0].staff.track.index+"-"+l;this._voiceOfStaff.has(e)||this._voiceOfStaff.set(e,s)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let d=this.getOrCreateVoice(n,s);return i&&d.beats.length>0||1===d.beats.length&&d.isEmpty?o=d.beats[d.beats.length-1]:(o=new xe,o.isEmpty=!1,d.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let i=this.getOrCreateBeat(e,t,!1),s=parseInt(e.findChildElement("duration").innerText)*p.Quarter/this._divisionsPerQuarterNote,a=[p.SixtyFourth,p.ThirtySecond,p.Sixteenth,p.Eighth,p.Quarter,p.Half,p.Whole];for(let e of a)if(s>=e){i.duration=e,s-=e;break}i.isEmpty=!1}parseStaffDetails(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"staff-lines":for(let e of t.staves)e.stringTuning.tunings=new Array(parseInt(i.innerText)).fill(0);break;case"staff-tuning":this.parseStaffTuning(i,t)}for(let e of t.staves)this.isEmptyTuning(e.tuning)&&(e.stringTuning.tunings=[])}parseStaffTuning(e,t){let i=parseInt(e.getAttribute("line")),s="C",a="",r=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"tuning-step":s=t.innerText;break;case"tuning-alter":r=parseInt(t.innerText);break;case"tuning-octave":a=t.innerText}let n=me.getTuningForText(s+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-i]=n}parseHarmony(e,t){let i=null,s="";for(let t of e.childNodes)if(t.nodeType===H.Element&&"root"===t.localName)for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"root-step":i=e.innerText;break;case"root-alter":switch(parseInt(t.innerText)){case-2:s=" bb";break;case-1:s=" b";break;case 0:s="";break;case 1:s=" #";break;case 2:s=" ##"}}let a=new Pe;a.name=i+s,this._currentChord=me.newGuid();for(let e of t.staves)e.addChord(this._currentChord,a)}parseBarline(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"repeat":this.parseRepeat(i,t);break;case"ending":this.parseEnding(i,t)}}parseEnding(e,t){let i=parseInt(e.getAttribute("number"));i>0&&(--i,t.alternateEndings=t.alternateEndings|1<<i&255)}parseRepeat(e,t){let i=e.getAttribute("direction"),s=parseInt(e.getAttribute("times"));(s<0||isNaN(s))&&(s=2),"backward"===i?t.repeatCount=s:"forward"===i&&(t.isRepeatStart=!0)}parseNoteBeat(e,t){let i=e.getElementsByTagName("chord",!1).length>0,s=this.getOrCreateBeat(e,t,i);!s.chordId&&this._currentChord&&(s.chordId=this._currentChord,this._currentChord=null),this._currentDirection&&(s.text=this._currentDirection,this._currentDirection=null);let a=new _e;s.voice.isEmpty=!1,s.isEmpty=!1,s.addNote(a),s.dots=0;let r=!1;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"grace":s.graceType=f.BeforeBeat,s.duration=p.ThirtySecond;break;case"duration":if(s.isRest&&!r){switch(parseInt(t.innerText)){case 1:s.duration=p.Whole;break;case 2:s.duration=p.Half;break;case 4:default:s.duration=p.Quarter;break;case 8:s.duration=p.Eighth;break;case 16:s.duration=p.Sixteenth;break;case 32:s.duration=p.ThirtySecond;break;case 64:s.duration=p.SixtyFourth}}break;case"tie":this.parseTied(t,a);break;case"cue":case"instrument":case"stem":break;case"type":s.duration=this.getDuration(t.innerText),s.graceType!==f.None&&s.duration<p.Sixteenth&&(s.duration=p.Eighth);break;case"dot":s.dots++;break;case"accidental":this.parseAccidental(t,a);break;case"time-modification":this.parseTimeModification(t,s);break;case"notehead":"yes"===t.getAttribute("parentheses")&&(a.isGhost=!0);break;case"beam":"continue"===t.innerText&&(this._isBeamContinue=!0);break;case"notations":this.parseNotations(t,s,a);break;case"lyric":this.parseLyric(t,s);break;case"pitch":this.parsePitch(t,a);break;case"unpitched":this.parseUnpitched(t,a);break;case"rest":r="yes"===t.getAttribute("measure"),s.isEmpty=!1,s.notes=[],s.duration=p.Whole}if(a.isStringed)for(let e=0;e<s.notes.length;e++)if(s.notes[e].string===a.string&&s.notes[e]!==a){s.removeNote(a);break}}getDuration(e){switch(e){case"256th":case"128th":case"64th":return p.SixtyFourth;case"32nd":return p.ThirtySecond;case"16th":return p.Sixteenth;case"eighth":return p.Eighth;case"quarter":return p.Quarter;case"half":return p.Half;case"long":case"breve":case"whole":return p.Whole}return p.Quarter}parseLyric(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element&&"text"===i.localName)t.text?t.text+=" "+i.innerText:t.text=i.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=b.ForceSharp;break;case"natural":t.accidentalMode=b.ForceNatural;break;case"flat":t.accidentalMode=b.ForceFlat}}parseTied(e,t){"start"===e.getAttribute("type")?this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t)):"stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination&&(t.isTieDestination=!0,t.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(t.id))}parseNotations(e,t,i){for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"articulations":this.parseArticulations(s,i);break;case"tied":this.parseTied(s,i);break;case"slide":case"glissando":"start"===s.getAttribute("type")&&(i.slideOutType=_.Shift);break;case"dynamics":this.parseDynamics(s,t);break;case"technical":this.parseTechnical(s,i);break;case"ornaments":this.parseOrnaments(s,i);break;case"slur":let e=s.getAttribute("number");switch(e||(e="1"),e=t.voice.bar.staff.index+"_"+e,s.getAttribute("type")){case"start":this._slurStarts.set(e,i);break;case"stop":if(this._slurStarts.has(e)){i.isSlurDestination=!0;let t=this._slurStarts.get(e);t.slurDestination=i,i.slurOrigin=t}}}}parseOrnaments(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element&&"tremolo"===i.localName){switch(parseInt(i.innerText)){case 1:t.beat.tremoloSpeed=p.Eighth;break;case 2:t.beat.tremoloSpeed=p.Sixteenth;break;case 3:t.beat.tremoloSpeed=p.ThirtySecond}}}parseTechnical(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"string":t.string=parseInt(i.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(i.innerText);break;case"down-bow":t.beat.pickStroke=x.Down;break;case"up-bow":t.beat.pickStroke=x.Up}-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseArticulations(e,t){for(let i of e.childNodes)switch(i.localName){case"accent":t.accentuated=a.Normal;break;case"strong-accent":t.accentuated=a.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"p":t.dynamics=g.P;break;case"pp":t.dynamics=g.PP;break;case"ppp":t.dynamics=g.PPP;break;case"f":t.dynamics=g.F;break;case"ff":t.dynamics=g.FF;break;case"fff":t.dynamics=g.FFF;break;case"mp":t.dynamics=g.MP;break;case"mf":t.dynamics=g.MF}}parseTimeModification(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"actual-notes":t.tupletNumerator=parseInt(i.innerText);break;case"normal-notes":t.tupletDenominator=parseInt(i.innerText)}}parseUnpitched(e,t){let i="",s=0,a=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"display-step":i=t.innerText;break;case"display-alter":s=parseInt(t.innerText);break;case"display-octave":a=parseInt(t.innerText)}let r=12*a+me.getToneForText(i)+s;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let i="",s=0,a=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"step":i=t.innerText;break;case"alter":s=parseFloat(t.innerText),isNaN(s)&&(s=0);break;case"octave":a=parseInt(t.innerText)+1}let r=12*a+me.getToneForText(i)+(0|s);t.octave=r/12|0,t.tone=r-12*t.octave}getOrCreateVoice(e,t){if(t<e.voices.length)return e.voices[t];for(let i=e.voices.length;i<=t;i++)e.addVoice(new Ve);return this._maxVoices=Math.max(this._maxVoices,e.voices.length),e.voices[t]}parseDirection(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"sound":let e=i.getAttribute("tempo");if(e){let i=new oe;i.isLinear=!0,i.type=r.Tempo,i.value=parseInt(e),t.tempoAutomation=i,0===t.index&&(t.score.tempo=i.value)}break;case"direction-type":let s=i.firstElement;switch(s.localName){case"words":this._currentDirection=s.innerText;break;case"metronome":this.parseMetronome(s,t)}}}parseMetronome(e,t){let i=p.Quarter,s=120;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"beat-unit":i=this.getDuration(t.innerText);break;case"per-minute":s=parseInt(t.innerText)}let a=new oe;a.type=r.Tempo,a.value=s*(i/4|0),t.tempoAutomation=a,0===t.index&&(t.score.tempo=a.value)}parseAttributes(e,t,i,s){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===H.Element)switch(n.localName){case"divisions":this._divisionsPerQuarterNote=parseInt(n.innerText);break;case"key":this.parseKey(n,i);break;case"time":this.parseTime(n,i),r=!0;break;case"clef":a=parseInt(n.getAttribute("number")),isNaN(a)&&(a=1),this.parseClef(n,t[a-1]);break;case"staff-details":this.parseStaffDetails(n,s);break;case"transpose":this.parseTranspose(n,s)}r||(i.timeSignatureCommon=!0)}parseTranspose(e,t){let i=0;for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"chromatic":i+=parseInt(t.innerText);break;case"octave-change":i+=12*parseInt(t.innerText)}for(let e of t.staves)e.transpositionPitch=i}parseClef(e,t){let i="s",s=0;for(let a of e.childNodes)if(a.nodeType===H.Element)switch(a.localName){case"sign":i=a.innerText.toLowerCase();break;case"line":s=parseInt(a.innerText);break;case"clef-octave-change":switch(parseInt(a.innerText)){case-2:t.clefOttava=o._15mb;break;case-1:t.clefOttava=o._8vb;break;case 1:t.clefOttava=o._8va;break;case 2:t.clefOttava=o._15mb}}switch(i){case"g":default:t.clef=n.G2;break;case"f":t.clef=n.F4;break;case"c":t.clef=3===s?n.C3:n.C4;break;case"percussion":t.clef=n.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=n.G2,t.staff.showTablature=!0}}parseTime(e,t){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let i=!1,s=!1;for(let a of e.childNodes)if(a.nodeType===H.Element){let e=a.innerText;switch(a.localName){case"beats":i||(-1===e.indexOf("+")?t.timeSignatureNumerator=parseInt(e):t.timeSignatureNumerator=4,i=!0);break;case"beat-type":s||(-1===e.indexOf("+")?t.timeSignatureDenominator=parseInt(e):t.timeSignatureDenominator=4,s=!0)}}}parseKey(e,t){let i=-2147483648,s="";for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"fifths":i=parseInt(t.innerText);break;case"key-step":case"key-alter":break;case"mode":s=t.innerText}t.keySignature=-7<=i&&i<=7?i:M.C,t.keySignatureType="minor"===s?I.Minor:I.Major}getOrCreateMasterBar(e){if(e<this._score.masterBars.length)return this._score.masterBars[e];for(let t=this._score.masterBars.length;t<=e;t++){let e=new Ce;if(this._score.masterBars.length>0){let t=this._score.masterBars[this._score.masterBars.length-1];e.timeSignatureDenominator=t.timeSignatureDenominator,e.timeSignatureNumerator=t.timeSignatureNumerator,e.keySignature=t.keySignature,e.keySignatureType=t.keySignatureType}this._score.addMasterBar(e)}return this._score.masterBars[e]}parseIdentification(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"creator":"composer"===t.getAttribute("type")&&(this._score.music=t.innerText);break;case"rights":this._score.copyright&&(this._score.copyright+="\n"),this._score.copyright+=t.innerText}}parsePartList(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"part-group":this.parsePartGroup(t);break;case"score-part":this.parseScorePart(t)}}parsePartGroup(e){switch(e.getAttribute("type")){case"start":this._currentPartGroup=e.getAttribute("number"),this._partGroups.set(this._currentPartGroup,[]);break;case"stop":this._currentPartGroup=null}}parseScorePart(e){let t=e.getAttribute("id"),i=new He;i.ensureStaveCount(1),i.staves[0].showStandardNotation=!0,this._trackById.set(t,i),this._score.addTrack(i),this._currentPartGroup&&this._partGroups.get(this._currentPartGroup).push(i);for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"part-name":i.name=t.innerText;break;case"part-abbreviation":i.shortName=t.innerText;break;case"midi-instrument":this.parseMidiInstrument(t,i)}this.isEmptyTuning(i.staves[0].tuning)&&(i.staves[0].stringTuning.tunings=[])}isEmptyTuning(e){if(!e)return!0;for(let t=0;t<e.length;t++)if(0!==e[t])return!1;return!0}parseMidiInstrument(e,t){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(i.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(i.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(i.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(i.innerText)+90)/180*16)))}}}!function(e){e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.NoteOff=128]="NoteOff",e[e.NoteOn=144]="NoteOn",e[e.NoteAftertouch=160]="NoteAftertouch",e[e.Controller=176]="Controller",e[e.ProgramChange=192]="ProgramChange",e[e.ChannelAftertouch=208]="ChannelAftertouch",e[e.PitchBend=224]="PitchBend",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(U||(U={}));class Nt{constructor(e,t,i,s,a){this.track=e,this.tick=t,this.message=i|s<<8|a<<16}get channel(){return 15&this.message}get command(){return 240&this.message}get data1(){return(65280&this.message)>>8}set data1(e){this.message&=-65281,this.message|=e<<8}get data2(){return(16711680&this.message)>>16}set data2(e){this.message&=-16711681,this.message|=e<<16}writeTo(e){let t=new Uint8Array([this.message>>24&255,this.message>>16&255,this.message>>8&255,255&this.message]);e.write(t,0,t.length)}}!function(e){e[e.SequenceNumber=0]="SequenceNumber",e[e.TextEvent=1]="TextEvent",e[e.CopyrightNotice=2]="CopyrightNotice",e[e.SequenceOrTrackName=3]="SequenceOrTrackName",e[e.InstrumentName=4]="InstrumentName",e[e.LyricText=5]="LyricText",e[e.MarkerText=6]="MarkerText",e[e.CuePoint=7]="CuePoint",e[e.PatchName=8]="PatchName",e[e.PortName=9]="PortName",e[e.MidiChannel=32]="MidiChannel",e[e.MidiPort=33]="MidiPort",e[e.EndOfTrack=47]="EndOfTrack",e[e.Tempo=81]="Tempo",e[e.SmpteOffset=84]="SmpteOffset",e[e.TimeSignature=88]="TimeSignature",e[e.KeySignature=89]="KeySignature",e[e.SequencerSpecific=127]="SequencerSpecific"}(X||(X={}));class xt extends Nt{get channel(){return-1}get command(){return 255&this.message}get metaStatus(){return this.data1}constructor(e,t,i,s,a){super(e,t,i,s,a)}}!function(e){e[e.SystemExclusive=240]="SystemExclusive",e[e.MtcQuarterFrame=241]="MtcQuarterFrame",e[e.SongPosition=242]="SongPosition",e[e.SongSelect=243]="SongSelect",e[e.TuneRequest=246]="TuneRequest",e[e.SystemExclusive2=247]="SystemExclusive2"}(Y||(Y={}));class Pt extends Nt{get channel(){return-1}get command(){return 255&this.message}constructor(e,t,i,s,a){super(e,t,i,s,a)}}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(q||(q={}));class Et extends Pt{constructor(e,t,i,s,a){super(e,t,i,255&s,s>>8&255),this.data=a}get isMetronome(){return this.manufacturerId==Et.AlphaTabManufacturerId&&this.data[0]==q.MetronomeTick}get metronomeNumerator(){return this.isMetronome?this.data[1]:-1}get metronomeDurationInTicks(){return this.isMetronome?ze.decodeUInt32LE(this.data,2):-1}get metronomeDurationInMilliseconds(){return this.isMetronome?ze.decodeUInt32LE(this.data,6):-1}get isRest(){return this.manufacturerId==Et.AlphaTabManufacturerId&&this.data[0]==q.Rest}get manufacturerId(){return this.message>>8}writeTo(e){e.writeByte(240);let t=this.data.length+2;e.writeByte(this.manufacturerId);let i=new Uint8Array([t>>24&255,t>>16&255,t>>8&255,255&t]);e.write(i,0,i.length),e.writeByte(247)}static encodeMetronome(e,t,i){const s=Ue.withCapacity(10);return s.writeByte(q.MetronomeTick),s.writeByte(e),ze.writeInt32LE(s,t),ze.writeInt32LE(s,i),s.toArray()}}Et.AlphaTabManufacturerId=125;class Ct{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event instanceof Et&&this.event.isMetronome}static newMetronomeEvent(e,t,i,s,a){const r=new Et(0,t,U.SystemExclusive2,Et.AlphaTabManufacturerId,Et.encodeMetronome(i,s,a));return new Ct(e,r)}}class Ft{}Ft.DefaultChannelCount=17,Ft.MetronomeChannel=Ft.DefaultChannelCount-1,Ft.AudioChannels=2,Ft.MinVolume=0,Ft.MinProgram=0,Ft.MaxProgram=127,Ft.MinPlaybackSpeed=.125,Ft.MaxPlaybackSpeed=8,Ft.MaxPitchWheel=16384,Ft.MaxPitchWheel20=4294967296,Ft.DefaultPitchWheel=Ft.MaxPitchWheel/2,Ft.MicroBufferCount=32,Ft.MicroBufferSize=64;class Lt{constructor(e,t,i){this.bpm=e,this.ticks=t,this.time=i}}class Mt{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=le.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Dt{constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this._synthesizer=e,this._mainState=new Mt,this._currentState=this._mainState}get isPlayingMain(){return this._currentState==this._mainState}get isPlayingOneTimeMidi(){return this._currentState==this._oneTimeState}get isPlayingCountIn(){return this._currentState==this._countInState}get mainPlaybackRange(){return this._mainState.playbackRange}set mainPlaybackRange(e){this._mainState.playbackRange=e,e&&(this._mainState.playbackRangeStartTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.startTick,1),this._mainState.playbackRangeEndTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.endTick,1))}get currentTime(){return this._currentState.currentTime/this.playbackSpeed}get currentEndTick(){return this._currentState.endTick}get currentEndTime(){return this._currentState.endTime/this.playbackSpeed}mainSeek(e){if(e*=this.playbackSpeed,this.mainPlaybackRange&&(e<this._mainState.playbackRangeStartTime?e=this._mainState.playbackRangeStartTime:e>this._mainState.playbackRangeEndTime&&(e=this._mainState.playbackRangeEndTime)),e>this._mainState.currentTime)this.mainSilentProcess(e-this._mainState.currentTime);else if(e<this._mainState.currentTime){if(this._mainState.currentTime=0,this._mainState.eventIndex=0,this.isPlayingMain){let e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;let t=Date.now(),i=this._mainState.currentTime+e;if(this.isPlayingMain)for(;this._mainState.currentTime<i;)this.fillMidiEventQueueLimited(i-this._mainState.currentTime)&&this._synthesizer.synthesizeSilent(Ft.MicroBufferSize);this._mainState.currentTime=i;let s=Date.now()-t;ge.debug("Sequencer","Silent seek finished in "+s+"ms (main)")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new Mt;t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let i=120,s=0,a=0,r=0,n=0,o=0,h=0,l=0,d=0;for(let c of e.events){let u=new Ct(t.synthData.length,c);t.synthData.push(u);let p=c.tick-d;if(s+=p,a+=p*(6e4/(i*e.division)),u.time=a,d=c.tick,n>0)for(;h<s;){let e=Ct.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(c.command===U.Meta&&c.data1===X.Tempo){i=6e7/c.value,t.tempoChanges.push(new Lt(i,s,a)),o=n*(6e4/(i*e.division))}else if(c.command===U.Meta&&c.data1===X.TimeSignature){let s=c,a=Math.pow(2,s.data[1]);r=s.data[0],n=t.division*(4/a)|0,o=n*(6e4/(i*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=s.data[0],t.firstTimeSignatureDenominator=a)}else if(c.command===U.ProgramChange){let e=c.channel;t.firstProgramEventPerChannel.has(e)||t.firstProgramEventPerChannel.set(e,u)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=s,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Ft.MicroBufferSize/this._synthesizer.outSampleRate*1e3*this.playbackSpeed,i=this.internalEndTime;e>0&&(e<t&&(t=e),i=Math.min(this.internalEndTime,this._currentState.currentTime+e));let s=!1;for(this._currentState.currentTime+=t;this._currentState.eventIndex<this._currentState.synthData.length&&this._currentState.synthData[this._currentState.eventIndex].time<this._currentState.currentTime&&this._currentState.currentTime<i;)this._synthesizer.dispatchEvent(this._currentState.synthData[this._currentState.eventIndex]),this._currentState.eventIndex++,s=!0;return s}mainTickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(this._mainState,e,this.playbackSpeed)}mainTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._mainState,e,this.playbackSpeed)}currentTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._currentState,e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t,i){let s=0,a=120,r=0;for(const i of e.tempoChanges){if(t<i.ticks)break;s=i.time,a=i.bpm,r=i.ticks}return s+=(t-=r)*(6e4/(a*e.division)),s/i}timePositionToTickPositionWithSpeed(e,t,i){t*=i;let s=0,a=120,r=0;for(const i of e.tempoChanges){if(t<i.time)break;s=i.ticks,a=i.bpm,r=i.time}return s+=(t-=r)/(6e4/(a*e.division))|0,s+1}get internalEndTime(){return this.isPlayingMain&&this.mainPlaybackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.isPlayingMain&&this.mainPlaybackRange?this._currentState.currentTime=this.mainPlaybackRange.startTick:this._currentState.currentTime=0,this._currentState.eventIndex=0}resetOneTimeMidi(){this._oneTimeState=null,this._currentState=this._mainState}resetCountIn(){this._countInState=null,this._currentState=this._mainState}startCountIn(){this.generateCountInMidi(),this._currentState=this._countInState,this.stop(),this._synthesizer.noteOffAll(!0)}generateCountInMidi(){const e=new Mt;e.division=this._mainState.division;let t=120,i=4,s=4;0===this._mainState.eventIndex?(t=this._mainState.tempoChanges[0].bpm,i=this._mainState.firstTimeSignatureNumerator,s=this._mainState.firstTimeSignatureDenominator):(t=this._synthesizer.currentTempo,i=this._synthesizer.timeSignatureNumerator,s=this._synthesizer.timeSignatureDenominator),e.tempoChanges.push(new Lt(t,0,0));let a=e.division*(4/s)|0,r=a*(6e4/(t*this._mainState.division)),n=0,o=0;for(let t=0;t<i;t++){let i=Ct.newMetronomeEvent(e.synthData.length,n,t,a,r);e.synthData.push(i),i.time=o,n+=a,o+=r}e.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),e.endTime=o,e.endTick=n,this._countInState=e}}!function(e){e[e.Paused=0]="Paused",e[e.Playing=1]="Playing"}(J||(J={}));class It{constructor(e,t){this.state=e,this.stopped=t}}class Rt{constructor(e,t,i,s,a){this.currentTime=e,this.endTime=t,this.currentTick=i,this.endTick=s,this.isSeek=a}}class At{constructor(){this.id="",this.size=0}static load(e,t,i){if(e&&At.HeaderSize>e.size)return!1;if(i.position+At.HeaderSize>=i.length)return!1;if(t.id=ze.read8BitStringLength(i,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=ze.readUInt32LE(i),e&&At.HeaderSize+t.size>e.size)return!1;e&&(e.size-=At.HeaderSize+t.size);let s="RIFF"===t.id,a="LIST"===t.id;return(!s||!e)&&(!s&&!a||(t.id=ze.read8BitStringLength(i,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}At.HeaderSize=8;class Ot{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.fontSamples=new Float32Array(0)}load(e){const t=new At,i=new At;if(!At.load(null,t,e)||"sfbk"!==t.id)throw new Ie("Soundfont is not a valid Soundfont2 file");for(;At.load(t,i,e);){let t=new At;if("pdta"===i.id)for(;At.load(i,t,e);)switch(t.id){case"phdr":for(let i=0,s=t.size/Xt.SizeInFile|0;i<s;i++)this.phdrs.push(new Xt(e));break;case"pbag":for(let i=0,s=t.size/zt.SizeInFile|0;i<s;i++)this.pbags.push(new zt(e));break;case"pmod":for(let i=0,s=t.size/Yt.SizeInFile|0;i<s;i++)this.pmods.push(new Yt(e));break;case"pgen":for(let i=0,s=t.size/Ut.SizeInFile|0;i<s;i++)this.pgens.push(new Ut(e));break;case"inst":for(let i=0,s=t.size/Wt.SizeInFile|0;i<s;i++)this.insts.push(new Wt(e));break;case"ibag":for(let i=0,s=t.size/Gt.SizeInFile|0;i<s;i++)this.ibags.push(new Gt(e));break;case"imod":for(let i=0,s=t.size/Ht.SizeInFile|0;i<s;i++)this.imods.push(new Ht(e));break;case"igen":for(let i=0,s=t.size/Vt.SizeInFile|0;i<s;i++)this.igens.push(new Vt(e));break;case"shdr":for(let i=0,s=t.size/qt.SizeInFile|0;i<s;i++)this.sHdrs.push(new qt(e));break;default:e.position+=t.size}else if("sdta"===i.id)for(;At.load(i,t,e);)if("smpl"===t.id)this.fontSamples=Ot.loadSamples(t,e);else e.position+=t.size;else e.position+=i.size}}static loadSamples(e,t){let i=e.size/2|0;const s=new Float32Array(i);let a=0;const r=new Uint8Array(16384);for(;i>0;){let e=Math.min(i,r.length/2|0);t.read(r,0,2*e);for(let t=0;t<e;t++){const e=We.int32ToInt16(r[2*t+1]<<8|r[2*t]);s[a+t]=e/32767}i-=e,a+=e}return s}}class Gt{constructor(e){this.instGenNdx=ze.readUInt16LE(e),this.instModNdx=ze.readUInt16LE(e)}}Gt.SizeInFile=4;class Ht{constructor(e){this.modSrcOper=ze.readUInt16LE(e),this.modDestOper=ze.readUInt16LE(e),this.modAmount=ze.readInt16LE(e),this.modAmtSrcOper=ze.readUInt16LE(e),this.modTransOper=ze.readUInt16LE(e)}}Ht.SizeInFile=10;class Vt{constructor(e){this.genOper=ze.readUInt16LE(e),this.genAmount=new Jt(e)}}Vt.SizeInFile=4;class Wt{constructor(e){this.instName=ze.read8BitStringLength(e,20),this.instBagNdx=ze.readUInt16LE(e)}}Wt.SizeInFile=22;class zt{constructor(e){this.genNdx=ze.readUInt16LE(e),this.modNdx=ze.readUInt16LE(e)}}zt.SizeInFile=4;class Ut{constructor(e){this.genOper=ze.readUInt16LE(e),this.genAmount=new Jt(e)}}Ut.SizeInFile=4,Ut.GenInstrument=41,Ut.GenKeyRange=43,Ut.GenVelRange=44,Ut.GenSampleId=53;class Xt{constructor(e){this.presetName=ze.read8BitStringLength(e,20),this.preset=ze.readUInt16LE(e),this.bank=ze.readUInt16LE(e),this.presetBagNdx=ze.readUInt16LE(e),this.library=ze.readUInt32LE(e),this.genre=ze.readUInt32LE(e),this.morphology=ze.readUInt32LE(e)}}Xt.SizeInFile=38;class Yt{constructor(e){this.modSrcOper=ze.readUInt16LE(e),this.modDestOper=ze.readUInt16LE(e),this.modAmount=ze.readUInt16LE(e),this.modAmtSrcOper=ze.readUInt16LE(e),this.modTransOper=ze.readUInt16LE(e)}}Yt.SizeInFile=10;class qt{constructor(e){this.sampleName=ze.read8BitStringLength(e,20),this.start=ze.readUInt32LE(e),this.end=ze.readUInt32LE(e),this.startLoop=ze.readUInt32LE(e),this.endLoop=ze.readUInt32LE(e),this.sampleRate=ze.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=ze.readSInt8(e),this.sampleLink=ze.readUInt16LE(e),this.sampleType=ze.readUInt16LE(e)}}qt.SizeInFile=46;class Jt{constructor(e){this.wordAmount=ze.readUInt16LE(e)}get shortAmount(){return We.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}}class jt{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 Qt{constructor(){this.activeChannel=0,this.channelList=[]}setupVoice(e,t){const i=this.channelList[this.activeChannel],s=t.region.pan+i.panOffset;t.playingChannel=this.activeChannel,t.mixVolume=i.mixVolume,t.noteGainDb+=i.gainDb,t.updatePitchRatio(i,e.outSampleRate),s<=-.5?(t.panFactorLeft=1,t.panFactorRight=0):s>=.5?(t.panFactorLeft=0,t.panFactorRight=1):(t.panFactorLeft=Math.sqrt(.5-s),t.panFactorRight=Math.sqrt(.5+s))}}!function(e){e[e.None=0]="None",e[e.Continuous=1]="Continuous",e[e.Sustain=2]="Sustain"}(j||(j={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Q||(Q={}));class $t{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class Kt{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}static clamp(e,t,i){return e<=t?t:e>=i?i:e}}class Zt{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:Kt.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:Kt.timecents2Secs(this.attack),this.release=this.release<-11950?0:Kt.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:Kt.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:Kt.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?Kt.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"}($||($={}));class ei{constructor(e){this.loopMode=j.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new Zt,this.modEnv=new Zt,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new Zt(e.ampEnv),this.modEnv=new Zt(e.modEnv),this.initialFilterQ=e.initialFilterQ,this.initialFilterFc=e.initialFilterFc,this.modEnvToPitch=e.modEnvToPitch,this.modEnvToFilterFc=e.modEnvToFilterFc,this.modLfoToFilterFc=e.modLfoToFilterFc,this.modLfoToVolume=e.modLfoToVolume,this.delayModLFO=e.delayModLFO,this.freqModLFO=e.freqModLFO,this.modLfoToPitch=e.modLfoToPitch,this.delayVibLFO=e.delayVibLFO,this.freqVibLFO=e.freqVibLFO,this.vibLfoToPitch=e.vibLfoToPitch)}clear(e){this.loopMode=j.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case $.StartAddrsOffset:this.offset+=We.int16ToUint32(t.shortAmount);break;case $.EndAddrsOffset:this.end+=We.int16ToUint32(t.shortAmount);break;case $.StartloopAddrsOffset:this.loopStart+=We.int16ToUint32(t.shortAmount);break;case $.EndloopAddrsOffset:this.loopEnd+=We.int16ToUint32(t.shortAmount);break;case $.StartAddrsCoarseOffset:this.offset+=32768*We.int16ToUint32(t.shortAmount);break;case $.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case $.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case $.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case $.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case $.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case $.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case $.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case $.EndAddrsCoarseOffset:this.end+=32768*We.int16ToUint32(t.shortAmount);break;case $.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case $.Pan:this.pan=t.shortAmount/1e3;break;case $.DelayModLFO:this.delayModLFO=t.shortAmount;break;case $.FreqModLFO:this.freqModLFO=t.shortAmount;break;case $.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case $.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case $.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case $.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case $.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case $.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case $.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case $.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case $.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case $.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case $.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case $.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case $.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case $.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case $.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case $.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case $.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case $.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case $.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case $.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case $.StartloopAddrsCoarseOffset:this.loopStart+=32768*We.int16ToUint32(t.shortAmount);break;case $.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case $.EndloopAddrsCoarseOffset:this.loopEnd+=32768*We.int16ToUint32(t.shortAmount);break;case $.CoarseTune:this.transpose+=t.shortAmount;break;case $.FineTune:this.tune+=t.shortAmount;break;case $.SampleModes:this.loopMode=3==(3&t.wordAmount)?j.Sustain:1==(3&t.wordAmount)?j.Continuous:j.None;break;case $.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case $.ExclusiveClass:this.group=t.wordAmount;break;case $.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}!function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(K||(K={}));class ti{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=K.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case K.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=K.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=K.Delay;break;case K.Delay:if(this.samplesUntilNextSegment=this.parameters.attack*t|0,this.samplesUntilNextSegment>0)return this.isAmpEnv||(this.samplesUntilNextSegment=this.parameters.attack*((145-this.midiVelocity)/144)*t|0),this.segment=K.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=K.Attack;break;case K.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=K.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=K.Hold;break;case K.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=K.Decay,this.level=1,this.isAmpEnv){let e=-9.226/this.samplesUntilNextSegment;this.slope=Math.exp(e),this.segmentIsExponential=!0,this.parameters.sustain>0&&(this.samplesUntilNextSegment=Math.log(this.parameters.sustain)/e|0)}else this.slope=-1/this.samplesUntilNextSegment,this.samplesUntilNextSegment=this.parameters.decay*(1-this.parameters.sustain)*t|0,this.segmentIsExponential=!1;return}e=K.Decay;break;case K.Decay:return this.segment=K.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case K.Sustain:if(this.segment=K.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?ti.FastReleaseTime:this.parameters.release)*t|0,this.isAmpEnv){let e=-9.226/this.samplesUntilNextSegment;this.slope=Math.exp(e),this.segmentIsExponential=!0}else this.slope=-this.level/this.samplesUntilNextSegment,this.segmentIsExponential=!1;return;default:return this.segment=K.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,i,s,a){this.parameters=new Zt(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:Kt.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:Kt.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|i,this.isAmpEnv=s,this.nextSegment(K.None,a)}process(e,t){this.slope>0&&(this.segmentIsExponential?this.level*=Math.pow(this.slope,e):this.level+=this.slope*e),this.samplesUntilNextSegment-=e,this.samplesUntilNextSegment<=0&&this.nextSegment(this.segment,t)}}ti.FastReleaseTime=.01;class ii{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,i){this.samplesUntil=e*i|0,this.delta=4*Kt.cents2Hertz(t)/i,this.level=0}process(e){this.samplesUntil>e?this.samplesUntil-=e:(this.level+=this.delta*e,this.level>1?(this.delta=-this.delta,this.level=2-this.level):this.level<-1&&(this.delta=-this.delta,this.level=-2-this.level))}}class si{constructor(e){this.qInv=0,this.a0=0,this.a1=0,this.b1=0,this.b2=0,this.z1=0,this.z2=0,this.active=!1,e&&(this.qInv=e.qInv,this.a0=e.a0,this.a1=e.a1,this.b1=e.b1,this.b2=e.b2,this.z1=e.z1,this.z2=e.z2,this.active=e.active)}setup(e){let t=Math.tan(Math.PI*e),i=t*t,s=1/(1+t*this.qInv+i);this.a0=i*s,this.a1=2*this.a0,this.b1=2*(i-1)*s,this.b2=(1-t*this.qInv+i)*s}process(e){let t=e*this.a0+this.z1;return this.z1=e*this.a1+this.z2-this.b1*t,this.z2=e*this.a0-this.b2*t,t}}class ai{constructor(){this.playingPreset=0,this.playingKey=0,this.playingChannel=0,this.region=null,this.pitchInputTimecents=0,this.pitchOutputFactor=0,this.sourceSamplePosition=0,this.noteGainDb=0,this.panFactorLeft=0,this.panFactorRight=0,this.playIndex=0,this.loopStart=0,this.loopEnd=0,this.ampEnv=new ti,this.modEnv=new ti,this.lowPass=new si,this.modLfo=new ii,this.vibLfo=new ii,this.mixVolume=0,this.mute=!1}updatePitchRatio(e,t){let i=e.pitchWheel;e.perNotePitchWheel.has(this.playingKey)&&(i+=e.perNotePitchWheel.get(this.playingKey)-8192);const s=8192===i?e.tuning:i/16383*e.pitchRange*2-e.pitchRange+e.tuning;this.calcPitchRatio(s,t)}calcPitchRatio(e,t){if(!this.region)return;const i=this.playingKey+this.region.transpose+this.region.tune/100;let s=this.region.pitchKeyCenter+(i-this.region.pitchKeyCenter)*(this.region.pitchKeyTrack/100);0!==e&&(s+=e),this.pitchInputTimecents=100*s,this.pitchOutputFactor=this.region.sampleRate/(Kt.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(K.Sustain,e),this.modEnv.nextSegment(K.Sustain,e),this.region.loopMode===j.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(K.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(K.Sustain,e)}render(e,t,i,s,a){if(!this.region)return;let r=this.region;let n=e.presets[this.playingPreset].fontSamples,o=0,h=e.outputMode===Q.StereoUnweaved?s:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,d=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),c=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,f=r.end,m=g+1,y=this.sourceSamplePosition,b=new si(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,_=0,w=0,B=0,T=0,k=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,v=0,N=0,x=0,P=0,E=0!==r.modLfoToVolume,C=0,F=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,T=r.modEnvToFilterFc):(_=0,w=0,B=0,T=0),k?(v=0,N=r.modLfoToPitch,x=r.vibLfoToPitch,P=r.modEnvToPitch):(v=Kt.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,N=0,x=0,P=0),E?F=.1*r.modLfoToVolume:(C=Kt.decibelsToGain(this.noteGainDb),F=0);s>0;){let r,L,M=0,D=s>ai.RenderEffectSampleBlock?ai.RenderEffectSampleBlock:s;if(s-=D,S){let e=w+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(Kt.cents2Hertz(e)/_)}switch(k&&(v=Kt.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*N+this.vibLfo.level*x+this.modEnv.level*P))*this.pitchOutputFactor),E&&(C=Kt.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(D,e.outSampleRate),l&&this.modEnv.process(D,e.outSampleRate),d&&this.modLfo.process(D),c&&this.vibLfo.process(D),e.outputMode){case Q.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;D-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[s]*a;b.active&&(r=b.process(r)),t[i+o]+=r*L,o++,t[i+o]+=r*M,o++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Q.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;D-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[s]*a;b.active&&(r=b.process(r)),t[i+o]+=r*L,o++,t[i+h]+=r*M,h++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Q.Mono:for(;D-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,h=n[e]*(1-a)+n[s]*a;b.active&&(h=b.process(h)),t[i+o]=h*r,o++,y+=v,y>=m&&u&&(y-=g-p+1)}}if(y>=f||this.ampEnv.segment===K.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}ai.RenderEffectSampleBlock=Ft.MicroBufferSize;class ri{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0==this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}class ni{constructor(e){this._midiEventQueue=new ri,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Q.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,i){return this.fillWorkingBuffer(e,t,i)}synthesizeSilent(e){this.fillWorkingBuffer(null,0,e)}channelGetMixVolume(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].mixVolume:1}channelSetMixVolume(e,t){let i=this.channelInit(e);for(let i of this._voices)i.playingChannel===e&&-1!==i.playingPreset&&(i.mixVolume=t);i.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,i){const s=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){let e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Ft.MetronomeChannel,33),this.channelNoteOn(Ft.MetronomeChannel,33,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||s&&r!=Ft.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,i,n):a.kill()}return a}processMidiMessage(e){const t=e.command,i=e.channel,s=e.data1,a=e.data2;switch(t){case U.NoteOff:this.channelNoteOff(i,s);break;case U.NoteOn:this.channelNoteOn(i,s,a/127);break;case U.NoteAftertouch:break;case U.Controller:this.channelMidiControl(i,s,a);break;case U.ProgramChange:this.channelSetPresetNumber(i,s,9===i);break;case U.ChannelAftertouch:break;case U.PitchBend:this.channelSetPitchWheel(i,s|a<<7);break;case U.PerNotePitchBend:const t=e;let r=t.pitch;r=r*Ft.MaxPitchWheel/Ft.MaxPitchWheel20,this.channelSetPerNotePitchWheel(i,t.noteKey,r);break;case U.Meta:switch(e.data1){case X.Tempo:this.currentTempo=6e7/e.value;break;case X.TimeSignature:this.timeSignatureNumerator=e.data[0],this.timeSignatureDenominator=Math.pow(2,e.data[1])}}}get metronomeVolume(){return this.channelGetMixVolume(Ft.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Ft.MetronomeChannel,e),e>0&&(this.channelSetVolume(Ft.MetronomeChannel,1),this.channelSetPresetNumber(Ft.MetronomeChannel,0,!0))}get masterVolume(){return Kt.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=Kt.gainToDecibels(e);const i=t-this.globalGainDb;if(0!==i){for(const e of this._voices)-1!==e.playingPreset&&(e.noteGainDb+=i);this.globalGainDb=t}}resetSoft(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<K.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){var e,t;return null!==(t=null===(e=this.presets)||void 0===e?void 0:e.length)&&void 0!==t?t:0}reset(){for(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<K.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);this._channels=null}setOutput(e,t,i){this.outputMode=e,this.outSampleRate=t>=1?t:44100,this.globalGainDb=i}noteOn(e,t,i){if(!this.presets)return;const s=127*i|0;if(e<0||e>=this.presets.length)return;if(i<=0)return void this.noteOff(e,t);const a=this._voicePlayIndex++;for(const r of this.presets[e].regions){if(t<r.loKey||t>r.hiKey||s<r.loVel||s>r.hiVel)continue;let n=null;if(0!==r.group)for(const t of this._voices)t.playingPreset===e&&t.region.group===r.group?t.endQuick(this.outSampleRate):-1!==t.playingPreset||n||(n=t);else for(let e of this._voices)-1===e.playingPreset&&(n=e);if(!n){for(let e=0;e<4;e++){const e=new ai;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-Kt.gainToDecibels(1/i),this._channels?this._channels.setupVoice(this,n):(n.calcPitchRatio(0,this.outSampleRate),n.panFactorLeft=Math.sqrt(.5-r.pan),n.panFactorRight=Math.sqrt(.5+r.pan)),n.sourceSamplePosition=r.offset;const o=r.loopMode!==j.None&&r.loopStart<r.loopEnd;n.loopStart=o?r.loopStart:0,n.loopEnd=o?r.loopEnd:0,n.ampEnv.setup(r.ampEnv,t,s,!0,this.outSampleRate),n.modEnv.setup(r.modEnv,t,s,!1,this.outSampleRate);const h=r.initialFilterQ/10;n.lowPass.qInv=1/Math.pow(10,h/20),n.lowPass.z1=0,n.lowPass.z2=0,n.lowPass.active=r.initialFilterFc<=13500,n.lowPass.active&&n.lowPass.setup(Kt.cents2Hertz(r.initialFilterFc)/this.outSampleRate),n.modLfo.setup(r.delayModLFO,r.freqModLFO,this.outSampleRate),n.vibLfo.setup(r.delayVibLFO,r.freqVibLFO,this.outSampleRate)}}bankNoteOn(e,t,i,s){let a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,i,s),!0)}noteOff(e,t){let i=null,s=null,a=[];for(let r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=K.Release||(!i||r.playIndex<i.playIndex?(i=r,s=r,a.push(r)):r.playIndex===i.playIndex&&(s=r,a.push(r)));if(i)for(const r of a)r!==i&&r!==s&&(r.playIndex!==i.playIndex||r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=K.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,i){const s=this.getPresetIndex(e,t);return-1!==s&&(this.noteOff(s,i),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&t.ampEnv.segment<K.Release&&(e?t.endQuick(this.outSampleRate):t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new Qt);for(let t=this._channels.channelList.length;t<=e;t++){let e=new jt;e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0,e.mixVolume=1,this._channels.channelList.push(e)}return this._channels.channelList[e]}getPresetIndex(e,t){if(!this.presets)return-1;for(let i=this.presets.length-1;i>=0;i--){let s=this.presets[i];if(s.presetNumber===t&&s.bank===e)return i}return-1}getPresetName(e){return this.presets?e<0||e>=this.presets.length?null:this.presets[e].name:null}bankGetPresetName(e,t){return this.getPresetName(this.getPresetIndex(e,t))}channelNoteOn(e,t,i){!this._channels||e>this._channels.channelList.length||(this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,i))}channelNoteOff(e,t){const i=[];let s=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=K.Release||(!s||r.playIndex<s.playIndex?(s=r,a=r,i.push(r)):r.playIndex===s.playIndex&&(a=r,i.push(r)));if(this.channelInit(e).perNotePitchWheel.delete(t),s)for(const r of i)r!==s&&r!==a&&(r.playIndex!==s.playIndex||-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=K.Release)||r.end(this.outSampleRate)}channelNoteOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(const t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&t.ampEnv.segment<K.Release&&t.end(this.outSampleRate)}channelSoundsOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(let t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&(t.ampEnv.segment<K.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=We.int32ToUint16(t)}channelSetPresetNumber(e,t,i=!1){const s=this.channelInit(e);let a=0;return i?(a=this.getPresetIndex(128|32767&s.bank,t),-1===a&&(a=this.getPresetIndex(128,t)),-1===a&&(a=this.getPresetIndex(128,0)),-1===a&&(a=this.getPresetIndex(2047&s.bank,t))):a=this.getPresetIndex(2047&s.bank,t),s.presetIndex=a,-1!==a}channelSetBank(e,t){this.channelInit(e).bank=We.int32ToUint16(t)}channelSetBankPreset(e,t,i){const s=this.channelInit(e),a=this.getPresetIndex(t,i);return-1!==a&&(s.presetIndex=We.int32ToUint16(a),s.bank=We.int32ToUint16(t),!0)}channelSetPan(e,t){for(const i of this._voices)if(i.playingChannel===e&&-1!==i.playingPreset){let e=i.region.pan+t-.5;e<=-.5?(i.panFactorLeft=1,i.panFactorRight=0):e>=.5?(i.panFactorLeft=0,i.panFactorRight=1):(i.panFactorLeft=Math.sqrt(.5-e),i.panFactorRight=Math.sqrt(.5+e))}this.channelInit(e).panOffset=t-.5}channelSetVolume(e,t){const i=this.channelInit(e),s=Kt.gainToDecibels(t),a=s-i.gainDb;if(0!==a){for(const t of this._voices)t.playingChannel===e&&-1!==t.playingPreset&&(t.noteGainDb+=a);i.gainDb=s}}channelSetPitchWheel(e,t){const i=this.channelInit(e);i.pitchWheel!==t&&(i.pitchWheel=We.int32ToUint16(t),this.channelApplyPitch(e,i))}channelSetPerNotePitchWheel(e,t,i){const s=this.channelInit(e);s.perNotePitchWheel.has(t)&&s.perNotePitchWheel.get(t)===i||(s.perNotePitchWheel.set(t,i),this.channelApplyPitch(e,s,t))}channelApplyPitch(e,t,i=-1){for(const s of this._voices)s.playingChannel!==e||-1===s.playingPreset||-1!=i&&s.playingKey!==i||s.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const i=this.channelInit(e);i.pitchRange!==t&&(i.pitchRange=t,8192!==i.pitchWheel&&this.channelApplyPitch(e,i))}channelSetTuning(e,t){const i=this.channelInit(e);i.tuning!==t&&(i.tuning=t,this.channelApplyPitch(e,i))}channelMidiControl(e,t,i){let s=this.channelInit(e);switch(t){case 5:case 96:case 97:case 64:case 65:case 66:case 122:case 124:case 125:case 126:case 127:return;case 38:return s.midiData=We.int32ToUint16(16256&s.midiData|i),void(0===s.midiRpn?this.channelSetPitchRange(e,(s.midiData>>7)+.01*(127&s.midiData)):1===s.midiRpn?this.channelSetTuning(e,(0|s.tuning)+(s.midiData-8192)/8192):2===s.midiRpn&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case 7:return s.midiVolume=We.int32ToUint16(127&s.midiVolume|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 39:return s.midiVolume=We.int32ToUint16(16256&s.midiVolume|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 11:return s.midiExpression=We.int32ToUint16(127&s.midiExpression|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 43:return s.midiExpression=We.int32ToUint16(16256&s.midiExpression|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 10:return s.midiPan=We.int32ToUint16(127&s.midiPan|i<<7),void this.channelSetPan(e,s.midiPan/16383);case 42:return s.midiPan=We.int32ToUint16(16256&s.midiPan|i),void this.channelSetPan(e,s.midiPan/16383);case 6:return s.midiData=We.int32ToUint16(127&s.midiData|i<<7),void(0===s.midiRpn?this.channelSetPitchRange(e,(s.midiData>>7)+.01*(127&s.midiData)):1===s.midiRpn?this.channelSetTuning(e,(0|s.tuning)+(s.midiData-8192)/8192):2===s.midiRpn&&6===t&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case 0:return void(s.bank=We.int32ToUint16(32768|i));case 32:return void(s.bank=We.int32ToUint16((0!=(32768&s.bank)?(127&s.bank)<<7:0)|i));case 101:return void(s.midiRpn=We.int32ToUint16(127&(65535===s.midiRpn?0:s.midiRpn)|i<<7));case 100:return void(s.midiRpn=We.int32ToUint16(16256&(65535===s.midiRpn?0:s.midiRpn)|i));case 98:case 99:return void(s.midiRpn=65535);case 120:return void this.channelSoundsOffAll(e);case 123:return void this.channelNoteOffAll(e);case 121:return s.midiVolume=16383,s.midiExpression=16383,s.midiPan=8192,s.bank=0,this.channelSetVolume(e,1),this.channelSetPan(e,.5),void this.channelSetPitchRange(e,2)}}channelGetPresetIndex(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].presetIndex:0}channelGetPresetBank(e){return this._channels&&e<this._channels.channelList.length?32767&this._channels.channelList[e].bank:0}channelGetPan(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].panOffset-.5:.5}channelGetVolume(e){return this._channels&&e<this._channels.channelList.length?Kt.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t){const i=[];for(let t=0;t<e.phdrs.length-1;t++){const s=e.phdrs[t];let a=0;const r=new $t;i.push(r),r.name=s.presetName,r.bank=s.bank,r.presetNumber=s.preset,r.fontSamples=e.fontSamples;let n=0;for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){let t=0,s=127,a=0,r=127;for(let o=e.pbags[i].genNdx;o<e.pbags[i+1].genNdx;o++){let i=e.pgens[o];if(i.genOper!==Ut.GenKeyRange)if(i.genOper!==Ut.GenVelRange){if(i.genOper===Ut.GenInstrument&&!(i.genAmount.wordAmount>=e.insts.length))for(let o=e.insts[i.genAmount.wordAmount].instBagNdx;o<e.insts[i.genAmount.wordAmount+1].instBagNdx;o++){let i=0,h=127,l=0,d=127;for(let c=e.ibags[o].instGenNdx;c<e.ibags[o+1].instGenNdx;c++){let o=e.igens[c];o.genOper!==Ut.GenKeyRange?o.genOper!==Ut.GenVelRange?53===o.genOper&&h>=t&&i<=s&&d>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,d=o.genAmount.highByteAmount):(i=o.genAmount.lowByteAmount,h=o.genAmount.highByteAmount)}}}else a=i.genAmount.lowByteAmount,r=i.genAmount.highByteAmount;else t=i.genAmount.lowByteAmount,s=i.genAmount.highByteAmount}}r.regions=new Array(n);let o=new ei;o.clear(!0);for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){const t=e.pbags[i],n=new ei(o);let h=!1;for(let s=t.genNdx;s<e.pbags[i+1].genNdx;s++){const t=e.pgens[s];if(t.genOper===Ut.GenInstrument){let i=t.genAmount.wordAmount;if(i>=e.insts.length)continue;let s=new ei;s.clear(!1);let o=e.insts[i];for(let t=o.instBagNdx;t<e.insts[i+1].instBagNdx;t++){let i=e.ibags[t],h=new ei(s),l=!1;for(let s=i.instGenNdx;s<e.ibags[t+1].instGenNdx;s++){let t=e.igens[s];if(t.genOper===Ut.GenSampleId){if(h.hiKey<n.loKey||h.loKey>n.hiKey)continue;if(h.hiVel<n.loVel||h.loVel>n.hiVel)continue;n.loKey>h.loKey&&(h.loKey=n.loKey),n.hiKey<h.hiKey&&(h.hiKey=n.hiKey),n.loVel>h.loVel&&(h.loVel=n.loVel),n.hiVel<h.hiVel&&(h.hiVel=n.hiVel),h.offset+=n.offset,h.end+=n.end,h.loopStart+=n.loopStart,h.loopEnd+=n.loopEnd,h.transpose+=n.transpose,h.tune+=n.tune,h.pitchKeyTrack+=n.pitchKeyTrack,h.attenuation+=n.attenuation,h.pan+=n.pan,h.ampEnv.delay+=n.ampEnv.delay,h.ampEnv.attack+=n.ampEnv.attack,h.ampEnv.hold+=n.ampEnv.hold,h.ampEnv.decay+=n.ampEnv.decay,h.ampEnv.sustain+=n.ampEnv.sustain,h.ampEnv.release+=n.ampEnv.release,h.modEnv.delay+=n.modEnv.delay,h.modEnv.attack+=n.modEnv.attack,h.modEnv.hold+=n.modEnv.hold,h.modEnv.decay+=n.modEnv.decay,h.modEnv.sustain+=n.modEnv.sustain,h.modEnv.release+=n.modEnv.release,h.initialFilterQ+=n.initialFilterQ,h.initialFilterFc+=n.initialFilterFc,h.modEnvToPitch+=n.modEnvToPitch,h.modEnvToFilterFc+=n.modEnvToFilterFc,h.delayModLFO+=n.delayModLFO,h.freqModLFO+=n.freqModLFO,h.modLfoToPitch+=n.modLfoToPitch,h.modLfoToFilterFc+=n.modLfoToFilterFc,h.modLfoToVolume+=n.modLfoToVolume,h.delayVibLFO+=n.delayVibLFO,h.freqVibLFO+=n.freqVibLFO,h.vibLfoToPitch+=n.vibLfoToPitch,h.ampEnv.envToSecs(!0),h.modEnv.envToSecs(!1),h.delayModLFO=h.delayModLFO<-11950?0:Kt.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:Kt.timecents2Secs(h.delayVibLFO),h.pan<-.5?h.pan=-.5:h.pan>.5&&(h.pan=.5),(h.initialFilterQ<1500||h.initialFilterQ>13500)&&(h.initialFilterQ=0);let i=e.sHdrs[t.genAmount.wordAmount];h.offset+=i.start,h.end+=i.end,h.loopStart+=i.startLoop,h.loopEnd+=i.endLoop,i.endLoop>0&&(h.loopEnd-=1),-1===h.pitchKeyCenter&&(h.pitchKeyCenter=i.originalPitch),h.tune+=i.pitchCorrection,h.sampleRate=i.sampleRate,0!==h.end&&h.end<r.fontSamples.length?h.end++:h.end=r.fontSamples.length,r.regions[a]=new ei(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}i!==e.ibags[o.instBagNdx]||l||(s=new ei(h))}h=!0}else n.operator(t.genOper,t.genAmount)}t!==e.pbags[s.presetBagNdx]||h||(o=n)}}if(t&&this.presets)for(const e of i)this.presets.push(e);else this.presets=i}}class oi{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 hi{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 li{constructor(e){this.events=e}}class di{constructor(e){this.playbackRange=e}}class ci{constructor(e,t){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new ri,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this.isReady=!1,this.state=J.Paused,this.ready=new oi,this.readyForPlayback=new oi,this.finished=new oi,this.soundFontLoaded=new oi,this.soundFontLoadFailed=new hi,this.midiLoaded=new hi,this.midiLoadFailed=new hi,this.stateChanged=new hi,this.positionChanged=new hi,this.midiEventsPlayed=new hi,this.playbackRangeChanged=new hi,ge.debug("AlphaSynth","Initializing player"),this.state=J.Paused,ge.debug("AlphaSynth","Creating output"),this.output=e,ge.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new ni(this.output.sampleRate),this._sequencer=new Dt(this._synthesizer),ge.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this._sequencer.isFinished){let e=new Float32Array(0);this.output.addSamples(e)}else{let e=new Float32Array(Ft.MicroBufferSize*Ft.MicroBufferCount*Ft.AudioChannels),t=0;for(let i=0;i<Ft.MicroBufferCount;i++){this._sequencer.fillMidiEventQueue();const i=this._synthesizer.synthesize(e,t,Ft.MicroBufferSize);t+=Ft.MicroBufferSize*Ft.AudioChannels;for(const e of i)this._midiEventsPlayedFilter.has(e.event.command)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return ge.logLevel}set logLevel(e){ge.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Ft.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ft.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ft.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=Kt.clamp(e,Ft.MinPlaybackSpeed,Ft.MaxPlaybackSpeed);let t=this._sequencer.playbackSpeed;this._sequencer.playbackSpeed=e,this.timePosition=this.timePosition*(t/e)}get tickPosition(){return this._tickPosition}set tickPosition(e){this.timePosition=this._sequencer.mainTickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){ge.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 di(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){ge.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}play(){return!(this.state!==J.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(ge.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(ge.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),ge.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=J.Playing,this.stateChanged.trigger(new It(this.state,!1))}pause(){this.state!==J.Paused&&this._isMidiLoaded&&(ge.debug("AlphaSynth","Pausing playback"),this.state=J.Paused,this.stateChanged.trigger(new It(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===J.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(ge.debug("AlphaSynth","Stopping playback"),this.state=J.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 It(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let i=Ue.fromBuffer(e);try{ge.debug("AlphaSynth","Loading soundfont from bytes");let e=new Ot;e.load(i),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),ge.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){ge.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){this.isReadyForPlayback&&(this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.readyForPlayback.trigger())}loadMidiFile(e){this.stop();try{ge.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new Rt(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),ge.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){ge.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Ft.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Ft.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(ge.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(ge.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=J.Paused,this.stopOneTimeMidi()):(ge.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.isLooping?this.tickPosition=e:this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){const i=e;this._timePosition=i;const s=this._sequencer.currentTimePositionToTickPosition(i);this._tickPosition=s;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick,n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(ge.debug("AlphaSynth",`Position changed: (time: ${i}/${a}, tick: ${s}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new Rt(i,a,s,r,t)),t)this._playedEventsQueue.clear();else{const e=new ri;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<i;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new li(e.toArray()))}}}class ui{constructor(){this.division=le.QuarterTime,this.events=[]}addEvent(e){if(0===this.events.length)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}toBinary(){let e=Ue.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),t=new Uint8Array([0,0,0,6]),e.write(t,0,t.length),t=new Uint8Array([0,0]),e.write(t,0,t.length);let i=1;t=new Uint8Array([i>>8&255,255&i]),e.write(t,0,t.length),i=this.division,t=new Uint8Array([i>>8&255,255&i]),e.write(t,0,t.length);let s=Ue.empty(),a=0;for(let e of this.events){let t=e.tick-a;ui.writeVariableInt(s,t),e.writeTo(s),a=e.tick}t=new Uint8Array([77,84,114,107]),e.write(t,0,t.length);let r=s.toArray(),n=r.length;t=new Uint8Array([n>>24&255,n>>16&255,n>>8&255,255&n]),e.write(t,0,t.length),e.write(r,0,r.length)}static writeVariableInt(e,t){let i=new Uint8Array(4),s=0;do{i[s++]=127&t,t>>=7}while(t>0);for(;s>0;)s--,s>0?e.writeByte(128|i[s]):e.writeByte(i[s])}}class pi extends xt{constructor(e,t,i,s,a){super(e,t,i,s,0),this.data=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus);let t=this.data.length;ui.writeVariableInt(e,t),e.write(this.data,0,this.data.length)}}class gi extends xt{constructor(e,t,i,s,a){super(e,t,i,s,0),this.value=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus),ui.writeVariableInt(e,3);let t=new Uint8Array([this.value>>16&255,this.value>>8&255,255&this.value]);e.write(t,0,t.length)}}class fi{static parseEnum(t,i){switch(typeof t){case"string":const e=parseInt(t);return isNaN(e)?i[Object.keys(i).find((e=>e.toLowerCase()===t.toLowerCase()))]:e;case"number":return t;case"undefined":case"object":return null}throw new re(e.AlphaTabErrorType.Format,`Could not parse enum value '${t}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const i in e)t(e[i],i)}}class mi{constructor(e,t,i){this.text=e,this.startPos=t,this.endPos=i}}class yi{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],this.parseOnlyFamilies=!1,this._currentTokenIndex=-1,this._input="",this._currentToken=null,this._input=e,this._tokens=this.splitToTokens(e)}splitToTokens(e){const t=[];let i=0;for(;i<e.length;){let s=i;for(;s<e.length&&" "!==e.charAt(s);)s++;s>i&&t.push(new mi(e.substring(i,s),i,s)),i=s+1}return t}parse(){var e;if(this.reset(),1===this._tokens.length)switch(null===(e=this._currentToken)||void 0===e?void 0:e.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new yi(e);return t.parseOnlyFamilies=!0,t.parse(),t.families}fontFamily(){if(!this._currentToken){if(this.parseOnlyFamilies)return;throw new Error("Missing font list")}const e=this._input.substr(this._currentToken.startPos).trim();let t=0;for(;t<e.length;){let i=e.charAt(t);if(" "===i||","==i)t++;else if('"'===i||"'"===i){const s=this.findEndOfQuote(e,t+1,i);this.families.push(e.substring(t+1,s).split("\\"+i).join(i)),t=s+1}else{const i=this.findEndOfQuote(e,t+1,",");this.families.push(e.substring(t,i).trim()),t=i+1}}}findEndOfQuote(e,t,i){let s=!1;for(;t<e.length;){const a=e.charAt(t);if(!s&&a===i)return t;s=!s&&"\\"===a,t+=1}return e.length}fontSizeLineHeight(){if(!this._currentToken)throw new Error("Missing font size");const e=this._currentToken.text.split("/");if(e.length>=3)throw new Error(`Invalid font size '${this._currentToken}' specified`);if(this.nextToken(),e.length>=2)if("/"===e[1]){if(!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.size=e[0],this.lineHeight=e[1];else{if(!(e.length>=1))throw new Error("Missing font size");if(this.size=e[0],this._currentToken&&0===this._currentToken.text.indexOf("/"))if("/"===this._currentToken.text){if(this.nextToken(),!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.lineHeight=this._currentToken.text.substr(1),this.nextToken()}}nextToken(){this._currentTokenIndex++,this._currentTokenIndex<this._tokens.length?this._currentToken=this._tokens[this._currentTokenIndex]:this._currentToken=null}fontStyleVariantWeight(){let e=!1,t=!1,i=!1,s=3,a=[];for(;;){if(!this._currentToken)return;let r=this._currentToken.text;switch(r){case"normal":case"inherit":a.push(r),s--,this.nextToken();break;case"italic":case"oblique":this.style=r,e=!0,s--,this.nextToken();break;case"small-caps":this.variant=r,t=!0,s--,this.nextToken();break;case"bold":case"bolder":case"lighter":case"100":case"200":case"300":case"400":case"500":case"600":case"700":case"800":case"900":this.weight=r,i=!0,s--,this.nextToken();break;default:return}if(0===s)break}for(;a.length>0;){const s=a.pop();i?t?e||(this.style=s):this.variant=s:this.weight=s}}reset(){this._currentTokenIndex=-1,this.nextToken()}static quoteFont(e){if(-1===e.indexOf(" "))return e;return`"${e.replaceAll('"','\\"')}"`}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}(Z||(Z={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(ee||(ee={}));class bi{constructor(e,t,i=Z.Plain,s=ee.Regular){this._cssScale=0,this._families=yi.parseFamilies(e),this._size=t,this._style=i,this._weight=s,this._css=this.toCssString()}reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=yi.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===ee.Bold}get isItalic(){return this.style===Z.Italic}static withFamilyList(e,t,i=Z.Plain,s=ee.Regular){const a=new bi("",t,i,s);return a.families=e,a}toCssString(e=1){if(!(this._css&&Math.abs(e-this._cssScale)<.01)){let t="";this.isBold&&(t+="bold "),this.isItalic&&(t+="italic "),t+=this.size*e,t+="px ",t+=this.families.map((e=>yi.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let i=t.get("families"),s=t.get("size"),a=fi.parseEnum(t.get("style"),Z),r=fi.parseEnum(t.get("weight"),ee);return bi.withFamilyList(i,s,a,r)}case"string":{const t=new yi(e);t.parse();let i=t.families,s=t.size.toLowerCase(),a=0;switch(s){case"xx-small":a=7;break;case"x-small":a=10;break;case"small":case"smaller":a=13;break;case"medium":a=16;break;case"large":case"larger":a=18;break;case"x-large":a=24;break;case"xx-large":a=32;break;default:try{a=s.endsWith("em")?16*parseFloat(s.substr(0,s.length-2)):s.endsWith("pt")?16*parseFloat(s.substr(0,s.length-2))/12:s.endsWith("px")?parseFloat(s.substr(0,s.length-2)):12}catch(e){a=12}}let r=Z.Plain;"italic"===t.style&&(r=Z.Italic);let n=ee.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=ee.Bold}return bi.withFamilyList(i,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class Si{constructor(){this.copyrightFont=new bi(Si.sansFont,12,Z.Plain,ee.Bold),this.titleFont=new bi(Si.serifFont,32,Z.Plain),this.subTitleFont=new bi(Si.serifFont,20,Z.Plain),this.wordsFont=new bi(Si.serifFont,15,Z.Plain),this.effectFont=new bi(Si.serifFont,12,Z.Italic),this.fretboardNumberFont=new bi(Si.sansFont,11,Z.Plain),this.tablatureFont=new bi(Si.sansFont,13,Z.Plain),this.graceFont=new bi(Si.sansFont,11,Z.Plain),this.staffLineColor=new Re(165,165,165,255),this.barSeparatorColor=new Re(34,34,17,255),this.barNumberFont=new bi(Si.sansFont,11,Z.Plain),this.barNumberColor=new Re(200,0,0,255),this.fingeringFont=new bi(Si.serifFont,14,Z.Plain),this.markerFont=new bi(Si.serifFont,14,Z.Plain,ee.Bold),this.mainGlyphColor=new Re(0,0,0,255),this.secondaryGlyphColor=new Re(0,0,0,100),this.scoreInfoColor=new Re(0,0,0,255)}}Si.sansFont="Arial, sans-serif",Si.serifFont="Georgia, serif";class _i{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.LayoutMode.Page,this.staveProfile=e.StaveProfile.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.resources=new Si,this.padding=null}}class wi{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}e.ScrollMode=void 0,(te=e.ScrollMode||(e.ScrollMode={}))[te.Off=0]="Off",te[te.Continuous=1]="Continuous",te[te.OffScreen=2]="OffScreen";class Bi{constructor(){this.noteWideLength=480,this.noteWideAmplitude=2,this.noteSlightLength=480,this.noteSlightAmplitude=2,this.beatWideLength=240,this.beatWideAmplitude=3,this.beatSlightLength=240,this.beatSlightAmplitude=3}}class Ti{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}class ki{constructor(){this.soundFont=null,this.scrollElement="html,body",this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=e.ScrollMode.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Bi,this.slide=new Ti,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class vi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scriptfile",e.scriptFile),t.set("fontdirectory",e.fontDirectory),t.set("file",e.file),t.set("tex",e.tex),t.set("tracks",e.tracks),t.set("enablelazyloading",e.enableLazyLoading),t.set("engine",e.engine),t.set("loglevel",e.logLevel),t.set("useworkers",e.useWorkers),t.set("includenotebounds",e.includeNoteBounds),t}static setProperty(t,i,s){switch(i){case"scriptfile":return t.scriptFile=s,!0;case"fontdirectory":return t.fontDirectory=s,!0;case"file":return t.file=s,!0;case"tex":return t.tex=s,!0;case"tracks":return t.tracks=s,!0;case"enablelazyloading":return t.enableLazyLoading=s,!0;case"engine":return t.engine=s,!0;case"loglevel":return t.logLevel=fi.parseEnum(s,e.LogLevel),!0;case"useworkers":return t.useWorkers=s,!0;case"includenotebounds":return t.includeNoteBounds=s,!0}return!1}}class Ni{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",bi.toJson(e.copyrightFont)),t.set("titlefont",bi.toJson(e.titleFont)),t.set("subtitlefont",bi.toJson(e.subTitleFont)),t.set("wordsfont",bi.toJson(e.wordsFont)),t.set("effectfont",bi.toJson(e.effectFont)),t.set("fretboardnumberfont",bi.toJson(e.fretboardNumberFont)),t.set("tablaturefont",bi.toJson(e.tablatureFont)),t.set("gracefont",bi.toJson(e.graceFont)),t.set("stafflinecolor",Re.toJson(e.staffLineColor)),t.set("barseparatorcolor",Re.toJson(e.barSeparatorColor)),t.set("barnumberfont",bi.toJson(e.barNumberFont)),t.set("barnumbercolor",Re.toJson(e.barNumberColor)),t.set("fingeringfont",bi.toJson(e.fingeringFont)),t.set("markerfont",bi.toJson(e.markerFont)),t.set("mainglyphcolor",Re.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Re.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Re.toJson(e.scoreInfoColor)),t}static setProperty(e,t,i){switch(t){case"copyrightfont":return e.copyrightFont=bi.fromJson(i),!0;case"titlefont":return e.titleFont=bi.fromJson(i),!0;case"subtitlefont":return e.subTitleFont=bi.fromJson(i),!0;case"wordsfont":return e.wordsFont=bi.fromJson(i),!0;case"effectfont":return e.effectFont=bi.fromJson(i),!0;case"fretboardnumberfont":return e.fretboardNumberFont=bi.fromJson(i),!0;case"tablaturefont":return e.tablatureFont=bi.fromJson(i),!0;case"gracefont":return e.graceFont=bi.fromJson(i),!0;case"stafflinecolor":return e.staffLineColor=Re.fromJson(i),!0;case"barseparatorcolor":return e.barSeparatorColor=Re.fromJson(i),!0;case"barnumberfont":return e.barNumberFont=bi.fromJson(i),!0;case"barnumbercolor":return e.barNumberColor=Re.fromJson(i),!0;case"fingeringfont":return e.fingeringFont=bi.fromJson(i),!0;case"markerfont":return e.markerFont=bi.fromJson(i),!0;case"mainglyphcolor":return e.mainGlyphColor=Re.fromJson(i),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Re.fromJson(i),!0;case"scoreinfocolor":return e.scoreInfoColor=Re.fromJson(i),!0}return!1}}class xi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scale",e.scale),t.set("stretchforce",e.stretchForce),t.set("layoutmode",e.layoutMode),t.set("staveprofile",e.staveProfile),t.set("barsperrow",e.barsPerRow),t.set("startbar",e.startBar),t.set("barcount",e.barCount),t.set("barcountperpartial",e.barCountPerPartial),t.set("resources",Ni.toJson(e.resources)),t.set("padding",e.padding),t}static setProperty(t,i,s){switch(i){case"scale":return t.scale=s,!0;case"stretchforce":return t.stretchForce=s,!0;case"layoutmode":return t.layoutMode=fi.parseEnum(s,e.LayoutMode),!0;case"staveprofile":return t.staveProfile=fi.parseEnum(s,e.StaveProfile),!0;case"barsperrow":return t.barsPerRow=s,!0;case"startbar":return t.startBar=s,!0;case"barcount":return t.barCount=s,!0;case"barcountperpartial":return t.barCountPerPartial=s,!0;case"padding":return t.padding=s,!0}if(["resources"].indexOf(i)>=0)return Ni.fromJson(t.resources,s),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Ni.setProperty(t.resources,i.substring(e.length),s))return!0;return!1}}class Pi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notationmode",e.notationMode),t.set("fingeringmode",e.fingeringMode);{const i=new Map;t.set("elements",i);for(const[t,s]of e.elements)i.set(t.toString(),s)}return t.set("rhythmmode",e.rhythmMode),t.set("rhythmheight",e.rhythmHeight),t.set("transpositionpitches",e.transpositionPitches),t.set("displaytranspositionpitches",e.displayTranspositionPitches),t.set("smallgracetabnotes",e.smallGraceTabNotes),t.set("extendbendarrowsontiednotes",e.extendBendArrowsOnTiedNotes),t.set("extendlineeffectstobeatend",e.extendLineEffectsToBeatEnd),t.set("slurheight",e.slurHeight),t}static setProperty(t,i,s){switch(i){case"notationmode":return t.notationMode=fi.parseEnum(s,e.NotationMode),!0;case"fingeringmode":return t.fingeringMode=fi.parseEnum(s,e.FingeringMode),!0;case"elements":return t.elements=new Map,fi.forEach(s,((e,i)=>{t.elements.set(fi.parseEnum(i,v),e)})),!0;case"rhythmmode":return t.rhythmMode=fi.parseEnum(s,e.TabRhythmMode),!0;case"rhythmheight":return t.rhythmHeight=s,!0;case"transpositionpitches":return t.transpositionPitches=s,!0;case"displaytranspositionpitches":return t.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return t.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return t.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return t.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return t.slurHeight=s,!0}return!1}}class Ei{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("encoding",e.encoding),t.set("mergepartgroupsinmusicxml",e.mergePartGroupsInMusicXml),t.set("beattextaslyrics",e.beatTextAsLyrics),t}static setProperty(e,t,i){switch(t){case"encoding":return e.encoding=i,!0;case"mergepartgroupsinmusicxml":return e.mergePartGroupsInMusicXml=i,!0;case"beattextaslyrics":return e.beatTextAsLyrics=i,!0}return!1}}class Ci{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("notewidelength",e.noteWideLength),t.set("notewideamplitude",e.noteWideAmplitude),t.set("noteslightlength",e.noteSlightLength),t.set("noteslightamplitude",e.noteSlightAmplitude),t.set("beatwidelength",e.beatWideLength),t.set("beatwideamplitude",e.beatWideAmplitude),t.set("beatslightlength",e.beatSlightLength),t.set("beatslightamplitude",e.beatSlightAmplitude),t}static setProperty(e,t,i){switch(t){case"notewidelength":return e.noteWideLength=i,!0;case"notewideamplitude":return e.noteWideAmplitude=i,!0;case"noteslightlength":return e.noteSlightLength=i,!0;case"noteslightamplitude":return e.noteSlightAmplitude=i,!0;case"beatwidelength":return e.beatWideLength=i,!0;case"beatwideamplitude":return e.beatWideAmplitude=i,!0;case"beatslightlength":return e.beatSlightLength=i,!0;case"beatslightamplitude":return e.beatSlightAmplitude=i,!0}return!1}}class Fi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("simpleslidepitchoffset",e.simpleSlidePitchOffset),t.set("simpleslidedurationratio",e.simpleSlideDurationRatio),t.set("shiftslidedurationratio",e.shiftSlideDurationRatio),t}static setProperty(e,t,i){switch(t){case"simpleslidepitchoffset":return e.simpleSlidePitchOffset=i,!0;case"simpleslidedurationratio":return e.simpleSlideDurationRatio=i,!0;case"shiftslidedurationratio":return e.shiftSlideDurationRatio=i,!0}return!1}}class Li{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("soundfont",e.soundFont),t.set("enableplayer",e.enablePlayer),t.set("enablecursor",e.enableCursor),t.set("enableanimatedbeatcursor",e.enableAnimatedBeatCursor),t.set("enableelementhighlighting",e.enableElementHighlighting),t.set("enableuserinteraction",e.enableUserInteraction),t.set("scrolloffsetx",e.scrollOffsetX),t.set("scrolloffsety",e.scrollOffsetY),t.set("scrollmode",e.scrollMode),t.set("scrollspeed",e.scrollSpeed),t.set("nativebrowsersmoothscroll",e.nativeBrowserSmoothScroll),t.set("songbookbendduration",e.songBookBendDuration),t.set("songbookdipduration",e.songBookDipDuration),t.set("vibrato",Ci.toJson(e.vibrato)),t.set("slide",Fi.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(t,i,s){switch(i){case"soundfont":return t.soundFont=s,!0;case"scrollelement":return t.scrollElement=s,!0;case"enableplayer":return t.enablePlayer=s,!0;case"enablecursor":return t.enableCursor=s,!0;case"enableanimatedbeatcursor":return t.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return t.enableElementHighlighting=s,!0;case"enableuserinteraction":return t.enableUserInteraction=s,!0;case"scrolloffsetx":return t.scrollOffsetX=s,!0;case"scrolloffsety":return t.scrollOffsetY=s,!0;case"scrollmode":return t.scrollMode=fi.parseEnum(s,e.ScrollMode),!0;case"scrollspeed":return t.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return t.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return t.songBookBendDuration=s,!0;case"songbookdipduration":return t.songBookDipDuration=s,!0;case"playtripletfeel":return t.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return t.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(i)>=0)return Ci.fromJson(t.vibrato,s),!0;for(const e of["vibrato"])if(0===i.indexOf(e)&&Ci.setProperty(t.vibrato,i.substring(e.length),s))return!0;if(["slide"].indexOf(i)>=0)return Fi.fromJson(t.slide,s),!0;for(const e of["slide"])if(0===i.indexOf(e)&&Fi.setProperty(t.slide,i.substring(e.length),s))return!0;return!1}}class Mi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",vi.toJson(e.core)),t.set("display",xi.toJson(e.display)),t.set("notation",Pi.toJson(e.notation)),t.set("importer",Ei.toJson(e.importer)),t.set("player",Li.toJson(e.player)),t}static setProperty(e,t,i){if(["core",""].indexOf(t)>=0)return vi.fromJson(e.core,i),!0;for(const s of["core",""])if(0===t.indexOf(s)&&vi.setProperty(e.core,t.substring(s.length),i))return!0;if(["display",""].indexOf(t)>=0)return xi.fromJson(e.display,i),!0;for(const s of["display",""])if(0===t.indexOf(s)&&xi.setProperty(e.display,t.substring(s.length),i))return!0;if(["notation"].indexOf(t)>=0)return Pi.fromJson(e.notation,i),!0;for(const s of["notation"])if(0===t.indexOf(s)&&Pi.setProperty(e.notation,t.substring(s.length),i))return!0;if(["importer"].indexOf(t)>=0)return Ei.fromJson(e.importer,i),!0;for(const s of["importer"])if(0===t.indexOf(s)&&Ei.setProperty(e.importer,t.substring(s.length),i))return!0;if(["player"].indexOf(t)>=0)return Li.fromJson(e.player,i),!0;for(const s of["player"])if(0===t.indexOf(s)&&Li.setProperty(e.player,t.substring(s.length),i))return!0;return!1}}class Di{constructor(){this.core=new yo,this.display=new _i,this.notation=new ce,this.importer=new wi,this.player=new ki}setSongBookModeSettings(){this.notation.notationMode=e.NotationMode.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=e.FingeringMode.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(v.ParenthesisOnTiedBends,!1),this.notation.elements.set(v.TabNotesOnTiedBends,!1),this.notation.elements.set(v.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Di;return e.setSongBookModeSettings(),e}fillFromJson(e){Mi.fromJson(this,e)}}class Ii extends Nt{constructor(e,t,i,s,a){super(e,t,i,0,0),this.noteKey=s,this.pitch=a}writeTo(e){let t=new Uint8Array([64,255&this.message,255&this.noteKey,0,this.pitch>>24&255,this.pitch>>16&255,this.pitch>>8&255,255&this.pitch]);e.write(t,0,t.length)}}class Ri{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("marker",e.marker),t.set("text",e.text),t}static setProperty(e,t,i){switch(t){case"marker":return e.marker=i,!0;case"text":return e.text=i,!0}return!1}}class Ai{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("islinear",e.isLinear),t.set("type",e.type),t.set("value",e.value),t.set("ratioposition",e.ratioPosition),t.set("text",e.text),t}static setProperty(e,t,i){switch(t){case"islinear":return e.isLinear=i,!0;case"type":return e.type=fi.parseEnum(i,r),!0;case"value":return e.value=i,!0;case"ratioposition":return e.ratioPosition=i,!0;case"text":return e.text=i,!0}return!1}}class Oi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("type",e.type),t.set("length",e.length),t}static setProperty(e,t,i){switch(t){case"type":return e.type=fi.parseEnum(i,G),!0;case"length":return e.length=i,!0}return!1}}class Gi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("tripletfeel",e.tripletFeel),t.set("section",Ri.toJson(e.section)),t.set("tempoautomation",Ai.toJson(e.tempoAutomation));{const i=new Map;t.set("fermata",i);for(const[t,s]of e.fermata)i.set(t.toString(),Oi.toJson(s))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t}static setProperty(e,t,i){switch(t){case"alternateendings":return e.alternateEndings=i,!0;case"keysignature":return e.keySignature=fi.parseEnum(i,M),!0;case"keysignaturetype":return e.keySignatureType=fi.parseEnum(i,I),!0;case"isdoublebar":return e.isDoubleBar=i,!0;case"isrepeatstart":return e.isRepeatStart=i,!0;case"repeatcount":return e.repeatCount=i,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=i,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=i,!0;case"timesignaturecommon":return e.timeSignatureCommon=i,!0;case"tripletfeel":return e.tripletFeel=fi.parseEnum(i,R),!0;case"fermata":return e.fermata=new Map,fi.forEach(i,((t,i)=>{const s=new Ke;Oi.fromJson(s,t),e.addFermata(parseInt(i),s)})),!0;case"start":return e.start=i,!0;case"isanacrusis":return e.isAnacrusis=i,!0}return["section"].indexOf(t)>=0?(i?(e.section=new De,Ri.fromJson(e.section,i)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(i?(e.tempoAutomation=new oe,Ai.fromJson(e.tempoAutomation,i)):e.tempoAutomation=null,!0)}}class Hi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("offset",e.offset),t.set("value",e.value),t}static setProperty(e,t,i){switch(t){case"offset":return e.offset=i,!0;case"value":return e.value=i,!0}return!1}}class Vi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("accentuated",e.accentuated),t.set("bendtype",e.bendType),t.set("bendstyle",e.bendStyle),t.set("iscontinuedbend",e.isContinuedBend),t.set("bendpoints",e.bendPoints.map((e=>Hi.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("isfingering",e.isFingering),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),e.toJson(t),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"accentuated":return e.accentuated=fi.parseEnum(i,a),!0;case"bendtype":return e.bendType=fi.parseEnum(i,d),!0;case"bendstyle":return e.bendStyle=fi.parseEnum(i,l),!0;case"iscontinuedbend":return e.isContinuedBend=i,!0;case"bendpoints":e.bendPoints=[];for(const t of i){const i=new de;Hi.fromJson(i,t),e.addBendPoint(i)}return!0;case"fret":return e.fret=i,!0;case"string":return e.string=i,!0;case"octave":return e.octave=i,!0;case"tone":return e.tone=i,!0;case"percussionarticulation":return e.percussionArticulation=i,!0;case"isvisible":return e.isVisible=i,!0;case"islefthandtapped":return e.isLeftHandTapped=i,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=i,!0;case"isslurdestination":return e.isSlurDestination=i,!0;case"harmonictype":return e.harmonicType=fi.parseEnum(i,y),!0;case"harmonicvalue":return e.harmonicValue=i,!0;case"isghost":return e.isGhost=i,!0;case"isletring":return e.isLetRing=i,!0;case"ispalmmute":return e.isPalmMute=i,!0;case"isdead":return e.isDead=i,!0;case"isstaccato":return e.isStaccato=i,!0;case"slideintype":return e.slideInType=fi.parseEnum(i,S),!0;case"slideouttype":return e.slideOutType=fi.parseEnum(i,_),!0;case"vibrato":return e.vibrato=fi.parseEnum(i,w),!0;case"istiedestination":return e.isTieDestination=i,!0;case"lefthandfinger":return e.leftHandFinger=fi.parseEnum(i,m),!0;case"righthandfinger":return e.rightHandFinger=fi.parseEnum(i,m),!0;case"isfingering":return e.isFingering=i,!0;case"trillvalue":return e.trillValue=i,!0;case"trillspeed":return e.trillSpeed=fi.parseEnum(i,p),!0;case"durationpercent":return e.durationPercent=i,!0;case"accidentalmode":return e.accidentalMode=fi.parseEnum(i,b),!0;case"dynamics":return e.dynamics=fi.parseEnum(i,g),!0}return e.setProperty(t,i)}}class Wi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("notes",e.notes.map((e=>Vi.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=>Ai.toJson(e)))),t.set("dots",e.dots),t.set("fadein",e.fadeIn),t.set("lyrics",e.lyrics),t.set("hasrasgueado",e.hasRasgueado),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),t.set("whammybarpoints",e.whammyBarPoints.map((e=>Hi.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"notes":e.notes=[];for(const t of i){const i=new _e;Vi.fromJson(i,t),e.addNote(i)}return!0;case"isempty":return e.isEmpty=i,!0;case"whammystyle":return e.whammyStyle=fi.parseEnum(i,l),!0;case"ottava":return e.ottava=fi.parseEnum(i,o),!0;case"islegatoorigin":return e.isLegatoOrigin=i,!0;case"duration":return e.duration=fi.parseEnum(i,p),!0;case"automations":e.automations=[];for(const t of i){const i=new oe;Ai.fromJson(i,t),e.automations.push(i)}return!0;case"dots":return e.dots=i,!0;case"fadein":return e.fadeIn=i,!0;case"lyrics":return e.lyrics=i,!0;case"hasrasgueado":return e.hasRasgueado=i,!0;case"pop":return e.pop=i,!0;case"slap":return e.slap=i,!0;case"tap":return e.tap=i,!0;case"text":return e.text=i,!0;case"brushtype":return e.brushType=fi.parseEnum(i,c),!0;case"brushduration":return e.brushDuration=i,!0;case"tupletdenominator":return e.tupletDenominator=i,!0;case"tupletnumerator":return e.tupletNumerator=i,!0;case"iscontinuedwhammy":return e.isContinuedWhammy=i,!0;case"whammybartype":return e.whammyBarType=fi.parseEnum(i,F),!0;case"whammybarpoints":e.whammyBarPoints=[];for(const t of i){const i=new de;Hi.fromJson(i,t),e.addWhammyBarPoint(i)}return!0;case"vibrato":return e.vibrato=fi.parseEnum(i,w),!0;case"chordid":return e.chordId=i,!0;case"gracetype":return e.graceType=fi.parseEnum(i,f),!0;case"pickstroke":return e.pickStroke=fi.parseEnum(i,x),!0;case"tremolospeed":return e.tremoloSpeed=fi.parseEnum(i,p),!0;case"crescendo":return e.crescendo=fi.parseEnum(i,u),!0;case"displaystart":return e.displayStart=i,!0;case"playbackstart":return e.playbackStart=i,!0;case"displayduration":return e.displayDuration=i,!0;case"playbackduration":return e.playbackDuration=i,!0;case"dynamics":return e.dynamics=fi.parseEnum(i,g),!0;case"invertbeamdirection":return e.invertBeamDirection=i,!0;case"preferredbeamdirection":return e.preferredBeamDirection=fi.parseEnum(i,W),!0;case"beamingmode":return e.beamingMode=fi.parseEnum(i,L),!0}return!1}}class zi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("beats",e.beats.map((e=>Wi.toJson(e)))),t.set("isempty",e.isEmpty),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"beats":e.beats=[];for(const t of i){const i=new xe;Wi.fromJson(i,t),e.addBeat(i)}return!0;case"isempty":return e.isEmpty=i,!0}return!1}}class Ui{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("clef",e.clef),t.set("clefottava",e.clefOttava),t.set("voices",e.voices.map((e=>zi.toJson(e)))),t.set("similemark",e.simileMark),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"clef":return e.clef=fi.parseEnum(i,n),!0;case"clefottava":return e.clefOttava=fi.parseEnum(i,o),!0;case"voices":e.voices=[];for(const t of i){const i=new Ve;zi.fromJson(i,t),e.addVoice(i)}return!0;case"similemark":return e.simileMark=fi.parseEnum(i,h),!0}return!1}}class Xi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("name",e.name),t.set("firstfret",e.firstFret),t.set("strings",e.strings),t.set("barrefrets",e.barreFrets),t.set("showname",e.showName),t.set("showdiagram",e.showDiagram),t.set("showfingering",e.showFingering),t}static setProperty(e,t,i){switch(t){case"name":return e.name=i,!0;case"firstfret":return e.firstFret=i,!0;case"strings":return e.strings=i,!0;case"barrefrets":return e.barreFrets=i,!0;case"showname":return e.showName=i,!0;case"showdiagram":return e.showDiagram=i,!0;case"showfingering":return e.showFingering=i,!0}return!1}}class Yi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("isstandard",e.isStandard),t.set("name",e.name),t.set("tunings",e.tunings),t}static setProperty(e,t,i){switch(t){case"isstandard":return e.isStandard=i,!0;case"name":return e.name=i,!0;case"tunings":return e.tunings=i,!0}return!1}}class qi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("bars",e.bars.map((e=>Ui.toJson(e))));{const i=new Map;t.set("chords",i);for(const[t,s]of e.chords)i.set(t.toString(),Xi.toJson(s))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",Yi.toJson(e.stringTuning)),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,i){switch(t){case"bars":e.bars=[];for(const t of i){const i=new he;Ui.fromJson(i,t),e.addBar(i)}return!0;case"chords":return e.chords=new Map,fi.forEach(i,((t,i)=>{const s=new Pe;Xi.fromJson(s,t),e.addChord(i,s)})),!0;case"capo":return e.capo=i,!0;case"transpositionpitch":return e.transpositionPitch=i,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=i,!0;case"showtablature":return e.showTablature=i,!0;case"showstandardnotation":return e.showStandardNotation=i,!0;case"ispercussion":return e.isPercussion=i,!0;case"standardnotationlinecount":return e.standardNotationLineCount=i,!0}return["stringtuning"].indexOf(t)>=0&&(Yi.fromJson(e.stringTuning,i),!0)}}class Ji{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("volume",e.volume),t.set("balance",e.balance),t.set("port",e.port),t.set("program",e.program),t.set("primarychannel",e.primaryChannel),t.set("secondarychannel",e.secondaryChannel),t.set("ismute",e.isMute),t.set("issolo",e.isSolo),t}static setProperty(e,t,i){switch(t){case"volume":return e.volume=i,!0;case"balance":return e.balance=i,!0;case"port":return e.port=i,!0;case"program":return e.program=i,!0;case"primarychannel":return e.primaryChannel=i,!0;case"secondarychannel":return e.secondaryChannel=i,!0;case"ismute":return e.isMute=i,!0;case"issolo":return e.isSolo=i,!0}return!1}}class ji{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("elementtype",e.elementType),t.set("staffline",e.staffLine),t.set("noteheaddefault",e.noteHeadDefault),t.set("noteheadhalf",e.noteHeadHalf),t.set("noteheadwhole",e.noteHeadWhole),t.set("techniquesymbol",e.techniqueSymbol),t.set("techniquesymbolplacement",e.techniqueSymbolPlacement),t.set("outputmidinumber",e.outputMidiNumber),t}static setProperty(e,t,i){switch(t){case"elementtype":return e.elementType=i,!0;case"staffline":return e.staffLine=i,!0;case"noteheaddefault":return e.noteHeadDefault=fi.parseEnum(i,P),!0;case"noteheadhalf":return e.noteHeadHalf=fi.parseEnum(i,P),!0;case"noteheadwhole":return e.noteHeadWhole=fi.parseEnum(i,P),!0;case"techniquesymbol":return e.techniqueSymbol=fi.parseEnum(i,P),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=fi.parseEnum(i,C),!0;case"outputmidinumber":return e.outputMidiNumber=i,!0}return!1}}class Qi{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("staves",e.staves.map((e=>qi.toJson(e)))),t.set("playbackinfo",Ji.toJson(e.playbackInfo)),t.set("color",Re.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("percussionarticulations",e.percussionArticulations.map((e=>ji.toJson(e)))),t}static setProperty(e,t,i){switch(t){case"staves":e.staves=[];for(const t of i){const i=new Ge;qi.fromJson(i,t),e.addStaff(i)}return!0;case"color":return e.color=Re.fromJson(i),!0;case"name":return e.name=i,!0;case"shortname":return e.shortName=i,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of i){const i=new ye;ji.fromJson(i,t),e.percussionArticulations.push(i)}return!0}return["playbackinfo"].indexOf(t)>=0&&(Ji.fromJson(e.playbackInfo,i),!0)}}class $i{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("hidedynamics",e.hideDynamics),t}static setProperty(e,t,i){return"hidedynamics"===t&&(e.hideDynamics=i,!0)}}class Ki{static fromJson(e,t){t&&fi.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("album",e.album),t.set("artist",e.artist),t.set("copyright",e.copyright),t.set("instructions",e.instructions),t.set("music",e.music),t.set("notices",e.notices),t.set("subtitle",e.subTitle),t.set("title",e.title),t.set("words",e.words),t.set("tab",e.tab),t.set("tempo",e.tempo),t.set("tempolabel",e.tempoLabel),t.set("masterbars",e.masterBars.map((e=>Gi.toJson(e)))),t.set("tracks",e.tracks.map((e=>Qi.toJson(e)))),t.set("stylesheet",$i.toJson(e.stylesheet)),t}static setProperty(e,t,i){switch(t){case"album":return e.album=i,!0;case"artist":return e.artist=i,!0;case"copyright":return e.copyright=i,!0;case"instructions":return e.instructions=i,!0;case"music":return e.music=i,!0;case"notices":return e.notices=i,!0;case"subtitle":return e.subTitle=i,!0;case"title":return e.title=i,!0;case"words":return e.words=i,!0;case"tab":return e.tab=i,!0;case"tempo":return e.tempo=i,!0;case"tempolabel":return e.tempoLabel=i,!0;case"masterbars":e.masterBars=[];for(const t of i){const i=new Ce;Gi.fromJson(i,t),e.addMasterBar(i)}return!0;case"tracks":e.tracks=[];for(const t of i){const i=new He;Qi.fromJson(i,t),e.addTrack(i)}return!0}return["stylesheet"].indexOf(t)>=0&&($i.fromJson(e.stylesheet,i),!0)}}class Zi{static jsonReplacer(e,t){if(t instanceof Map){if("fromEntries"in Object)return Object.fromEntries(t);{const e={};for(const[i,s]of t)e[i]=s;return e}}return ArrayBuffer.isView(t)?Array.apply([],[t]):t}static scoreToJson(e){let t=Zi.scoreToJsObject(e);return JSON.stringify(t,Zi.jsonReplacer)}static jsonToScore(e,t){return Zi.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return Ki.toJson(e)}static jsObjectToScore(e,t){let i=new Me;return Ki.fromJson(i,e),i.finish(null!=t?t:new Di),i}static settingsToJson(e){let t=Zi.settingsToJsObject(e);return JSON.stringify(t,Zi.jsonReplacer)}static jsonToSettings(e){return Zi.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Mi.toJson(e)}static jsObjectToSettings(e){let t=new Di;return Mi.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new ui;t.division=e.division;let i=e.events;for(let e of i){let i=Zi.jsObjectToMidiEvent(e);t.events.push(i)}return t}static jsObjectToMidiEvent(e){let t,i=e.track,s=e.tick,a=e.message;switch(e.type){case"SystemExclusiveEvent":t=new Et(i,s,0,0,e.data),t.message=a;break;case"MetaDataEvent":t=new pi(i,s,0,0,e.data),t.message=a;break;case"MetaNumberEvent":t=new gi(i,s,0,0,e.value),t.message=a;break;case"Midi20PerNotePitchBendEvent":t=new Ii(i,s,0,e.noteKey,e.pitch),t.message=a;break;default:t=new Nt(i,s,0,0,0),t.message=a}return t}static midiFileToJsObject(e){let t={};t.division=e.division;let i=[];t.events=i;for(let t of e.events)i.push(Zi.midiEventToJsObject(t));return t}static midiEventToJsObject(e){let t={};return t.track=e.track,t.tick=e.tick,t.message=e.message,e instanceof Et?(t.type="SystemExclusiveEvent",t.data=e.data):e instanceof pi?(t.type="MetaDataEvent",t.data=e.data):e instanceof gi?(t.type="MetaNumberEvent",t.value=e.value):e instanceof Ii&&(t.type="Midi20PerNotePitchBendEvent",t.noteKey=e.noteKey,t.pitch=e.pitch),t}}class es{constructor(){this.ready=new oi,this.samplesPlayed=new hi,this.sampleRequest=new oi}get sampleRate(){return es.preferredSampleRate}open(){ge.debug("AlphaSynth","Initializing webworker worker"),this._worker=mo.globalThis,this._worker.addEventListener("message",this.handleMessage.bind(this)),this.ready.trigger()}destroy(){this._worker.postMessage({cmd:"alphaSynth.output.destroy"})}handleMessage(e){let t=e.data;switch(t.cmd){case es.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case es.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(){}}es.CmdOutputPrefix="alphaSynth.output.",es.CmdOutputAddSamples=es.CmdOutputPrefix+"addSamples",es.CmdOutputPlay=es.CmdOutputPrefix+"play",es.CmdOutputPause=es.CmdOutputPrefix+"pause",es.CmdOutputResetSamples=es.CmdOutputPrefix+"resetSamples",es.CmdOutputSampleRequest=es.CmdOutputPrefix+"sampleRequest",es.CmdOutputSamplesPlayed=es.CmdOutputPrefix+"samplesPlayed",es.preferredSampleRate=0;class ts{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new ci(new es,t),this._player.positionChanged.on(this.onPositionChanged.bind(this)),this._player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this._player.finished.on(this.onFinished.bind(this)),this._player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.midiLoaded.on(this.onMidiLoaded.bind(this)),this._player.midiLoadFailed.on(this.onMidiLoadFailed.bind(this)),this._player.readyForPlayback.on(this.onReadyForPlayback.bind(this)),this._player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this._player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this._main.postMessage({cmd:"alphaSynth.ready"})}static init(){let e=mo.globalThis;e.addEventListener("message",(t=>{let i=t.data;if("alphaSynth.initialize"===i.cmd)es.preferredSampleRate=i.sampleRate,ge.logLevel=i.logLevel,mo.globalThis.alphaSynthWebWorker=new ts(e,i.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":ge.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(Zi.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(Zi.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"})}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){let t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map(Zi.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class is{static generateFontLookup(e){if(!is.FontSizeLookupTables.has(e))if(mo.isRunningInWorker)is.FontSizeLookupTables.set(e,new Uint8Array([8]));else{let t=document.createElement("canvas").getContext("2d");t.font=`11px ${e}`;let i=[];for(let e=32;e<255;e++){let s=String.fromCharCode(e);i.push(t.measureText(s).width)}let s=new Uint8Array(i);is.FontSizeLookupTables.set(e,s)}}static measureString(e,t,i,s,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(is.FontSizeLookupTables.has(t[e])){n=t[e];break}is.FontSizeLookupTables.has(n)||is.generateFontLookup(n),r=is.FontSizeLookupTables.get(n);let o=1;s===Z.Italic&&(o*=1.2),a===ee.Bold&&(o*=1.2);let h=0;for(let t=0;t<e.length;t++){let s=Math.min(r.length-1,e.charCodeAt(t)-32);s>=0&&(h+=r[s]*i/11)}return h*o}}is.Georgia=new Uint8Array([3,4,5,7,7,9,8,2,4,4,5,7,3,4,3,5,7,5,6,6,6,6,6,6,7,6,3,3,7,7,7,5,10,7,7,7,8,7,7,8,9,4,6,8,7,10,8,8,7,8,8,6,7,8,7,11,8,7,7,4,5,4,7,7,6,6,6,5,6,5,4,6,6,3,3,6,3,10,6,6,6,6,5,5,4,6,5,8,6,5,5,5,4,5,7,6,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,4,6,7,6,7,4,6,6,10,6,6,7,0,10,7,5,7,6,6,6,6,6,3,6,6,6,6,12,12,12,5,7,7,7,7,7,7,11,7,7,7,7,7,4,4,4,4,8,8,8,8,8,8,8,7,8,8,8,8,8,7,7,6,6,6,6,6,6,6,8,5,5,5,5,5,3,3,3,3,6,6,6,6,6,6,6,7,6,6,6,6,6,5,6]),is.Arial=new Uint8Array([3,3,4,6,6,10,7,2,4,4,4,6,3,4,3,3,6,6,6,6,6,6,6,6,6,6,3,3,6,6,6,6,11,7,7,8,8,7,7,9,8,3,6,7,6,9,8,9,7,9,8,7,7,8,7,10,7,7,7,3,3,3,5,6,4,6,6,6,6,6,3,6,6,2,2,6,2,9,6,6,6,6,4,6,3,6,6,8,6,6,6,4,3,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,6,6,6,6,3,6,4,8,4,6,6,0,8,6,4,6,4,4,4,6,6,4,4,4,4,6,9,9,9,7,7,7,7,7,7,7,11,8,7,7,7,7,3,3,3,3,8,8,9,9,9,9,9,6,9,8,8,8,8,7,7,7,6,6,6,6,6,6,10,6,6,6,6,6,3,3,3,3,6,6,6,6,6,6,6,6,7,6,6,6,6,6,6]),is.FontSizeLookupTables=new Map([["Arial",is.Arial],["'Arial'",is.Arial],['"Arial"',is.Arial],["Georgia",is.Georgia],["'Georgia'",is.Georgia],['"Georgia"',is.Georgia]]),is.ControlChars=32;class ss{constructor(){this.id=me.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 as{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(let i of this.beats)if(!t||i.realBounds.x<e)t=i;else if(i.realBounds.x>e)break;return t}finish(){this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x))}}class rs{constructor(){this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const i=this.notes;if(!i)return null;for(let s of i){let i=s.noteHeadBounds.y+s.noteHeadBounds.h,a=s.noteHeadBounds.x+s.noteHeadBounds.w;if(s.noteHeadBounds.x<=e&&s.noteHeadBounds.y<=t&&e<=a&&t<=i)return s.note}return null}}class ns{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staveGroupBounds=null}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let i=null;for(let t of this.bars){let s=t.findBeatAtPos(e);if(s&&(!i||i.realBounds.x<s.realBounds.x)){const t=Math.abs(s.realBounds.x-e);(!i||t<1e7)&&(i=s)}}return i?i.beat:null}finish(){this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const e of this.bars)e.finish()}addBeat(e){this.staveGroupBounds.boundsLookup.addBeat(e)}}class os{}class hs{constructor(){this.index=0,this.bars=[]}finish(){for(let e of this.bars)e.finish()}addBar(e){this.boundsLookup.addMasterBar(e),e.staveGroupBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(let i of this.bars)if(!t||i.realBounds.x<e)t=i;else if(e>i.realBounds.x+i.realBounds.w)break;return t}}class ls{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaveGroup=null,this.staveGroups=[],this.isFinished=!1}toJson(){let e={},t=[];e.staveGroups=t;for(let e of this.staveGroups){let i={};i.visualBounds=this.boundsToJson(e.visualBounds),i.realBounds=this.boundsToJson(e.realBounds),i.bars=[];for(let t of e.bars){let e={};e.lineAlignedBounds=this.boundsToJson(t.lineAlignedBounds),e.visualBounds=this.boundsToJson(t.visualBounds),e.realBounds=this.boundsToJson(t.realBounds),e.index=t.index,e.bars=[];for(let i of t.bars){let t={};t.visualBounds=this.boundsToJson(i.visualBounds),t.realBounds=this.boundsToJson(i.realBounds),t.beats=[];for(let e of i.beats){let i={};i.visualBounds=this.boundsToJson(e.visualBounds),i.realBounds=this.boundsToJson(e.realBounds);let s=i;if(s.beatIndex=e.beat.index,s.voiceIndex=e.beat.voice.index,s.barIndex=e.beat.voice.bar.index,s.staffIndex=e.beat.voice.bar.staff.index,s.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){let t=i.notes=[];for(let i of e.notes){let e={};e.index=i.note.index,e.noteHeadBounds=this.boundsToJson(i.noteHeadBounds),t.push(e)}}t.beats.push(i)}e.bars.push(t)}i.bars.push(e)}t.push(i)}return e}static fromJson(e,t){let i=new ls,s=e.staveGroups;for(let e of s){let s=new hs;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds,i.addStaveGroup(s);for(let i of e.bars){let e=new ns;e.index=i.index,e.isFirstOfLine=i.isFirstOfLine,e.lineAlignedBounds=i.lineAlignedBounds,e.visualBounds=i.visualBounds,e.realBounds=i.realBounds,s.addBar(e);for(let s of i.bars){let i=new as;i.visualBounds=s.visualBounds,i.realBounds=s.realBounds,e.addBar(i);for(let e of s.beats){let s=new rs;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds;let a=e;if(s.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){s.notes=[];for(let t of e.notes){let e=new os,i=t;e.note=s.beat.notes[i.index],e.noteHeadBounds=t.noteHeadBounds,s.addNote(e)}}i.addBeat(s)}}}}return i}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(){for(let e of this.staveGroups)e.finish();this.isFinished=!0}addStaveGroup(e){e.index=this.staveGroups.length,e.boundsLookup=this,this.staveGroups.push(e),this._currentStaveGroup=e}addMasterBar(e){e.staveGroupBounds?this._masterBarLookup.set(e.index,e):(e.staveGroupBounds=this._currentStaveGroup,this._masterBarLookup.set(e.index,e),this._currentStaveGroup.addBar(e))}addBeat(e){var t;this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),null===(t=this._beatLookup.get(e.beat.id))||void 0===t||t.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){let t=e.index;return this._masterBarLookup.has(t)?this._masterBarLookup.get(t):null}findBeat(e){const t=this.findBeats(e);return t?t[0]:null}findBeats(e){let t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let i=0,s=this.staveGroups.length-1,a=-1;for(;i<=s;){let e=(s+i)/2|0,r=this.staveGroups[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?s=e-1:i=e+1}if(-1===a)return null;let r=this.staveGroups[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,i){const s=this.findBeats(e);if(s)for(const e of s){const s=e.findNoteAtPos(t,i);if(s)return s}return null}}class ds{constructor(t){this._currentLayoutMode=e.LayoutMode.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new hi,this.renderFinished=new hi,this.partialRenderFinished=new hi,this.partialLayoutFinished=new hi,this.postRenderFinished=new oi,this.error=new hi,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas=mo.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=mo.getLayoutEngineFactory(this.settings.display.layoutMode).createLayout(this),this._currentLayoutMode=this.settings.display.layoutMode,!0)}renderScore(e,t){try{this.score=e;let i=null;if(null!=e&&null!=t){if(t){i=[];for(let s of t)s>=0&&s<e.tracks.length&&i.push(e.tracks[s])}else i=e.tracks.slice(0);0===i.length&&e.tracks.length>0&&i.push(e.tracks[0])}this.tracks=i,this.render()}catch(e){this.error.trigger(e)}}renderTracks(e){0===e.length?this.score=null:this.score=e[0].score,this.tracks=e,this.render()}updateSettings(e){this.settings=e}renderResult(e){try{const t=this.layout;t?(ge.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):ge.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 ls,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){ge.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];ge.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),ge.debug("Rendering","Rendering finished")}else ge.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),ge.debug("Rendering","Clearing finished");else ge.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(ge.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(ge.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new ls,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):ge.warning("Rendering","Current layout does not support dynamic resizing, nothing was done",null),ge.debug("Rendering","Resize finished")}layoutAndRender(){ge.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){var e;null===(e=this.boundsLookup)||void 0===e||e.finish();const t=new ss;t.totalHeight=this.layout.height,t.totalWidth=this.layout.width,t.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(t)}}class cs{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){mo.globalThis.alphaTabWebWorker=new cs(mo.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=Zi.jsObjectToSettings(t.settings);ge.logLevel=e.core.logLevel,this._renderer=new ds(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{var e,t;this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:null!==(t=null===(e=this._renderer.boundsLookup)||void 0===e?void 0:e.toJson())&&void 0!==t?t:null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);let i=null==t.score?null:Zi.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(i,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){is.FontSizeLookupTables||(is.FontSizeLookupTables=new Map);for(let t in e)is.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){Mi.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){ge.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class us{constructor(){this._canvas=null,this._color=new Re(0,0,0,255),this._font=new bi("Arial",10,Z.Plain),this._lineWidth=0;let e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);let t=window.getComputedStyle(e),i=t.fontFamily;(i.startsWith('"')||i.startsWith("'"))&&(i=i.substr(1,i.length-2)),this._musicFont=new bi(i,parseFloat(t.fontSize),Z.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}onRenderFinished(){return null}beginRender(e,t){this._canvas=document.createElement("canvas"),this._canvas.width=e*mo.HighDpiFactor|0,this._canvas.height=t*mo.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(mo.HighDpiFactor,mo.HighDpiFactor),this._context.lineWidth=this._lineWidth}endRender(){let e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,i,s){i>0&&this._context.fillRect(0|e,0|t,i,s)}strokeRect(e,t,i,s){this._context.strokeRect(0|e,0|t,i,s)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,i,s){this._context.quadraticCurveTo(e,t,i,s)}bezierCurveTo(e,t,i,s,a,r){this._context.bezierCurveTo(e,t,i,s,a,r)}fillCircle(e,t,i){this._context.beginPath(),this._context.arc(e,t,i,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,i){this._context.beginPath(),this._context.arc(e,t,i,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(this.settings.display.scale)),this._measureContext.font=e.toCssString(this.settings.display.scale)}get textAlign(){switch(this._context.textAlign){case"left":default:return E.Left;case"center":return E.Center;case"right":return E.Right}}set textAlign(e){switch(e){case E.Left:this._context.textAlign="left";break;case E.Center:this._context.textAlign="center";break;case E.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return C.Top;case"middle":return C.Middle;case"bottom":return C.Bottom}}set textBaseline(e){switch(e){case C.Top:this._context.textBaseline="hanging";break;case C.Middle:this._context.textBaseline="middle";break;case C.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,i){this._context.fillText(e,t,i)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,i,s,a=!1){s!==P.None&&this.fillMusicFontSymbolText(e,t,i,String.fromCharCode(s),a)}fillMusicFontSymbols(e,t,i,s,a=!1){let r="";for(let e of s)e!==P.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a=!1){let r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(i),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(s,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,i){this._context.save(),this._context.translate(e,t),this._context.rotate(i*Math.PI/180)}endRotate(){this._context.restore()}}class ps{constructor(e){this._midiFile=e}addTimeSignature(e,t,i){let s=0;for(;(i>>=1)>0;)s++;const a=new pi(0,e,255,X.TimeSignature,new Uint8Array([255&t,255&s,48,8]));this._midiFile.addEvent(a)}addRest(e,t,i){const s=new Et(e,t,Y.SystemExclusive,Et.AlphaTabManufacturerId,new Uint8Array([q.Rest]));this._midiFile.addEvent(s)}addNote(e,t,i,s,a,r){const n=le.dynamicToVelocity(a),o=new Nt(e,t,this.makeCommand(U.NoteOn,r),ps.fixValue(s),ps.fixValue(n));this._midiFile.addEvent(o);const h=new Nt(e,t+i,this.makeCommand(U.NoteOff,r),ps.fixValue(s),ps.fixValue(n));this._midiFile.addEvent(h)}makeCommand(e,t){return 240&e|15&t}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,i,s,a){const r=new Nt(e,t,this.makeCommand(U.Controller,i),ps.fixValue(s),ps.fixValue(a));this._midiFile.addEvent(r)}addProgramChange(e,t,i,s){const a=new Nt(e,t,this.makeCommand(U.ProgramChange,i),ps.fixValue(s),0);this._midiFile.addEvent(a)}addTempo(e,t){const i=6e7/t|0,s=new gi(0,e,255,X.Tempo,i);this._midiFile.addEvent(s)}addBend(e,t,i,s){s=s>=Ft.MaxPitchWheel?Ft.MaxPitchWheel:Math.floor(s);const a=new Nt(e,t,this.makeCommand(U.PitchBend,i),127&s,s>>7&127);this._midiFile.addEvent(a)}addNoteBend(e,t,i,s,a){a=(a=a>=Ft.MaxPitchWheel?Ft.MaxPitchWheel:Math.floor(a))*Ft.MaxPitchWheel20/Ft.MaxPitchWheel;const r=new Ii(e,t,this.makeCommand(U.PerNotePitchBend,i),s,a);this._midiFile.addEvent(r)}finishTrack(e,t){const i=new pi(e,t,255,X.EndOfTrack,new Uint8Array(0));this._midiFile.addEvent(i)}}class gs{constructor(){this._highlightedBeats=new Map,this.index=0,this.start=0,this.end=0,this.isEmptyBar=!1,this.beatsToHighlight=[]}highlightBeat(e){this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.beatsToHighlight.push(e))}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(ie||(ie={}));class fs{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}class ms{constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}get finished(){return this.index>=this._score.masterBars.length}processCurrent(){const e=this._score.masterBars[this.index];let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const t=new fs(e.repeatGroup,e);this._repeatStack.push(t),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],i=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=0!=(t&1<<i)}this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class ys{constructor(){this.start=0,this.end=0,this.tempo=0,this.beats=[],this.nextMasterBar=null}finish(){this.beats.sort(((e,t)=>e.start-t.start))}addBeat(e){e.masterBar=this,e.index=this.beats.length,this.beats.push(e)}}class bs{constructor(){this.duration=0,this.tickDuration=0,this.nextBeatLookup=null}get currentBeat(){return this.currentBeatLookup.beat}get nextBeat(){var e,t;return null!==(t=null===(e=this.nextBeatLookup)||void 0===e?void 0:e.beat)&&void 0!==t?t:null}}class Ss{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}finish(){let e=null,t=[];for(let i of this.masterBars){i.finish(),e&&(e.nextMasterBar=i);for(const e of i.beats){const i=[];for(let s of t)s.end>e.start&&(i.push(s),e.highlightBeat(s.beat),e.start<=s.start&&s.highlightBeat(e.beat));i.push(e),t=i}e=i}}findBeat(e,t,i=null){const s=new Map;for(const t of e)s.set(t.index,!0);let a=null;return i&&(a=this.findBeatFast(s,i,t)),a||(a=this.findBeatSlow(s,t)),a}findBeatFast(e,t,i){const s=t.currentBeatLookup.start+t.tickDuration;return i>=t.currentBeatLookup.start&&i<s?t:t.nextBeatLookup&&i>=t.nextBeatLookup.start&&i<t.nextBeatLookup.end?this.createResult(t.nextBeatLookup,e):null}findBeatSlow(e,t){const i=this.findMasterBar(t);if(!i)return null;let s=null,a=i.beats;for(let i=0;i<a.length;i++){let r=a[i];if(e.has(r.beat.voice.bar.staff.track.index))if(r.start<=t&&t<r.end)(!s||s.start<r.start)&&(s=a[i]);else if(r.end>t)break}return s?this.createResult(s,e):null}createResult(e,t){const i=this.findNextBeat(e,t),s=new bs;return s.currentBeatLookup=e,s.nextBeatLookup=i,s.tickDuration=i?i.start-e.start:e.end-e.start,s.duration=le.ticksToMillis(s.tickDuration,e.masterBar.tempo),s.beatsToHighlight=e.beatsToHighlight,s}findNextBeat(e,t){const i=e.masterBar;let s=i.beats,a=null;for(let i=e.index+1;i<s.length;i++){const r=s[i];if(r.start>e.start&&t.has(r.beat.voice.bar.staff.track.index)){a=r;break}}if(!a&&i.nextMasterBar){s=i.nextMasterBar.beats;for(let e=0;e<s.length;e++){const i=s[e];if(t.has(i.beat.voice.bar.staff.track.index)){a=i;break}}}return a}findMasterBar(e){const t=this.masterBars;let i=0,s=t.length-1;for(;i<=s;){const a=(s+i)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?s=a-1:i=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new ys;return t.masterBar=e,t}return this.masterBarLookup.get(e.index)}getMasterBarStart(e){return this.masterBarLookup.has(e.index)?this.masterBarLookup.get(e.index).start:0}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e){var t;null===(t=this._currentMasterBar)||void 0===t||t.addBeat(e)}}class _s{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class ws{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Bs{constructor(e,t,i){this._currentTempo=0,this._currentBarRepeatLookup=null,this._programsPerChannel=new Map,this.tickLookup=new Ss,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Di,this._currentTempo=this._score.tempo,this._handler=i}generate(){for(const e of this._score.tracks)this.generateTrack(e);ge.debug("Midi","Begin midi generation");const e=new ms(this._score);let t=null;for(;!e.finished;){const i=e.index,s=this._score.masterBars[i],a=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(s,t,a);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],a)}e.moveNext(),t=s}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);this.tickLookup.finish(),ge.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,i,s){this._programsPerChannel.has(i)&&this._programsPerChannel.get(i)===s||(this._handler.addProgramChange(e.index,t,i,s),this._programsPerChannel.set(i,s))}generateChannel(e,t,i){let s=Bs.toChannelShort(i.volume),a=Bs.toChannelShort(i.balance);this._handler.addControlChange(e.index,0,t,ie.VolumeCoarse,s),this._handler.addControlChange(e.index,0,t,ie.PanCoarse,a),this._handler.addControlChange(e.index,0,t,ie.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,ie.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,ie.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,ie.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,ie.DataEntryCoarse,Bs.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,i.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(i,e.timeSignatureNumerator,e.timeSignatureDenominator),e.tempoAutomation?(this._handler.addTempo(i,e.tempoAutomation.value),this._currentTempo=e.tempoAutomation.value):t||(this._handler.addTempo(i,e.score.tempo),this._currentTempo=e.score.tempo);const s=new ys;s.masterBar=e,s.start=i,s.tempo=this._currentTempo,s.end=s.start+e.calculateDuration(),this.tickLookup.addMasterBar(s)}generateBar(e,t){let i=this.getPlaybackBar(e);this._currentBarRepeatLookup=null;for(const s of i.voices)this.generateVoice(s,t,e)}getPlaybackBar(e){switch(e.simileMark){case h.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case h.FirstOfDouble:case h.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,i){if(!e.isEmpty||e.bar.isEmpty&&0===e.index)for(const s of e.beats)this.generateBeat(s,t,i)}generateBeat(e,t,i){let s=e.playbackStart,a=e.playbackDuration;e.voice.bar.isEmpty?a=e.voice.bar.masterBar.calculateDuration():e.voice.bar.masterBar.tripletFeel!==R.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(s-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Bs.calculateTripletFeelInfo(s,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration)));const r=new gs;r.start=t+s;const n=e.nextBeat?e.nextBeat.absolutePlaybackStart-e.absolutePlaybackStart:a;r.end=t+s,r.highlightBeat(e),r.end+=n>a?n:a,i===e.voice.bar?(r.beat=e,this.tickLookup.addBeat(r)):(r.isEmptyBar=!0,r.beat=i.voices[0].beats[0],this._currentBarRepeatLookup?this._currentBarRepeatLookup.end=r.end:(this._currentBarRepeatLookup=r,this.tickLookup.addBeat(this._currentBarRepeatLookup)));const o=e.voice.bar.staff.track;for(const i of e.automations)this.generateAutomation(e,i,t);if(e.isRest)this._handler.addRest(o.index,t+s,o.playbackInfo.primaryChannel);else{let i=this.getBrushInfo(e);for(const r of e.notes)this.generateNote(r,t+s,a,i)}if(e.vibrato!==w.None){let i=240,a=3;switch(e.vibrato){case w.Slight:i=this._settings.player.vibrato.beatSlightLength,a=this._settings.player.vibrato.beatSlightAmplitude;break;case w.Wide:i=this._settings.player.vibrato.beatWideLength,a=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+s,e.playbackDuration,i,a,((t,i)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,i)}))}}static calculateTripletFeelInfo(e,t,i){let s;switch(i.voice.bar.masterBar.tripletFeel){case R.Triplet8th:case R.Dotted8th:case R.Scottish8th:s=p.Eighth;break;case R.Triplet16th:case R.Dotted16th:case R.Scottish16th:s=p.Sixteenth;break;default:return null}const a=le.toTicks(s);if(t!==a)return null;if(e%a!=0)return null;if(!i.nextBeat||i.nextBeat.voice!==i.voice||i.playbackDuration!==a)return null;const r=new ws;switch(i.voice.bar.masterBar.tripletFeel){case R.Triplet8th:r.firstBeatDuration=le.applyTuplet(le.toTicks(p.Quarter),3,2),r.secondBeatDuration=le.applyTuplet(le.toTicks(p.Eighth),3,2);break;case R.Dotted8th:r.firstBeatDuration=le.applyDot(le.toTicks(p.Eighth),!1),r.secondBeatDuration=le.toTicks(p.Sixteenth);break;case R.Scottish8th:r.firstBeatDuration=le.toTicks(p.Sixteenth),r.secondBeatDuration=le.applyDot(le.toTicks(p.Eighth),!1);break;case R.Triplet16th:r.firstBeatDuration=le.applyTuplet(le.toTicks(p.Eighth),3,2),r.secondBeatDuration=le.applyTuplet(le.toTicks(p.Sixteenth),3,2);break;case R.Dotted16th:r.firstBeatDuration=le.applyDot(le.toTicks(p.Sixteenth),!1),r.secondBeatDuration=le.toTicks(p.ThirtySecond);break;case R.Scottish16th:r.firstBeatDuration=le.toTicks(p.ThirtySecond),r.secondBeatDuration=le.applyDot(le.toTicks(p.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,i,s){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.realValue;if(e.isPercussion){const t=be.getArticulation(e);t&&(n=t.outputMidiNumber)}const o=e.isStringed&&e.string<=s.length?s[e.string-1]:0,h=t+o,l=this.getNoteDuration(e,i);l.untilTieOrSlideEnd-=o,l.noteOnly-=o,l.letRingEnd-=o;const d=Bs.getDynamicValue(e),c=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==w.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Bs.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Bs.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===_.Legato?-1:Bs.getPitchWheel(0),u>=0&&this._handler.addNoteBend(a.index,h,c,n,u),e.beat.fadeIn&&this.generateFadeIn(e,h,l),!e.isTrill||r.isPercussion){if(e.beat.isTremolo)this.generateTremoloPicking(e,h,l,n,d,c);else if(e.hasBend?this.generateBend(e,h,l,n,c):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,h,l,c):e.slideInType!==S.None||e.slideOutType!==_.None?this.generateSlide(e,h,l,n,d,c):(e.vibrato!==w.None||e.isTieDestination&&e.tieOrigin.vibrato!==w.None)&&this.generateVibrato(e,h,l,n,c),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===_.Legato)){let e=Math.max(l.untilTieOrSlideEnd,l.letRingEnd);this._handler.addNote(a.index,h,e,n,d,c)}}else this.generateTrill(e,h,l,n,d,c)}getNoteDuration(t,i){const s=new _s;if(s.noteOnly=i,s.untilTieOrSlideEnd=i,s.letRingEnd=i,t.isDead)return s.noteOnly=this.applyStaticDuration(Bs.DefaultDurationDead,i),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isPalmMute)return s.noteOnly=this.applyStaticDuration(Bs.DefaultDurationPalmMute,i),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isStaccato)return s.noteOnly=i/2|0,s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isTieOrigin){const e=t.tieDestination;if(e)if(t.isTieDestination){const t=this.getNoteDuration(e,e.beat.playbackDuration);s.untilTieOrSlideEnd=i+t.untilTieOrSlideEnd}else{const i=t.beat.absolutePlaybackStart,a=this.getNoteDuration(e,e.beat.playbackDuration),r=e.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}else if(t.slideOutType===_.Legato){const e=t.slideTarget;if(e){const i=t.beat.absolutePlaybackStart,a=this.getNoteDuration(e,e.beat.playbackDuration),r=e.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}if(t.isLetRing&&this._settings.notation.notationMode===e.NotationMode.GuitarPro){let e=t.beat,a=0;const r=t.beat.voice.bar.masterBar.calculateDuration();for(;e.nextBeat;){let i=e.nextBeat;if(i.isRest)break;if(t.isStringed&&i.hasNoteOnString(t.string))break;if(e=e.nextBeat,a=e.absolutePlaybackStart-t.beat.absolutePlaybackStart+e.playbackDuration,a>r){a=r;break}}e===t.beat?s.letRingEnd=i:s.letRingEnd=a}else s.letRingEnd=s.untilTieOrSlideEnd;return s}applyStaticDuration(e,t){const i=this._currentTempo*e/de.MaxPosition|0;return Math.min(i,t)}static getDynamicValue(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case a.Normal:t++;break;case a.Heavy:t+=2}return t<0&&(t=0),t}generateFadeIn(e,t,i){const s=e.beat.voice.bar.staff.track,a=Bs.toChannelShort(s.playbackInfo.volume)/i.noteOnly,r=i.noteOnly/120|0,n=t+i.noteOnly;for(let e=r-1;e>=0;e--){const i=n-120*e,o=(i-t)*a;e===r-1&&(this._handler.addControlChange(s.index,t,s.playbackInfo.primaryChannel,ie.VolumeCoarse,o),this._handler.addControlChange(s.index,t,s.playbackInfo.secondaryChannel,ie.VolumeCoarse,o)),this._handler.addControlChange(s.index,i,s.playbackInfo.primaryChannel,ie.VolumeCoarse,o),this._handler.addControlChange(s.index,i,s.playbackInfo.secondaryChannel,ie.VolumeCoarse,o)}}generateVibrato(e,t,i,s,a){let r=0,n=0;switch(e.vibrato!==w.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:w.Slight){case w.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case w.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;this.generateVibratorWithParams(t,i.noteOnly,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,s,t)}))}generateVibratorWithParams(e,t,i,s,a){const r=this.vibratoResolution,n=i/2|0,o=(e+=i)+t;for(;e<o;){let t=0;const h=e+i<o?i:o-e;for(;t<h;){let i=s*Math.sin(t*Math.PI/n);a(e+t|0,Bs.getPitchWheel(i)),t+=r}e+=i}}static getPitchWheel(e){return Ft.DefaultPitchWheel+e/2*Bs.PitchValuePerSemitone}generateSlide(e,t,i,s,a,r){let n=e.slideOutType===_.Legato?i.noteOnly:i.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,d=Math.floor(de.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(de.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case S.IntoFromAbove:o.push(new de(0,l)),o.push(new de(d,0));break;case S.IntoFromBelow:o.push(new de(0,-l)),o.push(new de(d,0))}switch(e.slideOutType){case _.Legato:case _.Shift:o.push(new de(c,0));const t=2*(e.slideTarget.realValue-e.realValue);o.push(new de(de.MaxPosition,t));break;case _.OutDown:o.push(new de(de.MaxPosition-d,0)),o.push(new de(de.MaxPosition,-l));break;case _.OutUp:o.push(new de(de.MaxPosition-d,0)),o.push(new de(de.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,((e,t)=>{this._handler.addNoteBend(h.index,e,r,s,t)}))}generateBend(e,t,i,s,a){let r=e.bendPoints,n=e.beat.voice.bar.staff.track;const o=(e,t)=>{this._handler.addNoteBend(n.index,e,a,s,t)};let h,c=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;h=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==f.None){switch(e.tieDestination.bendType){case d.Bend:case d.BendRelease:case d.PrebendBend:c=e.tieDestination.bendPoints[1].value;break;case d.Prebend:case d.PrebendRelease:c=e.tieDestination.bendPoints[0].value}h=Math.max(i.noteOnly,le.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else h=i.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(h,le.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case d.Custom:p=r;break;case d.Bend:case d.Release:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new de(0,e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),p.push(new de(de.MaxPosition,c));break;case l.Fast:return(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void(e.beat.graceType===f.BendGrace?this.generateSongBookWhammyOrBend(t,h,!0,[e.bendPoints[0].value,c],u,o):this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,c],u,o))}break;case d.BendRelease:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new de(0,e.bendPoints[0].value)),p.push(new de(de.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new de(de.MaxPosition,e.bendPoints[2].value));break;case l.Fast:return void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case d.Hold:case d.Prebend:p=r;break;case d.PrebendBend:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new de(0,e.bendPoints[0].value)),p.push(new de(de.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return o(t,0|Bs.getPitchWheel(e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,c],u,o)}break;case d.PrebendRelease:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new de(0,e.bendPoints[0].value)),p.push(new de(de.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return o(t,0|Bs.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,h,p,o)}generateSongBookWhammyOrBend(e,t,i,s,a,r){const n=i?e:e+t-a,o=a/(s.length-1);for(let e=0;e<s.length-1;e++){const t=Bs.getPitchWheel(s[e]),i=Bs.getPitchWheel(s[e+1]),a=n+o*e;this.generateBendValues(a,o,t,i,r)}}generateWhammy(e,t,i,s){const a=e.whammyBarPoints,r=e.voice.bar.staff.track,n=i.noteOnly;a[0].value>0&&!e.isContinuedWhammy&&t--;const o=(e,t)=>{this._handler.addBend(r.index,e,s,t)};let h=[];switch(e.whammyBarType){case F.Custom:h=a;break;case F.Dive:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new de(0,a[0].value)),h.push(new de(de.MaxPosition,a[1].value));break;case l.Fast:const e=Math.min(n,le.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case F.Dip:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new de(0,a[0].value)),h.push(new de(de.MaxPosition/2|0,a[1].value)),h.push(new de(de.MaxPosition,a[2].value));break;case l.Fast:const e=Math.min(n,le.millisToTicks(this._settings.player.songBookDipDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!0,[a[0].value,a[1].value,a[2].value],e,o)}break;case F.Hold:case F.Predive:h=a;break;case F.PrediveDive:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new de(0,a[0].value)),h.push(new de(de.MaxPosition/2|0,a[0].value)),h.push(new de(de.MaxPosition,a[1].value));break;case l.Fast:const e=Bs.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,s,0|e);const i=Math.min(n,le.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],i,o)}}this.generateWhammyOrBend(t,n,h,o)}generateWhammyOrBend(e,t,i,s){const a=t/de.MaxPosition;for(let t=0;t<i.length-1;t++){const r=i[t],n=i[t+1],o=Bs.getPitchWheel(r.value),h=Bs.getPitchWheel(n.value),l=a*(n.offset-r.offset),d=e+a*r.offset;this.generateBendValues(d,l,o,h,s)}}generateBendValues(e,t,i,s,a){const r=le.ticksToMillis(t,this._currentTempo),n=Math.abs(s-i)/Bs.PitchValuePerSemitone,o=Math.max(Bs.MinBreakpointsPerSemitone*n,r/Bs.MillisecondsPerBreakpoint),h=t/o,l=(s-i)/o;for(let t=0;t<o;t++)a(0|e,Math.round(i)),i+=l,e+=h;i<s&&a(0|e,s)}generateTrill(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=le.toTicks(e.trillSpeed),l=!0,d=t,c=t+i.untilTieOrSlideEnd;for(;d+10<c;)d+h>=c&&(h=c-d),this._handler.addNote(n.index,d,h,l?o:s,a,r),l=!l,d+=h}generateTremoloPicking(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track;let o=le.toTicks(e.beat.tremoloSpeed),h=t;const l=t+i.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,s,a,r),h+=o}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType!==c.None){let i=0,s=0;for(const t of e.notes)t.isTieDestination||(i|=1<<t.string-1,s++);if(e.notes.length>0){let a=0;const r=e.brushDuration/(s-1)|0;for(let s=0;s<e.voice.bar.staff.tuning.length;s++){let n=e.brushType===c.ArpeggioDown||e.brushType===c.BrushDown?s:t.length-1-s;0!=(i&1<<n)&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,i){switch(t.type){case r.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&(0|t.value)),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&(0|t.value));break;case r.Balance:let s=Bs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,ie.PanCoarse,s),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,ie.PanCoarse,s);break;case r.Volume:let a=Bs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,ie.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,ie.VolumeCoarse,a)}}prepareSingleBeat(e){let t=-1,i=-1,s=e;for(;s&&(-1===t||-1===i);){for(const s of e.automations)switch(s.type){case r.Instrument:i=s.value;break;case r.Tempo:t=s.value}s=s.previousBeat}const a=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===i&&(i=a.playbackInfo.program);const o=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Bs.toChannelShort(o);this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,ie.VolumeCoarse,h),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,ie.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,0,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Bs.DefaultDurationDead=30,Bs.DefaultDurationPalmMute=80,Bs.PitchBendRangeInSemitones=16,Bs.PitchValuePerSemitone=Ft.DefaultPitchWheel/Bs.PitchBendRangeInSemitones,Bs.MinBreakpointsPerSemitone=6,Bs.MillisecondsPerBreakpoint=150;class Ts{constructor(){this.startTick=0,this.endTick=0}}class ks{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}get scale(){return this.renderer.scale}doLayout(){}paint(e,t,i){}}class vs extends ks{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Ns extends vs{constructor(e,t,i,s){super(e,t),this.glyphScale=0,this.glyphScale=i,this.symbol=s}paint(e,t,i){i.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale*this.scale,this.symbol,!1)}}class xs extends Ns{constructor(e,t,i,s){super(e,t,s?xs.GraceScale:1,xs.getSymbol(i)),this._isGrace=s,this._duration=i}paint(e,t,i){let s=this._isGrace?this.scale:0;i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this.symbol,!1)}doLayout(){let e=(this._isGrace?xs.GraceScale:1)*this.scale;switch(this._duration){case p.QuadrupleWhole:this.width=14*e;break;case p.DoubleWhole:case p.Whole:this.width=14*(this._isGrace?xs.GraceScale:1)*this.scale;break;default:this.width=xs.QuarterNoteHeadWidth*(this._isGrace?xs.GraceScale:1)*this.scale}this.height=xs.NoteHeadHeight*e}static getSymbol(e){switch(e){case p.QuadrupleWhole:return P.NoteheadDoubleWholeSquare;case p.DoubleWhole:return P.NoteheadDoubleWhole;case p.Whole:return P.NoteheadWhole;case p.Half:return P.NoteheadHalf;default:return P.NoteheadBlack}}}xs.GraceScale=.75,xs.NoteHeadHeight=8,xs.QuarterNoteHeadWidth=9;class Ps extends Ns{constructor(e,t,i,s,a){super(e,t,a?xs.GraceScale:1,Ps.getSymbol(i,s,a))}doLayout(){this.width=0}static getSymbol(e,t,i){if(i&&(e=p.Eighth),t===W.Up)switch(e){case p.Eighth:return P.FlagEighthUp;case p.Sixteenth:return P.FlagSixteenthUp;case p.ThirtySecond:return P.FlagThirtySecondUp;case p.SixtyFourth:return P.FlagSixtyFourthUp;case p.OneHundredTwentyEighth:return P.FlagOneHundredTwentyEighthUp;case p.TwoHundredFiftySixth:return P.FlagTwoHundredFiftySixthUp;default:return P.FlagEighthUp}switch(e){case p.Eighth:return P.FlagEighthDown;case p.Sixteenth:return P.FlagSixteenthDown;case p.ThirtySecond:return P.FlagThirtySecondDown;case p.SixtyFourth:return P.FlagSixtyFourthDown;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return P.FlagOneHundredTwentyEighthDown;default:return P.FlagEighthDown}}}Ps.FlagWidth=11;class Es extends ks{constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}get onTimeX(){return this.onNotes.x+this.onNotes.centerX}addTie(e){e.renderer=this.renderer,this.ties.push(e)}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Es.GraceBeatPadding*this.renderer.scale);let i=this.onNotes.computedWidth-this.onNotes.centerX;const s=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(s&&s.hasFlag||this.beat.graceType!==f.None)&&(i+=Ps.FlagWidth*this.scale*(this.beat.graceType!==f.None?xs.GraceScale:1));for(const e of this.ties)i+=e.width;this.beat.graceType!==f.None&&(i+=Es.GraceBeatPadding*this.renderer.scale),e.addBeatSpring(this.beat,t,i),e.setPreBeatSize(this.beat,this.preNotes.computedWidth),e.setOnBeatSize(this.beat,this.onNotes.computedWidth),e.setBeatCenterX(this.beat,this.onNotes.centerX)}applyLayoutingInfo(e){let t=e.getBeatCenterX(this.beat)-this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Es.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=p.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:this.minWidth+=10*this.scale}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return"b"+e.id}paint(e,t,i){if(this.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;i.beginGroup(Es.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,i),this.onNotes.paint(e+this.x,t+this.y,i);let s=e-this.voiceContainer.x-this.renderer.x,a=t-this.voiceContainer.y-this.renderer.y;for(let e=0,t=this.ties.length;e<t;e++){let t=this.ties[e];t.renderer=this.renderer,t.paint(s,a,i)}i.endGroup()}buildBoundingsLookup(e,t,i,s){let a=new rs;a.beat=this.beat,a.visualBounds=new Qe,a.visualBounds.x=t+this.x+this.onNotes.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.onNotes.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new Qe,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,s&&(a.visualBounds.x=t+this.x,a.realBounds.x=a.visualBounds.x),e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,i+this.y)}}Es.GraceBeatPadding=3;class Cs{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new yo}causeIssue(){return this.settings=null,!0}}class Fs{constructor(e){this.activeBeats=e}}class Ls{constructor(e){this.bounds=null,this.beat=e}}class Ms{constructor(e,t){this._startTime=0,this._trackIndexes=null,this._isDestroyed=!1,this.score=null,this.tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=J.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=J.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new hi,this.activeBeatsChanged=new hi,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new hi,this.beatMouseMove=new hi,this.beatMouseUp=new hi,this.noteMouseDown=new hi,this.noteMouseMove=new hi,this.noteMouseUp=new hi,this.scoreLoaded=new hi,this.resize=new hi,this.renderStarted=new hi,this.renderFinished=new hi,this.postRenderFinished=new oi,this.error=new hi,this.playerReady=new oi,this.playerFinished=new oi,this.soundFontLoaded=new oi,this.midiLoad=new hi,this.midiLoaded=new hi,this.playerStateChanged=new hi,this.playerPositionChanged=new hi,this.midiEventsPlayed=new hi,this.playbackRangeChanged=new hi,this.settingsUpdated=new oi,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),ge.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&mo.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new ds(this.settings),this.container.resize.on(mo.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let i=new Cs;i.oldWidth=this.renderer.width,i.newWidth=0|this.container.width,i.settings=this.settings,this.onResize(i),this.renderer.preRender.on(this.onRenderStarted.bind(this)),this.renderer.renderFinished.on((e=>{this.onRenderFinished(e)})),this.renderer.postRenderFinished.on((()=>{let e=Date.now()-this._startTime;ge.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&&me.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?this.setupPlayer():this.destroyPlayer(),this.onSettingsUpdated()}load(e,t){try{return this.uiFacade.load(e,(e=>{this.renderScore(e,t)}),(e=>{this.onError(e)}))}catch(e){return this.onError(e),!1}}renderScore(e,t){let i=[];if(t)if(0===t.length)e.tracks.length>0&&i.push(e.tracks[0]);else if(1===t.length&&-1===t[0])for(let t of e.tracks)i.push(t);else for(let s of t)s>=0&&s<=e.tracks.length&&i.push(e.tracks[s]);else e.tracks.length>0&&i.push(e.tracks[0]);this.internalRenderTracks(e,i)}renderTracks(t){if(t.length>0){let i=t[0].score;for(let s of t)if(s.score!==i)return void this.onError(new re(e.AlphaTabErrorType.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(i,t)}}internalRenderTracks(e,t){if(me.applyPitchOffsets(this.settings,e),e!==this.score){this.score=e,this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.render()}}triggerResize(){if(this.container.isVisible){let e=new Cs;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 ge.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{ge.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e&&(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight)),this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{let i=new Ye;i.logErrors=!0,i.initFromString(e,this.settings);let s=i.readScore();this.renderScore(s,t)}catch(e){this.onError(e)}}loadSoundFont(e,t=!1){return!!this.player&&this.uiFacade.loadSoundFont(e,t)}resetSoundFonts(){this.player&&this.player.resetSoundFonts()}render(){this.renderer&&(this.uiFacade.canRender?(this.renderer.width=this.container.width,this.renderer.renderScore(this.score,this._trackIndexes)):this.uiFacade.canRenderChanged.on((()=>this.render())))}get tickCache(){return this._tickCache}get isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:J.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=J.Paused,this.destroyCursors())}setupPlayer(){this.updateCursors(),this.player||(this.player=this.uiFacade.createWorkerPlayer(),this.player&&(this.player.ready.on((()=>{this.loadMidiForScore()})),this.player.readyForPlayback.on((()=>{if(this.onPlayerReady(),this.tracks)for(let e of this.tracks){let t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.player||!this.score||!this.player.isReady)return;ge.debug("AlphaTab","Generating Midi");let e=new ui,t=new ps(e),i=new Bs(this.score,this.settings,t);i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e)}changeTrackVolume(e,t){if(this.player)for(let i of e)this.player.setChannelVolume(i.playbackInfo.primaryChannel,t),this.player.setChannelVolume(i.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let i of e)this.player.setChannelSolo(i.playbackInfo.primaryChannel,t),this.player.setChannelSolo(i.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let i of e)this.player.setChannelMute(i.playbackInfo.primaryChannel,t),this.player.setChannelMute(i.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;let t=new ui,i=new ps(t);new Bs(e.voice.bar.staff.track.score,this.settings,i).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new ui,i=new ps(t);new Bs(e.beat.voice.bar.staff.track.score,this.settings,i).generateSingleNote(e),this.player.playOneTimeMidiFile(t)}destroyCursors(){this._cursorWrapper&&(this.uiFacade.destroyCursors(),this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null)}updateCursors(){if(this.settings.player.enableCursor&&!this._cursorWrapper){let e=this.uiFacade.createCursors();e&&(this._cursorWrapper=e.cursorWrapper,this._barCursor=e.barCursor,this._beatCursor=e.beatCursor,this._selectionWrapper=e.selectionWrapper),null!==this._currentBeat&&this.cursorUpdateBeat(this._currentBeat,!1,this._previousTick>10,!0)}else!this.settings.player.enableCursor&&this._cursorWrapper&&this.destroyCursors()}setupPlayerEvents(){this._previousTick=0,this._playerState=J.Paused,this.renderer.postRenderFinished.on((()=>{this._currentBeat=null,this.cursorUpdateTick(this._previousTick,!1,this._previousTick>10)})),this.player&&(this.player.positionChanged.on((e=>{this._previousTick=e.currentTick,this.uiFacade.beginInvoke((()=>{this.cursorUpdateTick(e.currentTick,!1)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===J.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getMasterBarStart(e.currentBeat.voice.bar.masterBar)+e.currentBeat.playbackStart)}})))}cursorUpdateTick(e,t,i=!1){let s=this._tickCache;if(s){let a=this.tracks;if(a.length>0){let r=s.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,i)}}}cursorUpdateBeat(e,t,i,s=!1){const a=e.currentBeat,r=e.nextBeat,n=e.duration,o=e.beatsToHighlight;if(!a)return;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,d=this._previousCursorCache,c=this._previousStateForCursor;if(!s&&a===(null==l?void 0:l.currentBeat)&&h===d&&c===this._playerState)return;let u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,i)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(t){let i=this.uiFacade.getScrollContainer(),s=mo.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,a=this.settings.player.scrollMode;if(s){let s=t.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,a){case e.ScrollMode.Continuous:let a=this.uiFacade.getOffset(i,this.container);this.uiFacade.scrollToY(i,a.y+s,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let r=i.scrollTop+this.uiFacade.getOffset(null,i).h;if(t.visualBounds.y+t.visualBounds.h>=r||t.visualBounds.y<i.scrollTop){let e=t.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(i,e,this.settings.player.scrollSpeed)}}}else{let s=t.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,a){case e.ScrollMode.Continuous:let s=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(i,s,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let a=i.scrollLeft+this.uiFacade.getOffset(null,i).w;if(t.visualBounds.x+t.visualBounds.w>=a||t.visualBounds.x<i.scrollLeft){let e=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(i,e,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(t,i,s,a,r,n,o,h){const l=this._barCursor,d=this._beatCursor;let c=o.barBounds.masterBarBounds,u=c.visualBounds;this._currentBarBounds=c,l&&l.setBounds(u.x,u.y,u.w,u.h),d&&(this.settings.player.enableAnimatedBeatCursor&&d.stopAnimation(),d.setBounds(o.visualBounds.x,u.y,1,u.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let p=!1;if(this._playerState===J.Playing&&!a){if(this.settings.player.enableElementHighlighting)for(let e of r){let i=Es.getGroupId(e);this.uiFacade.highlightElements(i,t.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=c.visualBounds.x+c.visualBounds.w;if(i&&(i.voice.bar.index===t.voice.bar.index&&i.index>t.index||i.voice.bar.index===t.voice.bar.index+1)){let t=n.findBeat(i);t&&t.barBounds.masterBarBounds.staveGroupBounds===c.staveGroupBounds&&(e=t.visualBounds.x)}this.uiFacade.beginInvoke((()=>{d&&d.transitionToX(s/this.playbackSpeed,e)}))}h=!a,p=!0}h&&!this._beatMouseDown&&this.settings.player.scrollMode!==e.ScrollMode.Off&&this.internalScrollToCursor(c),p&&(this.onPlayedBeatChanged(t),this.onActiveBeatsChanged(new Fs(r)))}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 Ls(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 Ls(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.enableUserInteraction){if(this._selectionEnd){let e=this._selectionStart.beat.absolutePlaybackStart;if(this._selectionEnd.beat.absolutePlaybackStart<e){let e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){let e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===J.Paused&&this.cursorUpdateTick(this._selectionStart.beat.absolutePlaybackStart,!1),this.tickPosition=t+this._selectionStart.beat.playbackStart,this._selectionEnd&&this._selectionStart.beat!==this._selectionEnd.beat){let i=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),s=new Ts;s.startTick=t+this._selectionStart.beat.playbackStart,s.endTick=i+this._selectionEnd.beat.playbackStart+this._selectionEnd.beat.playbackDuration-50,this.playbackRange=s}else this._selectionStart=null,this.playbackRange=null,this.cursorSelectRange(this._selectionStart,this._selectionEnd)}}this.beatMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseUp",t,e),this._beatMouseDown=!1}}onNoteMouseUp(e,t){this._isDestroyed||(this.noteMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseUp",t,e),this._noteMouseDown=!1)}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this.tracks,e.startTick),i=this._tickCache.findBeat(this.tracks,e.endTick);if(t&&i){const e=new Ls(t.currentBeat),s=new Ls(i.currentBeat);this.cursorSelectRange(e,s)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{var t,i,s;if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let a=e.getX(this.canvasElement),r=e.getY(this.canvasElement),n=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(a,r))&&void 0!==i?i:null;if(n&&(this.onBeatMouseDown(e,n),this.settings.core.includeNoteBounds)){const t=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(n,a,r);t&&this.onNoteMouseDown(e,t)}})),this.canvasElement.mouseMove.on((e=>{var t,i,s;if(!this._beatMouseDown)return;let a=e.getX(this.canvasElement),r=e.getY(this.canvasElement),n=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(a,r))&&void 0!==i?i:null;if(n&&(this.onBeatMouseMove(e,n),this._noteMouseDown)){const t=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(n,a,r);t&&this.onNoteMouseMove(e,t)}})),this.canvasElement.mouseUp.on((e=>{var t,i,s,a;if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let r=e.getX(this.canvasElement),n=e.getY(this.canvasElement),o=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(r,n))&&void 0!==i?i:null;if(this.onBeatMouseUp(e,o),this._noteMouseDown)if(o){const t=null!==(a=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(o,r,n))&&void 0!==a?a:null;this.onNoteMouseUp(e,t)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){let i=this.renderer.boundsLookup;if(!i)return;let s=this._selectionWrapper;if(!s)return;if(s.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=i.findBeat(e.beat)),t.bounds||(t.bounds=i.findBeat(t.beat));let a=e.beat.absolutePlaybackStart;if(t.beat.absolutePlaybackStart<a){let i=e;e=t,t=i}let r=e.bounds.realBounds.x,n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staveGroupBounds!==t.bounds.barBounds.masterBarBounds.staveGroupBounds){let a=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),s.appendChild(h);let l=e.bounds.barBounds.masterBarBounds.staveGroupBounds.index+1,d=t.bounds.barBounds.masterBarBounds.staveGroupBounds.index;for(let e=l;e<d;e++){let t=i.staveGroups[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),s.appendChild(r)}let c=this.uiFacade.createSelectionElement();c.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),s.appendChild(c)}else{let t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),s.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(ge.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}onPlaybackRangeChanged(e){this._isDestroyed||(this.playbackRangeChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playbackRangeChanged",e))}onSettingsUpdated(){this._isDestroyed||(this.settingsUpdated.trigger(),this.uiFacade.triggerEvent(this.container,"settingsUpdated",null))}}class Ds extends re{constructor(t,i){super(e.AlphaTabErrorType.General,t),this.xhr=i,Object.setPrototypeOf(this,Ds.prototype)}}class Is{static loadScoreAsync(e,t,i,s){let a=new XMLHttpRequest;a.open("GET",e,!0,null,null),a.responseType="arraybuffer",a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){let e=a.response;if(200===a.status||0===a.status&&e)try{let e=a.response,i=new Uint8Array(e),r=Is.loadScoreFromBytes(i,s);t(r)}catch(e){i(e)}else 0===a.status?i(new Ds("You are offline!!\n Please Check Your Network.",a)):404===a.status?i(new Ds("Requested URL not found.",a)):500===a.status?i(new Ds("Internel Server Error.",a)):"parsererror"===a.statusText?i(new Ds("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?i(new Ds("Request Time out.",a)):i(new Ds("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Di);let i=mo.buildImporters();ge.debug("ScoreLoader","Loading score from "+e.length+" bytes using "+i.length+" importers",null);let s=null,a=Ue.fromBuffer(e);for(let e of i){a.reset();try{ge.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),s=e.readScore(),ge.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof ne))throw ge.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;ge.debug("ScoreLoader",e.name+" does not support the file")}}if(s)return s;throw ge.error("ScoreLoader","No compatible importer found for file"),new ne("No compatible importer found for file")}}class Rs{constructor(e){this.mouseEvent=e}get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){let t=e.element,i=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-i}getY(e){let t=e.element,i=t.getBoundingClientRect().top+t.ownerDocument.defaultView.pageYOffset;return this.mouseEvent.pageY-i}preventDefault(){this.mouseEvent.preventDefault()}}class As{constructor(e){this._resizeListeners=0,this.lastBounds=new Qe,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Rs(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Rs(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Rs(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&As.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,As.resizeObserver.value.unobserve(this.element))}}}get width(){return this.element.offsetWidth}set width(e){this.element.style.width=e+"px"}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollTop=e}get scrollTop(){return this.element.scrollLeft}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?e+"px":"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}stopAnimation(){this.element.style.transition="none"}transitionToX(e,t){this.element.style.transition=`transform ${e}ms linear`,this.setBounds(t,NaN,NaN,NaN)}setBounds(e,t,i,s){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(i)&&(i=this.lastBounds.w),isNaN(s)&&(s=this.lastBounds.h),this.element.style.transform=`translate(${e}px, ${t}px) scale(${i}, ${s})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=i,this.lastBounds.h=s}appendChild(e){this.element.appendChild(e.element)}clear(){this.element.innerHTML=""}}As.resizeObserver=new ue((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));var Os,Gs,Hs,Vs,Ws,zs,Us,Xs,Ys,qs=function(e,t,i,s){return new(i||(i=Promise))((function(a,r){function n(e){try{h(s.next(e))}catch(e){r(e)}}function o(e){try{h(s.throw(e))}catch(e){r(e)}}function h(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(n,o)}h((s=s.apply(e,t||[])).next())}))};class Js{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new hi,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(mo.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{ge.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);ge.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let i=e=>{this._families.length>1?(ge.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(ge.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},s=e=>{ge.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=()=>qs(this,void 0,void 0,(function*(){for(const e of this._families)if(yield this.isFontAvailable(e,!1))return void s(e);try{yield document.fonts.load(`1em ${this._families[0]}`)}catch(e){i(e)}return ge.debug("Font",`[${this._families[0]}] Font API signaled loaded`),(yield this.isFontAvailable(this._families[0],!0))?s(this._families[0]):i("Font not available"),!0}));document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((i=>{const s="1em "+e;if(document.fonts.check(s))i(!0);else if(t){ge.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=s,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(s)?i(!0):i(!1)}),200)}else i(!1)}))}}class js{constructor(e){this._writePosition=0,this._readPosition=0,this.count=0,this._buffer=new Float32Array(e)}clear(){this._readPosition=0,this._writePosition=0,this.count=0,this._buffer=new Float32Array(this._buffer.length)}write(e,t,i){let s=0;i>this._buffer.length-this.count&&(i=this._buffer.length-this.count);const a=Math.min(this._buffer.length-this._writePosition,i);return this._buffer.set(e.subarray(t,t+a),this._writePosition),this._writePosition+=a,this._writePosition%=this._buffer.length,s+=a,s<i&&(this._buffer.set(e.subarray(t+s,t+s+i-s),this._writePosition),this._writePosition+=i-s,s=i),this.count+=s,s}read(e,t,i){i>this.count&&(i=this.count);let s=0;const a=Math.min(this._buffer.length-this._readPosition,i);return e.set(this._buffer.subarray(this._readPosition,this._readPosition+a),t),s+=a,this._readPosition+=a,this._readPosition%=this._buffer.length,s<i&&(e.set(this._buffer.subarray(this._readPosition,this._readPosition+i-s),t+s),this._readPosition+=i-s,s=i),this.count-=s,s}}class Qs{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new oi,this.samplesPlayed=new hi,this.sampleRequest=new oi}get sampleRate(){return this._context?this._context.sampleRate:Qs.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(ge.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{var t,i;ge.debug("WebAudio",`Audio Context resume success: state=${null===(t=this._context)||void 0===t?void 0:t.state}, sampleRate:${null===(i=this._context)||void 0===i?void 0:i.sampleRate}`),e&&e()}),(e=>{var t,i;ge.warning("WebAudio",`Audio Context resume failed: state=${null===(t=this._context)||void 0===t?void 0:t.state}, sampleRate:${null===(i=this._context)||void 0===i?void 0:i.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,Qs.PreferredSampleRate),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),i.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in mo.globalThis)return new AudioContext;if("webkitAudioContext"in mo.globalThis)return new webkitAudioContext;throw new re(e.AlphaTabErrorType.General,"AudioContext not found")}open(e){this.patchIosSampleRate(),this._context=this.createAudioContext(),"suspended"===this._context.state&&this.registerResumeHandler()}registerResumeHandler(){this._resumeHandler=(()=>{this.activate((()=>{this.unregisterResumeHandler()}))}).bind(this),document.body.addEventListener("touchend",this._resumeHandler,!1),document.body.addEventListener("click",this._resumeHandler,!1)}unregisterResumeHandler(){const e=this._resumeHandler;e&&(document.body.removeEventListener("touchend",e,!1),document.body.removeEventListener("click",e,!1))}play(){let e=this._context;this.activate(),this._buffer=e.createBuffer(2,Qs.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){var e;this.pause(),null===(e=this._context)||void 0===e||e.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}}Qs.BufferSize=4096,Qs.PreferredSampleRate=44100;class $s extends Qs{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/Qs.BufferSize),this._circularBuffer=new js(Qs.BufferSize*this._bufferCount),this.onReady()}play(){super.play();let e=this._context;this._audioNode=e.createScriptProcessor(4096,0,2),this._audioNode.onaudioprocess=this.generateSound.bind(this),this._circularBuffer.clear(),this.requestBuffers(),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0,this._source.connect(this._audioNode,0,0),this._source.start(0),this._audioNode.connect(e.destination,0,0)}pause(){super.pause(),this._audioNode&&this._audioNode.disconnect(0),this._audioNode=null}addSamples(e){this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--}resetSamples(){this._circularBuffer.clear()}requestBuffers(){const e=this._bufferCount/2|0;let t=e*Qs.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Qs.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){let t=e.outputBuffer.getChannelData(0),i=e.outputBuffer.getChannelData(1),s=t.length+i.length,a=this._outputBuffer;a.length!==s&&(a=new Float32Array(s),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;for(let e=0;e<t.length;e++)t[e]=a[n++],i[e]=a[n++];this.onSamplesPlayed(r/Ft.AudioChannels),this.requestBuffers()}}class Ks{constructor(e,t){this.loaded=e,this.total=t}}class Zs{constructor(e,t,i,s){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=J.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 oi,this.readyForPlayback=new oi,this.finished=new oi,this.soundFontLoaded=new oi,this.soundFontLoadFailed=new hi,this.midiLoaded=new hi,this.midiLoadFailed=new hi,this.stateChanged=new hi,this.positionChanged=new hi,this.midiEventsPlayed=new hi,this.playbackRangeChanged=new hi,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=J.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(s);try{this._synth=mo.createAlphaTabWorker(t)}catch(e){ge.error("AlphaSynth","Failed to create WebWorker: "+e)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:i,bufferTimeInMilliseconds:s}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return ge.logLevel}set logLevel(e){ge.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Ft.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ft.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ft.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=Kt.clamp(e,Ft.MinPlaybackSpeed,Ft.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:Zi.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,i){ge.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);let s=new XMLHttpRequest;s.open("GET",e,!0,null,null),s.responseType="arraybuffer",s.onload=e=>{let i=new Uint8Array(s.response);this.loadSoundFont(i,t)},s.onerror=e=>{ge.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Ds(e.message,s))},s.onprogress=e=>{ge.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),i(new Ks(e.loaded,e.total))},s.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:Zi.midiFileToJsObject(e)})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Ft.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.ready":this._workerIsReady=!0,this.checkReady();break;case"alphaSynth.destroyed":this._synth.terminate();break;case"alphaSynth.readyForPlayback":this._workerIsReadyForPlayback=!0,this.checkReadyForPlayback();break;case"alphaSynth.positionChanged":this._timePosition=t.currentTime,this._tickPosition=t.currentTick,this.positionChanged.trigger(new Rt(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new li(t.events.map(Zi.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new It(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new di(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 Rt(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 ea{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new hi,this.partialRenderFinished=new hi,this.partialLayoutFinished=new hi,this.renderFinished=new hi,this.postRenderFinished=new oi,this.error=new hi,this._api=e;try{this._worker=mo.createAlphaTabWorker(t.core.scriptFile)}catch(e){return void ge.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=Zi.settingsToJsObject(e);return t.delete("player"),t}render(){this._worker.postMessage({cmd:"alphaTab.render"})}resizeRender(){this._worker.postMessage({cmd:"alphaTab.resizeRender"})}renderResult(e){this._worker.postMessage({cmd:"alphaTab.renderResult",resultId:e})}get width(){return this._width}set width(e){this._width=e,this._worker.postMessage({cmd:"alphaTab.setWidth",width:e})}handleWorkerMessage(e){let t=e.data;switch(t.cmd){case"alphaTab.preRender":this.preRender.trigger(t.resize);break;case"alphaTab.partialRenderFinished":this.partialRenderFinished.trigger(t.result);break;case"alphaTab.partialLayoutFinished":this.partialLayoutFinished.trigger(t.result);break;case"alphaTab.renderFinished":this.renderFinished.trigger(t.result);break;case"alphaTab.postRenderFinished":this.boundsLookup=ls.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){let i=null==e?null:Zi.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:i,trackIndexes:t,fontSizes:is.FontSizeLookupTables})}}class ta{constructor(e,t,i,s){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=i,this.selectionWrapper=s}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(Os||(Os={}));class ia{static init(){var e;ia._isRegistered||(ia._isRegistered=!0,registerProcessor("alphatab",((e=class e extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,ge.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new js(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case es.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case es.CmdOutputResetSamples:this._circularBuffer.clear()}}process(e,t,i){if(1!==t.length&&2!==t[0].length)return!1;let s=t[0][0],a=t[0][1];if(!s||!a)return!0;let r=s.length+a.length,n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;for(let e=0;e<s.length;e++)s[e]=n[h++],a[e]=n[h++];return this.port.postMessage({cmd:es.CmdOutputSamplesPlayed,samples:o/Ft.AudioChannels}),this.requestBuffers(),!0}requestBuffers(){const t=this._bufferCount/2|0;let i=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<i){for(let e=0;e<t;e++)this.port.postMessage({cmd:es.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}ia._isRegistered=!1;class sa extends Qs{constructor(){super(...arguments),this._worklet=null,this._bufferTimeInMilliseconds=0}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();let e=this._context;e.audioWorklet.addModule(mo.scriptFile).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{ge.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case es.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case es.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){var t;null===(t=this._worklet)||void 0===t||t.port.postMessage({cmd:es.CmdOutputAddSamples,samples:e})}resetSamples(){var e;null===(e=this._worklet)||void 0===e||e.port.postMessage({cmd:es.CmdOutputResetSamples})}}class aa extends As{constructor(e,t,i){super(e),this._xscale=t,this._yscale=i}get width(){return this.element.offsetWidth/this._xscale}set width(e){this.element.style.width=e*this._xscale+"px"}get height(){return this.element.offsetHeight/this._yscale}set height(e){this.element.style.height=e>=0?e*this._yscale+"px":"100%"}setBounds(e,t,i,s){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(i)?i=this.lastBounds.w:i/=this._xscale,isNaN(s)?s=this.lastBounds.h:s/=this._yscale,this.element.style.transform=`translate(${e}px, ${t}px) scale(${i}, ${s})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=i,this.lastBounds.h=s}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}(Gs||(Gs={}));class ra{constructor(t){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new oi,this.canRenderChanged=new oi,this._highlightedElements=[],this._scrollContainer=null,mo.webPlatform!==Os.Browser&&mo.webPlatform!==Os.BrowserModule)throw new re(e.AlphaTabErrorType.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");t.classList.add("alphaTab"),this.rootContainer=new As(t),this.areWorkersSupported="Worker"in window,mo.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(t)}get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(mo.bravuraFontChecker.checkForFontAvailability(),!mo.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(ge.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){is.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const i=e;t.isIntersecting?i.renderedResultId!==i.layoutResultId?this._resultIdToElementLookup.has(i.layoutResultId)?this._api.renderer.renderResult(i.layoutResultId):e.replaceChildren():i.resultState===Gs.Detached&&(e.replaceChildren(...i.renderedResult),i.resultState=Gs.RenderDone):i.resultState===Gs.RenderDone&&(i.resultState=Gs.Detached,i.replaceChildren())}}}createWorkerRenderer(){return new ea(this._api,this._api.settings)}initialize(t,i){let s;this._api=t,s=i instanceof Di?i:Zi.jsObjectToSettings(i);let a=this.getDataAttributes();Mi.fromJson(s,a),s.notation.notationMode===e.NotationMode.SongBook&&s.setSongBookModeSettings(),t.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";let r=t.container;s.core.tex&&(this._contents=r.element.innerHTML,r.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){let t=new Js(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){let e=document.createElement("div");return e.className="at-surface",e.style.fontSize="0",e.style.overflow="hidden",e.style.lineHeight="0",e.style.position="relative",new As(e)}triggerEvent(e,t,i=null,s){let a=e.element;t="alphaTab."+t;let r=document.createEvent("CustomEvent"),n=s?s.mouseEvent:null;if(r.initCustomEvent(t,!1,!1,i),n&&(r.originalEvent=n),a.dispatchEvent(r),window&&"jQuery"in window){let e=window.jQuery,s=[];s.push(i),n&&s.push(n),e(a).trigger(t,s)}}load(e,t,i){if(e instanceof Me)return t(e),!0;if(e instanceof ArrayBuffer){let i=new Uint8Array(e);return t(Is.loadScoreFromBytes(i,this._api.settings)),!0}return e instanceof Uint8Array?(t(Is.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Is.loadScoreAsync(e,t,i,this._api.settings),!0)}loadSoundFont(e,t){return!!this._api.player&&(e instanceof ArrayBuffer?(this._api.player.loadSoundFont(new Uint8Array(e),t),!0):e instanceof Uint8Array?(this._api.player.loadSoundFont(e,t),!0):"string"==typeof e&&(this._api.loadSoundFontFromUrl(e,t),!0))}initialRender(){this._api.renderer.preRender.on((e=>{this._totalResultCount=0,this._resultIdToElementLookup.clear(),this._barToElementLookup.clear()}));const e=()=>{var e;this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,null!==(e=this._initialTrackIndexes)&&void 0!==e?e:void 0),this._initialTrackIndexes=null):this._file&&Is.loadScoreAsync(this._file,(e=>{var t;this._api.renderScore(e,null!==(t=this._initialTrackIndexes)&&void 0!==t?t:void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){let t=this._api.container.element.ownerDocument;mo.createStyleElement(t,e.core.fontDirectory)}parseTracks(e){if(!e)return[];let t=[];if("string"==typeof e)try{if("all"===e)return[-1];e=JSON.parse(e)}catch(t){e=[0]}if("number"==typeof e)t.push(e);else if("length"in e){let i=e.length,s=e;for(let e=0;e<i;e++){let i=s[e],a=0;a="number"==typeof i?i:"index"in i?i.index:parseInt(i.toString()),(a>=0||-1===a)&&t.push(a)}}else"index"in e&&t.push(e.index);return t}getDataAttributes(){let e=new Map,t=this._api.container.element;if(t.dataset)for(let i of Object.keys(t.dataset)){let s=t.dataset[i];try{let e=s;s=JSON.parse(e)}catch(e){""===s&&(s=null)}e.set(i,s)}else for(let i=0;i<t.attributes.length;i++){let s=t.attributes.item(i),a=s.nodeName;if(a.startsWith("data-")){let t=a.substr(5).split("-"),i=t[0];for(let e=1;e<t.length;e++)i+=t[e].substr(0,1).toUpperCase()+t[e].substr(1);let r=s.nodeValue;try{r=JSON.parse(r)}catch(e){""===r&&(r=null)}e.set(i,r)}}return e}beginUpdateRenderResults(e){if(!this._resultIdToElementLookup.has(e.id))return;const t=this._resultIdToElementLookup.get(e.id),i=e.renderResult;"string"==typeof i?t.innerHTML=i:"nodeType"in i&&t.replaceChildren(i),t.resultState=Gs.RenderDone,t.renderedResultId=e.id,t.renderedResult=Array.from(t.children)}beginAppendRenderResults(e){const t=this._api.canvasElement.element;if(e){let i;this._totalResultCount<t.childElementCount?i=t.childNodes.item(this._totalResultCount):(i=document.createElement("div"),t.appendChild(i)),i.style.zIndex="1",i.style.position="absolute",i.style.left=e.x+"px",i.style.top=e.y+"px",i.style.width=e.width+"px",i.style.height=e.height+"px",i.style.display="inline-block",i.layoutResultId=e.id,i.resultState=Gs.LayoutDone,delete i.renderedResultId,delete i.renderedResult,this._resultIdToElementLookup.set(e.id,i);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)t>=0&&this._barToElementLookup.set(t,i);this._api.settings.core.enableLazyLoading&&(this._intersectionObserver.unobserve(i),this._intersectionObserver.observe(i)),this._totalResultCount++}else for(;t.childElementCount>this._totalResultCount;)this._api.settings.core.enableLazyLoading&&this._intersectionObserver.unobserve(t.lastChild),t.removeChild(t.lastElementChild)}createWorkerPlayer(){let e=mo.scriptFile;if(!e)return ge.error("Player","alphaTab script file could not be detected, player cannot initialize"),null;let t=null,i="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&!mo.isWebPackBundled?(ge.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new Zs(new sa,e,this._api.settings.core.logLevel,this._api.settings.player.bufferTimeInMilliseconds)):i&&(ge.debug("Player","Will use webworkers for synthesizing and web audio api for playback"),t=new Zs(new $s,e,this._api.settings.core.logLevel,this._api.settings.player.bufferTimeInMilliseconds)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):ge.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const i=this._barToElementLookup.get(t);if(i){let t=i.getElementsByClassName(e);for(let e=0;e<t.length;e++)t.item(e).classList.add("at-highlight"),this._highlightedElements.push(t.item(e))}}removeHighlights(){const e=this._highlightedElements;if(e){for(const t of e)t.classList.remove("at-highlight");this._highlightedElements=[]}}destroyCursors(){let e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){let e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");let i=document.createElement("div");i.classList.add("at-selection");const s=this.createScalingElement(),a=this.createScalingElement();let r=s.element;r.classList.add("at-cursor-bar");let n=a.element;return n.classList.add("at-cursor-beat"),e.style.position="relative",e.style.textAlign="left",t.style.position="absolute",t.style.zIndex="1000",t.style.display="inline",t.style.pointerEvents="none",i.style.position="absolute",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.willChange="transform",s.width=1,s.height=1,s.setBounds(0,0,1,1),n.style.position="absolute",n.style.transition="all 0s linear",n.style.left="0",n.style.top="0",n.style.willChange="transform",a.width=3,a.height=1,a.setBounds(0,0,1,1),e.insertBefore(t,e.firstChild),t.appendChild(i),t.appendChild(r),t.appendChild(n),new ta(new As(t),s,a,new As(i))}getOffset(e,t){let i=t.element,s=i.getBoundingClientRect(),a=s.top+i.ownerDocument.defaultView.pageYOffset,r=s.left+i.ownerDocument.defaultView.pageXOffset;if(e){let t=e.element,i=t.nodeName.toLowerCase();if("html"!==i&&"body"!==i){let i=this.getOffset(null,e);a=a+t.scrollTop-i.y,r=r+t.scrollLeft-i.x}}let n=new Qe;return n.x=r,n.y=a,n.w=s.width,n.h=s.height,n}getScrollContainer(){if(this._scrollContainer)return this._scrollContainer;let e="string"==typeof this._api.settings.player.scrollElement?document.querySelector(this._api.settings.player.scrollElement):this._api.settings.player.scrollElement,t=e.nodeName.toLowerCase();if("html"===t||"body"===t)if("scrollingElement"in document)e=document.scrollingElement;else{e=-1!==navigator.userAgent.indexOf("WebKit")?document.body:document.documentElement}return this._scrollContainer=new As(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new aa(e,100,100);return t.width=1,t.height=1,t.setBounds(0,0,1,1),t}scrollToY(e,t,i){this.internalScrollToY(e.element,t,i)}scrollToX(e,t,i){this.internalScrollToX(e.element,t,i)}internalScrollToY(e,t,i){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({top:t,behavior:"smooth"});else{let s=e.scrollTop,a=t-s,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/i,1);e.scrollTop=s+a*h|0,o<i&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}internalScrollToX(e,t,i){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({left:t,behavior:"smooth"});else{let s=e.scrollLeft,a=t-s,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/i,1);e.scrollLeft=s+a*h|0,o<i&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class na extends Ms{constructor(e,t){super(new ra(e),t),this.soundFontLoad=new hi}tex(e,t){let i=this.uiFacade;super.tex(e,i.parseTracks(t))}print(t,i=null){let s=window.open("","","width=0,height=0"),a=s.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.LayoutMode.Horizontal?a.style.width="297mm":a.style.width="210mm",s.document.write("\n <!DOCTYPE html>\n <html>\n <head>\n <style>\n .at-surface {\n width: auto !important;\n height: auto !important;\n }\n .at-surface > div {\n position: relative!important;\n left: auto !important;\n top: auto !important;\n break-inside: avoid;\n }\n </style>\n </head>\n <body></body>\n </html>\n ");const r=this.score;r&&(r.artist&&r.title?s.document.title=`${r.title} - ${r.artist}`:r.title&&(s.document.title=`${r.title}`)),s.document.body.appendChild(a);let n=void 0!==window.screenLeft?window.screenLeft:window.left,o=void 0!==window.screenTop?window.screenTop:window.top,h="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,l="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,d=a.offsetWidth+50,c=window.innerHeight,u=(h/2|0)-(d/2|0)+n,p=(l/2|0)-(c/2|0)+o;s.resizeTo(d,c),s.moveTo(u,p),s.focus();let g=Zi.jsObjectToSettings(Zi.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,Mi.fromJson(g,i);let f=new na(a,g);s.onunload=()=>{f.destroy()},f.renderer.postRenderFinished.on((()=>{s.print()})),f.renderTracks(this.tracks)}downloadMidi(){if(!this.score)return;let e=new ui,t=new ps(e);new Bs(this.score,this.settings,t).generate();let i=e.toBinary(),s=this.score.title?`${this.score.title}.mid`:"File.mid",a=document.createElement("a");a.download=s;let r=new Blob([i],{type:"audio/midi"}),n=URL.createObjectURL(r);a.href=n,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a)}changeTrackMute(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(i,t)}changeTrackSolo(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(i,t)}changeTrackVolume(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(i,t)}trackIndexesToTracks(e){if(!this.score)return[];let t=[];if(1===e.length&&-1===e[0])for(let e of this.score.tracks)t.push(e);else for(let i of e)i>=0&&i<this.score.tracks.length&&t.push(this.score.tracks[i]);return t}loadSoundFontFromUrl(e,t){this.player&&this.player.loadSoundFontFromUrl(e,t,(e=>{this.soundFontLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"soundFontLoad",e)}))}}class oa{constructor(){this._initListeners=[]}exec(e,t,i){if("string"!=typeof t&&(i=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;let s=new jQuery(e),a=s.data("alphaTab");if("destroy"===t&&!a)return null;if("init"!==t&&!a)throw new Error("alphaTab not initialized");let r=this[t];if(r){let e=[s,a].concat(i);return r.apply(this,e)}return ge.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,i){if(!t){t=new na(e[0],i),e.data("alphaTab",t);for(let s of this._initListeners)s(e,t,i)}}destroy(e,t){e.removeData("alphaTab"),t.destroy()}print(e,t,i,s){t.print(i,s)}load(e,t,i,s){return t.load(i,s)}render(e,t){t.render()}renderScore(e,t,i,s){t.renderScore(i,s)}renderTracks(e,t,i){t.renderTracks(i)}invalidate(e,t){t.render()}tex(e,t,i,s){t.tex(i,s)}muteTrack(e,t,i,s){t.changeTrackMute(i,s)}soloTrack(e,t,i,s){t.changeTrackSolo(i,s)}trackVolume(e,t,i,s){t.changeTrackVolume(i,s)}loadSoundFont(e,t,i,s){t.loadSoundFont(i,s)}resetSoundFonts(e,t){t.resetSoundFonts()}pause(e,t){t.pause()}play(e,t){return t.play()}playPause(e,t){t.playPause()}stop(e,t){t.stop()}api(e,t){return t}player(e,t){return t.player}isReadyForPlayback(e,t){return t.isReadyForPlayback}playerState(e,t){return t.playerState}masterVolume(e,t,i){return"number"==typeof i&&(t.masterVolume=i),t.masterVolume}metronomeVolume(e,t,i){return"number"==typeof i&&(t.metronomeVolume=i),t.metronomeVolume}countInVolume(e,t,i){return"number"==typeof i&&(t.countInVolume=i),t.countInVolume}midiEventsPlayedFilter(e,t,i){return Array.isArray(i)&&(t.midiEventsPlayedFilter=i),t.midiEventsPlayedFilter}playbackSpeed(e,t,i){return"number"==typeof i&&(t.playbackSpeed=i),t.playbackSpeed}tickPosition(e,t,i){return"number"==typeof i&&(t.tickPosition=i),t.tickPosition}timePosition(e,t,i){return"number"==typeof i&&(t.timePosition=i),t.timePosition}loop(e,t,i){return"boolean"==typeof i&&(t.isLooping=i),t.isLooping}renderer(e,t){return t.renderer}score(e,t){return t.score}settings(e,t){return t.settings}tracks(e,t){return t.tracks}_oninit(e){this._initListeners.push(e)}static restore(e){new jQuery(e).empty().removeData("alphaTab")}}class ha{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new Re(255,255,255,255),this.lineWidth=1,this.font=new bi("Arial",10,Z.Plain),this.textAlign=E.Left,this.textBaseline=C.Top}beginRender(e,t){this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=C.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,i,s){i>0&&(this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${i}" height="${s}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,i,s){this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${i}" height="${s}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e},${t}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e},${t}`}quadraticCurveTo(e,t,i,s){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e},${t},${i},${s}`}bezierCurveTo(e,t,i,s,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e},${t},${i},${s},${a},${r}`}fillCircle(e,t,i){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-i},${t} A1,1 0 0,0 ${e+i},${t} A1,1 0 0,0 ${e-i},${t} z`,this.fill()}strokeCircle(e,t,i){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-i},${t} A1,1 0 0,0 ${e+i},${t} A1,1 0 0,0 ${e-i},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1!==this.lineWidth&&(e+=` stroke-width="${this.lineWidth}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,i){if(""===e)return;let s=`<text x="${0|t}" y="${0|i}" style="stroke: none; font:${this.font.toCssString(this.settings.display.scale)}" ${this.getSvgBaseLine()}`;"#000000"!==this.color.rgba&&(s+=` fill="${this.color.rgba}"`),this.textAlign!==E.Left&&(s+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),s+=`>${ha.escapeText(e)}</text>`,this.buffer+=s}static escapeText(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}getSvgTextAlignment(e){switch(e){case E.Left:return"start";case E.Center:return"middle";case E.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case C.Top:return'dominant-baseline="hanging"';case C.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?is.measureString(e,this.font.families,this.font.size,this.font.style,this.font.weight):0}onRenderFinished(){return null}beginRotate(e,t,i){this.buffer+='<g transform="translate('+e+" ,"+t+") rotate( "+i+')">'}endRotate(){this.buffer+="</g>"}}class la extends ha{constructor(){super()}fillMusicFontSymbol(e,t,i,s,a){s!==P.None&&this.fillMusicFontSymbolText(e,t,i,`&#${s};`,a)}fillMusicFontSymbols(e,t,i,s,a){let r="";for(let e of s)e!==P.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a){this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`,this.buffer+=1!==i?` style="font-size: ${100*i}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(E.Center)+'"'),this.buffer+=`>${s}</text></g>`}}class da{constructor(){this.isInAccolade=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(Hs||(Hs={}));class ca extends ks{constructor(e,t){super(e,t),this.glyphs=null}get isEmpty(){return!this.glyphs||0===this.glyphs.length}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.renderer=this.renderer,i.doLayout(),e=Math.max(e,i.width)}this.width=e}addGlyph(e){this.glyphs||(this.glyphs=[]),this.renderer&&(e.renderer=this.renderer),this.glyphs.push(e)}paint(e,t,i){let s=this.glyphs;if(s&&0!==s.length)for(let a of s)a.paint(e+this.x,t+this.y,i)}}class ua extends ca{constructor(){super(0,0),this.glyphs=[]}addGlyph(e){e.x=0===this.glyphs.length?0:this.glyphs[this.glyphs.length-1].x+this.glyphs[this.glyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class pa extends ca{constructor(e,t,i){super(e,t),this.voice=i,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.scale;let i=this.renderer.layoutingInfo.spaceToForce(e/t);this.scaleToForce(i)}scaleToForce(e){const t=this.renderer.scale;this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e)*t;let i=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,a=s.length;e<a;e++){let r=s[e];if(r.beat.graceType===f.None)r.x=i.get(r.beat.absoluteDisplayStart)*t-r.onTimeX;else{const a=r.beat.graceGroup.beats[0].absoluteDisplayStart,n=r.beat.graceGroup.id;if(r.beat.graceGroup.isComplete&&i.has(a)){r.x=i.get(a)*t-r.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(n),s=this.renderer.layoutingInfo.springs.get(a).preBeatWidth;r.x-=s,r.x-=e[r.beat.graceIndex].postSpringWidth,r.x+=e[r.beat.graceIndex].graceBeatWidth;const o=e[r.beat.graceGroup.beats.length-1];r.x-=o.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(n);const i=t[r.beat.graceIndex].postSpringWidth-t[r.beat.graceIndex].preSpringWidth;e>0?0===r.beat.graceIndex?r.x=s[e-1].x+s[e-1].width:r.x=s[e-1].x+t[r.beat.graceIndex-1].postSpringWidth-t[r.beat.graceIndex-1].preSpringWidth-i:r.x=-i}}if(e>0){let t=r.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===a-1){let e=this.width-s[s.length-1].x;r.scaleToWidth(e)}}}registerLayoutingInfo(e){e.updateVoiceSize(this.width);let t=this.beatGlyphs;for(let i of t)i.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let i of t)i.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){let t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,i){i.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let s=0,a=this.beatGlyphs.length;s<a;s++)this.beatGlyphs[s].paint(e+this.x,t+this.y,i)}}pa.KeySizeBeat="Beat",function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(Vs||(Vs={}));class ga{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class fa{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){var i,s;return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:null!==(s=null===(i=be.getArticulationByValue(t))||void 0===i?void 0:i.staffLine)&&void 0!==s?s:0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case 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=fa.getNoteValue(e);let i=e.hasQuarterToneOffset;return this.getAccidental(t,i,e.beat,!1,e)}applyAccidentalForValue(e,t,i,s){return this.getAccidental(t,i,e,s,null)}static computeLineWithoutAccidentals(e,t){let i=0;const s=fa.getNoteValue(t);if(e.staff.isPercussion)i=fa.getPercussionLine(e,s);else{const a=t?t.accidentalMode:b.Default;i=fa.calculateNoteLine(e,s,a)}return i}getAccidental(e,t,i,s,a=null){let r=Vs.None,n=0;if(this._bar.staff.isPercussion)n=fa.getPercussionLine(this._bar,e);else{const i=a?a.accidentalMode:b.Default;n=fa.calculateNoteLine(this._bar,e,i);let s=this._bar.masterBar.keySignature+7,o=e%12,h=s<7?Vs.Flat:Vs.Sharp,l=fa.KeySignatureLookup[s][o],d=fa.AccidentalNotes[o];if(t)switch(r=d?h:Vs.Natural,r){case Vs.Natural:r=Vs.NaturalQuarterNoteUp;break;case Vs.Sharp:r=Vs.SharpQuarterNoteUp;break;case Vs.Flat:r=Vs.FlatQuarterNoteUp}else{switch(i){case b.ForceSharp:r=Vs.Sharp;break;case b.ForceDoubleSharp:r=Vs.DoubleSharp;break;case b.ForceFlat:r=Vs.Flat;break;case b.ForceDoubleFlat:r=Vs.DoubleFlat;break;default:d?r=h:l&&(r=Vs.Natural)}let e=!1;if(a&&a.isTieDestination&&0===a.beat.index){const t=this._barRenderer.previousRenderer;if(t){t.accidentalHelper.getNoteLine(a.tieOrigin)===n&&(e=!0)}}e?r=Vs.None:r!==Vs.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=Vs.None):l&&r===h&&(r=Vs.None),r!==Vs.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===Vs.Natural?r=Vs.None:(r=Vs.Natural,this._registeredAccidentals.set(n,r)):this._registeredAccidentals.delete(n)}}return a?(this._appliedScoreLines.set(a.id,n),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,n),(-1e3===this.minLine||this.minLine<n)&&(this.minLine=n,this.minLineBeat=i),(-1e3===this.maxLine||this.maxLine>n)&&(this.maxLine=n,this.maxLineBeat=i),s||this.registerLine(i,n),r}registerLine(e,t){let i;this._beatLines.has(e.id)?i=this._beatLines.get(e.id):(i=new ga,this._beatLines.set(e.id,i)),(-1e3===i.minLine||t<i.minLine)&&(i.minLine=t),(-1e3===i.minLine||t>i.maxLine)&&(i.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteLine(e,t,i){let s=t,a=e.masterBar.keySignature,r=e.clef,n=s%12,o=(s/12|0)-1,h=fa.OctaveSteps[r];return h-=o*fa.StepsPerOctave,h-=(me.keySignatureIsSharp(a)||me.keySignatureIsNatural(a)?fa.SharpNoteSteps:fa.FlatNoteSteps)[n],h}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}fa.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]],fa.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],fa.StepsPerOctave=7,fa.OctaveSteps=[38,32,30,26,38],fa.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],fa.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class ma{constructor(){this.staffId="",this.up=0,this.down=0}}class ya{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 ba{constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=p.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=W.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>p.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>p.Quarter||this.beats[0].graceType!==f.None)}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===W.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,i,s){let a=this.getOrCreateBeatPositions(t);a.staffId=e,a.up=i,a.down=s;for(const e of this.drawingInfos.values())e.startBeat==t?e.startX=this.getBeatLineX(t):e.endBeat==t&&(e.endX=this.getBeatLineX(t))}getOrCreateBeatPositions(e){return this._beatLineXPositions.has(e.index)||this._beatLineXPositions.set(e.index,new ma),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(W.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==f.None)&&(e=this.invert(W.Up)):e=W.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,Ws.Center),i=this._renderer.getNoteY(this.lowestNoteInHelper,Ws.Center);if(null===e){const s=(t+i)/2;e=this.invert(this._renderer.middleYPosition<s?W.Up:W.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(W.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:return[2,2];case p.Whole:return[0,1];case p.Half:return[1,0];case p.Quarter:return[3,3];case p.Eighth:return[2,2];case p.Sixteenth:return[2,4];case p.ThirtySecond:return[4,4];case p.SixtyFourth:return[4,6];case p.OneHundredTwentyEighth:return[6,6];case p.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let i=t,s=t;const a=ba.computeLineHeightsForRest(e.duration);i-=a[0],s+=a[1];const r=this.minRestLine,n=this.maxRestLine;(null===r||r>i)&&(this.minRestLine=i,this.beatOfMinRestLine=e),(null===n||n<s)&&(this.maxRestLine=s,this.beatOfMaxRestLine=e)}invert(e){return this.invertBeamDirection?e===W.Down?W.Up:W.Down:e}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case L.Auto:t=ba.canJoin(this.beats[this.beats.length-1],e);break;case L.ForceSplitToNext:t=!1;break;case L.ForceMergeWithNext:t=!0}if(t){if(null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.isRest)0===this.beats.length&&this.beats.push(e);else{this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),e.graceType!==f.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let i=0;i<e.notes.length;i++){let s=e.notes[i];s.leftHandFinger===m.Unknown&&s.rightHandFinger===m.Unknown||t++}t>this.fingeringCount&&(this.fingeringCount=t),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e}e.hasTuplet&&(this.hasTuplet=!0)}return t}checkNote(e){if(!e)return;let t,i;this.voice&&e.isPercussion?(t=-fa.getPercussionLine(this.voice.bar,fa.getNoteValue(e)),i=t):(t=fa.getNoteValue(e),i=t,e.harmonicType!==y.None&&e.harmonicType!==y.Natural&&(i=e.realValue-this._staff.displayTranspositionPitch)),1===this.beats.length&&this.beats[0]===e.beat&&((-1===this._firstBeatLowestNoteCompareValue||t<this._firstBeatLowestNoteCompareValue)&&(this._firstBeatLowestNoteCompareValue=t),(-1===this._firstBeatHighestNoteCompareValue||i>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=i)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||i>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=i),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||i>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=i)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===f.BendGrace||t.graceType===f.BendGrace)return!1;if(e.graceType!==f.None&&t.graceType!==f.None)return!0;let i=e.voice.bar;if(i!==t.voice.bar)return!1;let s=e.playbackStart,a=t.playbackStart;if(!ba.canJoinDuration(e.duration)||!ba.canJoinDuration(t.duration))return s===a;if(e.tupletGroup!==t.tupletGroup)return!1;if(e.hasTuplet&&t.hasTuplet&&e.tupletGroup===t.tupletGroup&&e.tupletGroup.isFull)return!0;let r=le.QuarterTime;if(8===i.masterBar.timeSignatureDenominator)i.masterBar.timeSignatureNumerator%3==0&&(r+=le.QuarterTime/2|0);return(0|(r+s)/r)===(0|(r+a)/r)}static canJoinDuration(e){switch(e){case p.Whole:case p.Half:case p.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,i){return me.getIndex(e.duration)-2-i>0&&me.getIndex(t.duration)-2-i>0}get beatOfLowestNote(){return this.lowestNoteInHelper.beat}get beatOfHighestNote(){return this.highestNoteInHelper.beat}isPositionFrom(e,t){return!this._beatLineXPositions.has(t.index)||(this._beatLineXPositions.get(t.index).staffId===e||!this._beatLineXPositions.get(t.index).staffId)}}class Sa{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class _a{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Sa(e,t)),-1e3===this.topY)this.topY=e,this.bottomY=t;else{const i=Math.min(e,t),s=Math.max(e,t);i<this.topY&&(this.topY=i),s>this.bottomY&&(this.bottomY=s)}}}class wa{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const i of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=i.topY,t=i.bottomY):(e>i.topY&&(e=i.topY),t<i.bottomY&&(t=i.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,i){t!=i&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new _a(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,i),e.isRest&&this.registerRest(e))}registerRest(e){this.restDurationsByDisplayTime.has(e.displayStart)||this.restDurationsByDisplayTime.set(e.displayStart,new Map),this.restDurationsByDisplayTime.get(e.displayStart).has(e.playbackDuration)||this.restDurationsByDisplayTime.get(e.displayStart).set(e.playbackDuration,e.id)}applyRestCollisionOffset(e,t,i){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const s=ba.computeLineHeightsForRest(e.duration).map((e=>e*i));let a=t-s[0],r=t+s[1],n=a;const o=this.reservedLayoutAreasByDisplayTime.get(e.playbackStart);let h=!1;for(const e of o.slots)if(a>=e.topY&&a<=e.bottomY||r>=e.topY&&r<=e.bottomY){h=!0;break}if(h){n=1==e.voice.index?o.topY-s[1]-s[0]:o.bottomY;let t=n+s[0]+s[1];const r=2*i;let h=Math.ceil(Math.abs(n-a)/r);return o.addSlot(n,t),n<a?h*-r:h*r}}return 0}}class Ba{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this._renderer=e,this.collisionHelper=new wa}initialize(){var e=this._renderer,t=this._renderer.bar;let i=null,s=null;for(let a=0,r=t.voices.length;a<r;a++){let r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){let n,o=r.beats[a];o.graceType!==f.None?n=s:(n=i,s=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new ba(t.staff,e),n.checkBeat(o),o.graceType!==f.None?s=n:i=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}i&&i.finish(),s&&s.finish(),i=null,s=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}!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"}(Ws||(Ws={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(zs||(zs={}));class Ta{constructor(e,t){this._preBeatGlyphs=new ua,this._voiceContainers=new Map,this._postBeatGlyphs=new ua,this._ties=[],this.x=0,this.y=0,this.width=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this._wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new Ba(this))}get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.previousBar):null}registerTies(e){this._ties.push(...e)}get middleYPosition(){return 0}registerOverflowTop(e){return e>this.topOverflow&&(this.topOverflow=e,!0)}registerOverflowBottom(e){return e>this.bottomOverflow&&(this.bottomOverflow=e,!0)}scaleToWidth(e){let t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get scale(){return this.settings.display.scale}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){let e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e);let i=this._postBeatGlyphs.width;e.postBeatSize<i&&(e.postBeatSize=i)}applyLayoutingInfo(){if(this._appliedLayoutingInfo>=this.layoutingInfo.version)return!1;this._appliedLayoutingInfo=this.layoutingInfo.version,this._preBeatGlyphs.width=this.layoutingInfo.preBeatSize;let e=this._preBeatGlyphs.x+this._preBeatGlyphs.width;for(const t of this._voiceContainers.values()){t.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width,t.applyLayoutingInfo(this.layoutingInfo);let i=t.x+t.width;e<i&&(e=i)}return this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),!0}finalizeRenderer(){this.isFinalized=!0;let e=!1;const t=this.y-this.staff.topSpacing,i=this.y+this.height+this.staff.bottomSpacing;for(const s of this._ties)if(s.doLayout(),s.height>0){const a=s.y+s.height-i;a>0&&this.registerOverflowBottom(a)&&(e=!0);const r=s.y-t;r<0&&this.registerOverflowTop(-1*r)&&(e=!0)}return e}doLayout(){if(this.bar){this.helpers.initialize(),this._ties=[],this._preBeatGlyphs=new ua,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new ua,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];if(this.hasVoiceContainer(t)){let i=new pa(0,0,t);i.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,i)}}this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.createBeatGlyphs(),this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish()}}hasVoiceContainer(e){return!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,i=t;for(const s of e.values()){s.x=t,s.doLayout();let e=s.x+s.width;i<e&&(i=e)}this._postBeatGlyphs.x=Math.floor(i),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height*this.scale}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){var t,i;return null===(i=null===(t=this.getVoiceContainer(e.voice))||void 0===t?void 0:t.beatGlyphs)||void 0===i?void 0:i[e.index]}getPreNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.preNotes}getOnNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.onNotes}paint(e,t,i){this.paintBackground(e,t,i),i.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,i);for(const s of this._voiceContainers.values())i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.paint(e+this.x,t+this.y,i);i.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,i)}paintBackground(e,t,i){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,i)}buildBoundingsLookup(e,t,i){let s=new as;s.bar=this.bar,s.visualBounds=new Qe,s.visualBounds.x=t+this.x,s.visualBounds.y=i+this.y+this.topPadding,s.visualBounds.w=this.width,s.visualBounds.h=this.height-this.topPadding-this.bottomPadding,s.realBounds=new Qe,s.realBounds.x=t+this.x,s.realBounds.y=i+this.y,s.realBounds.w=this.width,s.realBounds.h=this.height,e.addBar(s);for(const[e,a]of this._voiceContainers){let r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(s,t+this.x+a.x,i+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this._wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(this.bar.voices[e])}}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=Hs.PreNotes){let i=this.getBeatContainer(e);if(i)switch(t){case Hs.PreNotes:return i.voiceContainer.x+i.x;case Hs.OnNotes:return i.voiceContainer.x+i.x+i.onNotes.x;case Hs.MiddleNotes:return i.voiceContainer.x+i.x+i.onTimeX;case Hs.Stem:const t=i.onNotes.beamingHelper?i.onNotes.beamingHelper.getBeatLineX(e):i.onNotes.x+i.onNotes.width/2;return i.voiceContainer.x+t;case Hs.PostNotes:return i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.width;case Hs.EndBeat:return i.voiceContainer.x+i.x+i.width}return 0}getNoteX(e,t){let i=this.getBeatContainer(e.beat);return i?i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.getNoteX(e,t):0}getNoteY(e,t){let i=this.getOnNotesGlyphForBeat(e.beat);return i?i.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&(this._preBeatGlyphs=new ua,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,i){switch(this.bar.simileMark){case h.Simple:i.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,P.Repeat1Bar,!1);break;case h.SecondOfDouble:i.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,P.Repeat2Bars,!1)}}completeBeamingHelper(e){}}Ta.LineSpacing=8,Ta.StemWidth=.12*Ta.LineSpacing,Ta.StaffLineThickness=.13*Ta.LineSpacing,Ta.BeamThickness=.5*Ta.LineSpacing,Ta.BeamSpacing=.25*Ta.LineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(Us||(Us={}));class ka extends ks{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case Us.SingleOnBeatToEnd:case Us.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height)}}createOrResizeGlyph(e,t){let i;switch(e){case Us.FullBar:case Us.SinglePreBeat:case Us.SingleOnBeat:case Us.SingleOnBeatToEnd:return i=this.info.createNewGlyph(this.renderer,t),i.renderer=this.renderer,i.beat=t,i.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,i),this._uniqueEffectGlyphs[t.voice.index].push(i),i;case Us.GroupedOnBeat:case Us.GroupedOnBeatToEnd:let s=e===Us.GroupedOnBeat?Us.SingleOnBeat:Us.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){let e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let i=null;if(t.index>0&&this._effectGlyphs[t.voice.index].has(e.index))i=this._effectGlyphs[t.voice.index].get(e.index);else if(this.renderer.index>0){let s=this.renderer.previousRenderer.getBand(this.voice,this.info.effectId)._effectGlyphs[t.voice.index];s.has(e.index)&&(i=s.get(e.index))}let a=this.createOrResizeGlyph(s,t);return i&&this.info.canExpand(e,t)&&(i.nextGlyph=a,a.previousGlyph=i,this.isLinkedToPrevious=!0),a}return this.createOrResizeGlyph(s,t)}return this.createOrResizeGlyph(s,t);default:return this.createOrResizeGlyph(Us.SingleOnBeat,t)}}paint(e,t,i){super.paint(e,t,i);for(let s=0,a=this._uniqueEffectGlyphs.length;s<a;s++){let a=this._uniqueEffectGlyphs[s];for(let s=0,r=a.length;s<r;s++){a[s].paint(e+this.x,t+this.y,i)}}}alignGlyphs(){for(let e=0;e<this._effectGlyphs.length;e++)for(const t of this._effectGlyphs[e].keys())this.alignGlyph(this.info.sizingMode,this.renderer.bar.voices[e].beats[t])}alignGlyph(e,t){let i,s=this._effectGlyphs[t.voice.index].get(t.index),a=this.renderer.getBeatContainer(t);switch(e){case Us.SinglePreBeat:i=a.preNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case Us.SingleOnBeat:case Us.GroupedOnBeat:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case Us.SingleOnBeatToEnd:case Us.GroupedOnBeatToEnd:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,a.beat.isLastOfVoice?s.width=this.renderer.width-s.x:s.width=a.width-a.preNotes.width-a.preNotes.x;break;case Us.FullBar:s.width=this.renderer.width}}}class va{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Na{constructor(){this.bands=[],this.shared=new va}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 xa{constructor(){this.slots=[],this._effectSlot=new Map}getOrCreateSlot(e){if(this._effectSlot.has(e.info.effectId)){let t=this._effectSlot.get(e.info.effectId);if(t.canBeUsed(e))return t}for(let t of this.slots)if(t.canBeUsed(e))return t;let t=new Na;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class Pa extends ca{constructor(){super(0,0),this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.x=e,i.renderer=this.renderer,i.doLayout(),e+=i.width}this.width=e,this.computedWidth=e}noteLoop(e){for(let t=this.container.beat.notes.length-1;t>=0;t--)e(this.container.beat.notes[t])}}class Ea extends Pa{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,i){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class Ca extends Ta{constructor(e,t,i){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=i}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(let t of this.sizingInfo.slots){t.shared.y=e;for(let i of t.bands)i.y=e,i.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){if(!super.applyLayoutingInfo())return!1;if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new xa;for(let e of this._bands)e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),!0}scaleToWidth(e){super.scaleToWidth(e);for(let e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(let e of this.bar.voices)if(this.hasVoiceContainer(e))for(let t of this._infos){let i=new ka(e,t);i.renderer=this,i.doLayout(),this._bands.push(i),this._bandLookup.set(e.index+"."+t.effectId,i)}for(let e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e);for(let e of this._bands)e.isLinkedToPrevious&&(this.isLinkedToPrevious=!0)}createVoiceGlyphs(e){for(let t of e.beats){let i=new Es(t,this.getVoiceContainer(e));i.preNotes=new Pa,i.onNotes=new Ea,this.addBeatGlyph(i);for(let e of this._bands)e.createGlyph(t)}}paint(e,t,i){this.paintBackground(e,t,i);for(let s of this._bands)i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isEmpty||s.paint(e+this.x,t+this.y,i)}getBand(e,t){let i=e.index+"."+t;return this._bandLookup.has(i)?this._bandLookup.get(i):null}}class Fa extends da{constructor(e,t){super(),this._infos=t,this._staffId=e,this.isInAccolade=!1,this.isRelevantForBoundsLookup=!1}get staffId(){return this._staffId}create(e,t){return new Ca(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class La extends vs{constructor(e,t,i){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<Ce.MaxAlternateEndings;e++)0!=(i&1<<e)&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(La.Padding*this.scale+2);let e="";for(let t=0,i=this._endings.length;t<i;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,i){super.paint(e,t,i);let s=i.textBaseline;if(i.textBaseline=C.Top,this._endings.length>0){let s=this.renderer.resources;i.font=s.wordsFont,i.moveTo(e+this.x,t+this.y+this.height),i.lineTo(e+this.x,t+this.y),i.lineTo(e+this.x+this.width,t+this.y),i.stroke(),i.fillText(this._endingsString,e+this.x+La.Padding*this.scale,t+this.y*this.scale)}i.textBaseline=s}}La.Padding=3;class Ma{get effectId(){return this.notationElement.toString()}}class Da extends Ma{get notationElement(){return v.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Us.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new La(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class Ia extends vs{constructor(e,t,i,s,a=E.Left){super(e,t),this._lines=i.split("\n"),this.font=s,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,i){let s=i.color;i.color=s,i.font=this.font;let a=i.textAlign;i.textAlign=this.textAlign;let r=t+this.y;for(let t of this._lines)i.fillText(t,e+this.x,r),r+=this.font.size;i.textAlign=a}}class Ra extends Ma{get notationElement(){return v.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Ia(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,E.Left)}canExpand(e,t){return!1}}class Aa extends Ma{get notationElement(){return v.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Ia(0,0,t.chord.name,e.resources.effectFont,E.Center)}canExpand(e,t){return!1}}class Oa extends vs{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}paint(e,t,i){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,i);let s;if(!this.isLinkedWithNext&&this.forceGroupedRendering)s=this;else for(s=this.nextGlyph;s.isLinkedWithNext;)s=s.nextGlyph;let a=s.renderer,r=s.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,i)}calculateEndX(e,t,i,s){return t?i+e.x+e.getBeatX(t,s):i+e.x+this.x+this.width}paintNonGrouped(e,t,i){let s=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,s,this.endPosition);this.paintGrouped(e,t,a,i)}}class Ga extends Oa{constructor(e,t,i){super(Hs.EndBeat),this._crescendo=u.None,this._crescendo=i,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17*this.scale}paintGrouped(e,t,i,s){let a=e+this.x,r=this.height*this.scale;s.beginPath(),this._crescendo===u.Crescendo?(i-=Ga.Padding*this.scale,s.moveTo(i,t+this.y),s.lineTo(a,t+this.y+r/2),s.lineTo(i,t+this.y+r)):(i-=Ga.Padding*this.scale,s.moveTo(a,t+this.y),s.lineTo(i,t+this.y+r/2),s.lineTo(a,t+this.y+r)),s.stroke()}}Ga.Padding=xs.QuarterNoteHeadWidth/2|0;class Ha extends Ma{get notationElement(){return v.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==u.None}createNewGlyph(e,t){return new Ga(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Va extends Ns{constructor(e,t,i){super(e,t,.6,Va.getSymbol(i))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case g.PPP:return P.DynamicPPP;case g.PP:return P.DynamicPP;case g.P:return P.DynamicPiano;case g.MP:return P.DynamicMP;case g.MF:return P.DynamicMF;case g.F:return P.DynamicForte;case g.FF:return P.DynamicFF;case g.FFF:return P.DynamicFFF;default:return P.None}}}class Wa extends Ma{get notationElement(){return v.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest||e.graceType!==f.None)return!1;let t=this.getPreviousDynamicsBeat(e),i=0===e.voice.index&&!t||e.dynamics!==(null==t?void 0:t.dynamics);if(i&&e.voice.index>0)for(let t of e.voice.bar.voices)if(t.index<e.voice.index){let s=t.getBeatAtPlaybackStart(e.playbackStart);s&&e.dynamics===s.dynamics&&this.internalShouldCreateGlyph(s)&&(i=!1)}return i}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest&&t.graceType===f.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Va(0,0,t.dynamics)}canExpand(e,t){return!0}}class za extends vs{doLayout(){super.doLayout(),this.height=17*this.scale}paint(e,t,i){let s=6*this.scale,a=Math.max(this.width,14*this.scale),r=this.height/2;i.beginPath(),i.moveTo(e+this.x,t+this.y+r),i.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r-s),i.moveTo(e+this.x,t+this.y+r),i.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r+s),i.stroke()}}class Ua extends Ma{get notationElement(){return v.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new za}canExpand(e,t){return!0}}class Xa extends Ns{constructor(e,t,i){super(e,t,1,Xa.getSymbol(i))}static getSymbol(e){switch(e){case G.Short:return P.FermataShortAbove;case G.Medium:return P.FermataAbove;case G.Long:return P.FermataLongAbove;default:return P.None}}doLayout(){this.width=23*this.scale,this.height=12*this.scale}paint(e,t,i){super.paint(e-this.width/2,t+this.height,i)}}class Ya extends Ma{get notationElement(){return v.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new Xa(0,0,t.fermata.type)}canExpand(e,t){return!0}}class qa extends Ma{get notationElement(){return v.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(t,i){return!(0!==i.voice.index||i.isRest||t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBand&&t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBandForcePiano)&&(1===i.notes.length&&i.notes[0].isFingering)}createNewGlyph(e,t){var i;let s=m.Unknown,a=!1,r=t.notes[0];r.leftHandFinger!==m.Unknown?(s=r.leftHandFinger,a=!0):r.rightHandFinger!==m.Unknown&&(s=r.rightHandFinger);let n=null!==(i=me.fingerToString(e.settings,t,s,a))&&void 0!==i?i:"";return new Ia(0,0,n,e.resources.fingeringFont,E.Left)}canExpand(e,t){return!0}}class Ja extends Ma{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,i=t.notes.length;e<i;e++){let i=t.notes[e];this.shouldCreateGlyphForNote(i)&&this.lastCreateInfo.push(i)}return this.lastCreateInfo.length>0}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}canExpand(e,t){return!0}}class ja extends Oa{constructor(e){super(Hs.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=Hs.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=E.Center,i.fillText(this._label,e+this.x,t+this.y),i.textAlign=a}paintGrouped(e,t,i,s){this.paintNonGrouped(e,t,s);let a=3*this.scale,r=s.measureText(this._label),n=e+this.x+r/2+a,o=t+this.y+4*this.scale,h=8*this.scale;if(i>n){let e=n;for(;e<i;)s.beginPath(),s.moveTo(e,0|o),s.lineTo(Math.min(e+h,i),0|o),e+=h+a,s.stroke();s.beginPath(),s.moveTo(i,o-5*this.scale|0),s.lineTo(i,o+5*this.scale|0),s.stroke()}}}ja.LineSpacing=3,ja.LineTopPadding=4,ja.LineTopOffset=5,ja.LineSize=8;class Qa extends Ja{constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case y.None:this._effectId="harmonics-none";break;case y.Natural:this._effectId="harmonics-natural";break;case y.Artificial:this._effectId="harmonics-artificial";break;case y.Pinch:this._effectId="harmonics-pinch";break;case y.Tap:this._effectId="harmonics-tap";break;case y.Semi:this._effectId="harmonics-semi";break;case y.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}get effectId(){return this._effectId}get notationElement(){return v.EffectHarmonics}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return Us.GroupedOnBeat}createNewGlyph(e,t){return new ja(Qa.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case y.Natural:return"N.H.";case y.Artificial:return"A.H.";case y.Pinch:return"P.H.";case y.Tap:return"T.H.";case y.Semi:return"S.H.";case y.Feedback:return"Fdbk."}return""}}class $a extends Ma{get notationElement(){return v.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return Us.GroupedOnBeat}createNewGlyph(e,t){return new ja("LetRing")}canExpand(e,t){return!0}}class Ka extends vs{constructor(e,t,i,s,a=E.Center){super(e,t),this._lines=i,this.font=s,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,i){i.font=this.font;let s=i.textAlign;i.textAlign=this.textAlign;for(let s=0;s<this._lines.length;s++)this._lines[s]&&i.fillText(this._lines[s],e+this.x,t+this.y+s*this.font.size);i.textAlign=s}}class Za extends Ma{get notationElement(){return v.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new Ka(0,0,t.lyrics,e.resources.effectFont,E.Center)}canExpand(e,t){return!0}}class er extends Ma{get notationElement(){return v.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Us.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 Ia(0,0,t.voice.bar.masterBar.section.marker?"["+t.voice.bar.masterBar.section.marker+"] "+t.voice.bar.masterBar.section.text:t.voice.bar.masterBar.section.text,e.resources.markerFont,E.Left)}canExpand(e,t){return!0}}class tr extends Oa{constructor(e,t){super(Hs.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13*this.scale}paintNonGrouped(e,t,i){this.paintOttava(e,t,i)}paintOttava(e,t,i){let s=0;switch(this._ottava){case o._15ma:s=37*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.QuindicesimaAlta,!1);break;case o._8va:s=26*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.OttavaAlta,!1);break;case o._8vb:s=23*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.OttavaBassaVb,!1);break;case o._15mb:s=36*this.scale,i.fillMusicFontSymbols(e+this.x-s/2,t+this.y+this.height,.8,[P.Quindicesima,P.OctaveBaselineM,P.OctaveBaselineB],!1)}return s/2}paintGrouped(e,t,i,s){let a=this.paintOttava(e,t,s),r=3*this.scale,n=e+this.x+a+r,o=t+this.y;o+=this._aboveStaff?2*this.scale:this.height-2*this.scale;let h=8*this.scale;if(i>n){let e=n;for(;e<i;)s.beginPath(),s.moveTo(e,0|o),s.lineTo(Math.min(e+h,i),0|o),e+=h+r,s.stroke();s.beginPath(),this._aboveStaff?(s.moveTo(i,o),s.lineTo(i,t+this.y+this.height)):(s.moveTo(i,o),s.lineTo(i,t+this.y)),s.stroke()}}}class ir extends Ma{constructor(e){super(),this._aboveStaff=e}get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return v.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.GroupedOnBeat}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 tr(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class sr extends Ja{get notationElement(){return v.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return Us.GroupedOnBeat}createNewGlyph(e,t){return new ja("P.M.")}constructor(){super()}}class ar extends Ja{get notationElement(){return v.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===_.PickSlideDown||e.slideOutType===_.PickSlideUp}get sizingMode(){return Us.GroupedOnBeat}createNewGlyph(e,t){return new ja("P.S.")}constructor(){super()}}class rr extends Ns{constructor(e,t,i){super(e,t,xs.GraceScale,rr.getSymbol(i))}doLayout(){this.width=9*this.scale,this.height=13*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}static getSymbol(e){switch(e){case x.Up:return P.StringsUpBow;case x.Down:return P.StringsDownBow;default:return P.None}}}class nr extends Ma{get notationElement(){return v.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==x.None}createNewGlyph(e,t){return new rr(0,0,t.pickStroke)}canExpand(e,t){return!0}}class or extends Oa{constructor(e){super(Hs.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case w.Slight:this._stepSize=12*this.scale;break;case w.Wide:this._stepSize=23*this.scale}this.height=18*this.scale}paintGrouped(e,t,i,s){let a=e+this.x,r=i-a,n=Math.max(1,r/this._stepSize);s.beginPath(),s.moveTo(a,t+this.y);for(let e=0;e<n;e++)s.lineTo(a+this._stepSize/2,t+this.y+this.height),s.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;s.stroke()}}class hr extends Ma{get notationElement(){return v.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Slight}createNewGlyph(e,t){return new or(w.Slight)}canExpand(e,t){return!0}}class lr extends Oa{constructor(e,t,i,s=1.2,a=!1){super(Hs.EndBeat),this._scale=0,this._symbol=P.None,this._symbolSize=0,this._type=i,this._scale=s,this.x=e,this.y=t,this._partialWaves=a}doLayout(){super.doLayout();let e=0;switch(this._type){case w.Slight:this._symbol=P.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case w.Wide:this._symbol=P.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e*this.scale}paintGrouped(e,t,i,s){let a=i-(e+this.x),r=this._symbolSize*this.scale,n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let i=0;i<n;i++)s.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale*this.scale,this._symbol,!1),o+=r}}class dr extends Ja{get notationElement(){return v.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===w.Slight||e.isTieDestination&&e.tieOrigin.vibrato===w.Slight}get sizingMode(){return Us.GroupedOnBeatToEnd}createNewGlyph(e,t){return new lr(0,0,w.Slight,1.2)}constructor(){super()}}class cr extends Ma{get notationElement(){return v.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let i=e.resources;return t.slap?new Ia(0,0,"S",i.effectFont,E.Left):t.pop?new Ia(0,0,"P",i.effectFont,E.Left):new Ia(0,0,"T",i.effectFont,E.Left)}canExpand(e,t){return!0}}class ur extends vs{constructor(e,t,i){super(e,t),this._tempo=0,this._tempo=i}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.markerFont,i.fillMusicFontSymbol(e+this.x,t+this.y+.8*this.height,this.scale*xs.GraceScale,P.NoteQuarterUp,!1),i.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+i.font.size/2)}}class pr extends Ma{get notationElement(){return v.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Us.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&(!!t.voice.bar.masterBar.tempoAutomation||0===t.voice.bar.index)}createNewGlyph(e,t){let i=0;return i=t.voice.bar.masterBar.tempoAutomation?t.voice.bar.masterBar.tempoAutomation.value:t.voice.bar.staff.track.score.tempo,new ur(0,0,i)}canExpand(e,t){return!0}}class gr extends Ma{get notationElement(){return v.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Ia(0,0,t.text,e.resources.effectFont,E.Left)}canExpand(e,t){return!0}}class fr extends vs{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.markerFont;let a=i.measureText("tr");i.fillText("tr",e+this.x,t+this.y);let r=a+3*this.scale,n=this.width-r,o=11*this.scale*1.2,h=Math.max(1,(n-r)/o),l=r,d=t+this.y+1.2*this.height;for(let t=0;t<h;t++)i.fillMusicFontSymbol(e+this.x+l,d,1.2,P.WiggleTrill,!1),l+=o}}class mr extends Ja{get notationElement(){return v.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return Us.SingleOnBeat}createNewGlyph(e,t){return new fr(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Xs||(Xs={}));class yr extends vs{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,i){e+=this.x;let s=(t+=this.y)+this.height*xs.GraceScale;i.font=this.renderer.resources.effectFont,i.fillText("(",e,t+.3*this.height);let a=e+10*this.scale,r=e+40*this.scale;switch(this._tripletFeel){case R.NoTripletFeel:this.renderBarNote(a,s,yr.NoteScale,i,[Xs.Full]),this.renderBarNote(r,s,yr.NoteScale,i,[Xs.Full]);break;case R.Triplet8th:this.renderBarNote(a,s,yr.NoteScale,i,[Xs.Full]),i.fillMusicFontSymbol(r,s,yr.NoteScale,P.NoteQuarterUp,!1),i.fillMusicFontSymbol(r+yr.NoteSeparation*this.scale,s,yr.NoteScale,P.NoteEighthUp,!1),this.renderTriplet(r,t,i);break;case R.Triplet16th:this.renderBarNote(a,s,yr.NoteScale,i,[Xs.Full,Xs.Full]),this.renderBarNote(r,s,yr.NoteScale,i,[Xs.Full,Xs.PartialRight]),this.renderTriplet(r,t,i);break;case R.Dotted8th:this.renderBarNote(a,s,yr.NoteScale,i,[Xs.Full]),this.renderBarNote(r,s,yr.NoteScale,i,[Xs.Full,Xs.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case R.Dotted16th:this.renderBarNote(a,s,yr.NoteScale,i,[Xs.Full,Xs.Full]),this.renderBarNote(r,s,yr.NoteScale,i,[Xs.Full,Xs.Full,Xs.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case R.Scottish8th:this.renderBarNote(a,s,yr.NoteScale,i,[Xs.Full]),this.renderBarNote(r,s,yr.NoteScale,i,[Xs.Full,Xs.PartialLeft]),i.fillCircle(r+yr.NoteSeparation*this.scale+8*this.scale,s,this.scale);break;case R.Scottish16th:this.renderBarNote(a,s,yr.NoteScale,i,[Xs.Full,Xs.Full]),this.renderBarNote(r,s,yr.NoteScale,i,[Xs.Full,Xs.Full,Xs.PartialLeft]),i.fillCircle(r+yr.NoteSeparation*this.scale+8*this.scale,s,this.scale)}i.fillText("=",e+30*this.scale,t+5*this.scale),i.fillText(")",e+65*this.scale,t+.3*this.height)}renderBarNote(e,t,i,s,a){s.fillMusicFontSymbol(e,t,i,P.NoteQuarterUp,!1);let r=yr.NoteSeparation/2*this.scale;for(let i=0;i<a.length;i++)switch(a[i]){case Xs.Full:s.fillRect(e+4*this.scale,t-yr.NoteHeight*this.scale+yr.BarSeparation*this.scale*i,yr.NoteSeparation*this.scale,yr.BarHeight*this.scale);break;case Xs.PartialLeft:s.fillRect(e+4*this.scale,t-yr.NoteHeight*this.scale+yr.BarSeparation*this.scale*i,r,yr.BarHeight*this.scale);break;case Xs.PartialRight:s.fillRect(e+4*this.scale+r,t-yr.NoteHeight*this.scale+yr.BarSeparation*this.scale*i,r,yr.BarHeight*this.scale)}s.fillMusicFontSymbol(e+yr.NoteSeparation*this.scale,t,i,P.NoteQuarterUp,!1)}renderTriplet(e,t,i){t+=2*this.scale;let s=this.renderer.resources.effectFont;i.font=bi.withFamilyList(s.families,.8*s.size,s.style);let a=e+yr.NoteSeparation*this.scale+3*this.scale;i.beginPath(),i.moveTo(e,t+3*this.scale),i.lineTo(e,t),i.lineTo(e+5*this.scale,t),i.moveTo(a+5*this.scale,t+3*this.scale),i.lineTo(a+5*this.scale,t),i.lineTo(a,t),i.stroke(),i.fillText("3",e+7*this.scale,t-10*this.scale),i.font=s}}yr.NoteScale=.4,yr.NoteHeight=12,yr.NoteSeparation=12,yr.BarHeight=2,yr.BarSeparation=3;class br extends Ma{get notationElement(){return v.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Us.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==R.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new yr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Sr extends Ma{get notationElement(){return v.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Us.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new ja("w/bar")}canExpand(e,t){return!0}}class _r extends Ma{get notationElement(){return v.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Us.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Wide}createNewGlyph(e,t){return new or(w.Wide)}canExpand(e,t){return!0}}class wr extends Ja{get notationElement(){return v.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===w.Wide||e.isTieDestination&&e.tieOrigin.vibrato===w.Wide}get sizingMode(){return Us.GroupedOnBeatToEnd}createNewGlyph(e,t){return new lr(0,0,w.Wide,1.2)}}class Br extends vs{constructor(e,t,i){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=i}doLayout(){super.doLayout();const e=this.scale;let t=this.renderer.resources;this._textRow=1.5*t.effectFont.size*e,this._fretRow=1.5*t.effectFont.size*e,this._chord.firstFret>1?this._firstFretSpacing=Br.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(Br.Frets-1)*Br.FretSpacing*e+2*Br.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*Br.StringSpacing*e+2*Br.Padding*e}paint(e,t,i){e+=this.x+Br.Padding*this.scale+this._firstFretSpacing,t+=this.y;let s=this.width-2*Br.Padding*this.scale+this.scale-this._firstFretSpacing,a=Br.StringSpacing*this.scale,r=Br.FretSpacing*this.scale,n=this.renderer.resources,o=Br.CircleRadius*this.scale,h=i.textAlign,l=i.textBaseline;i.font=n.effectFont,i.textAlign=E.Center,i.textBaseline=C.Top,this._chord.showName&&i.fillText(this._chord.name,e+this.width/2,t+n.effectFont.size/2),t+=this._textRow,e+=a/2,i.font=n.fretboardNumberFont,i.textBaseline=C.Middle;for(let s=0;s<this._chord.staff.tuning.length;s++){let r=e+s*a,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-s-1];o<0?i.fillMusicFontSymbol(r,n,this.scale,P.FretboardX,!0):0===o?i.fillMusicFontSymbol(r,n,this.scale,P.FretboardO,!0):(o-=this._chord.firstFret-1,i.fillText(o.toString(),r,n))}t+=this._fretRow;for(let s=0;s<this._chord.staff.tuning.length;s++){let n=e+s*a;i.fillRect(n,t,1,r*Br.Frets+this.scale)}this._chord.firstFret>1&&(i.textAlign=E.Left,i.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+r/2)),i.fillRect(e,t-this.scale,s,2*this.scale);for(let a=0;a<=Br.Frets;a++){let n=t+a*r;i.fillRect(e,n,s,this.scale)}let d=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];d.set(e-this._chord.firstFret,t)}for(let s=0;s<this._chord.strings.length;s++){let n=this._chord.strings[s];if(n>0){if(n-=this._chord.firstFret,d.has(n)){let e=d.get(n);(-1===e[0]||s<e[0])&&(e[0]=s),(-1===e[1]||s>e[1])&&(e[1]=s)}let h=t+n*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-s-1)*a;i.fillCircle(l,h,o)}}for(const[s,n]of d){let h=t+s*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-n[1]-1)*a,d=e+(this._chord.strings.length-n[0]-1)*a;i.fillRect(l,h-o,d-l,2*o)}i.textAlign=h,i.textBaseline=l}}Br.Padding=5,Br.Frets=5,Br.CircleRadius=2.5,Br.StringSpacing=10,Br.FretSpacing=12;class Tr extends ca{constructor(e,t,i=E.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=i}doLayout(){let e=0;switch(this._align){case E.Left:e=0;break;case E.Center:e=(this.width-this._glyphWidth)/2;break;case E.Right:e=this.width-this._glyphWidth}for(let t of this.glyphs)t.x=e,e+=t.width}addGlyphToRow(e){this.glyphs.push(e),this._glyphWidth+=e.width,e.height>this.height&&(this.height=e.height)}}class kr extends ca{constructor(e,t,i=E.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=i}doLayout(){let e=0,t=0,i=2*kr.Padding*this.scale;this._rows=[];let s=new Tr(e,t,this._align);s.width=this.width;for(let a of this.glyphs)e+a.width<this.width?(s.addGlyphToRow(a),e+=a.width):(s.isEmpty||(s.doLayout(),this._rows.push(s),t+=s.height+i),e=0,s=new Tr(e,t,this._align),s.width=this.width,s.addGlyphToRow(a),e+=a.width);s.isEmpty||(s.doLayout(),this._rows.push(s),t+=s.height+i),this.height=t+i}paint(e,t,i){for(let s of this._rows)s.paint(e+this.x,t+this.y+kr.Padding*this.scale,i)}}kr.Padding=3;class vr extends kr{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new Br(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Nr{constructor(e,t,i){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.trackIndex=0,this.staveTop=0,this.topSpacing=20,this.bottomSpacing=5,this.staveBottom=0,this.isFirstInAccolade=!1,this.isLastInAccolade=!1,this._factory=i,this.trackIndex=e,this.modelStaff=t}get staveId(){return this._factory.staffId}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInAccolade(){return this._factory.isInAccolade}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.staveGroup.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let i;i=e?this._factory.create(this.staveGroup.layout.renderer,e):new Ta(this.staveGroup.layout.renderer,e),i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo(),this.barRenderers.push(i),e&&this.staveGroup.layout.registerBarRenderer(this.staveId,i)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];return this.barRenderers.splice(this.barRenderers.length-1,1),this.staveGroup.layout.unregisterBarRenderer(this.staveId,e),e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=e-this.staveGroup.width,i=t/this.barRenderers.length,s=0,a=this.topOverflow;for(let e=0,r=this.barRenderers.length;e<r;e++)this.barRenderers[e].x=s,this.barRenderers[e].y=this.topSpacing+a,0!==t&&this.barRenderers[e].scaleToWidth(this.barRenderers[e].width+i),s+=this.barRenderers[e].width}get topOverflow(){let e=0;for(let t=0,i=this.barRenderers.length;t<i;t++){let i=this.barRenderers[t];i.topOverflow>e&&(e=i.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,i=this.barRenderers.length;t<i;t++){let i=this.barRenderers[t];i.bottomOverflow>e&&(e=i.bottomOverflow)}return e}finalizeStaff(){this.height=0;let e=!1,t=this.topOverflow;for(let i=0;i<this.barRenderers.length;i++)this.barRenderers[i].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[i].height),this.barRenderers[i].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[e].height),this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,i,s,a){if(0!==this.height&&0!==a)for(let r=s,n=Math.min(s+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,i)}}class xr{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 Pr{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSizes=new Map,this.onBeatSizes=new Map,this.onBeatCenterX=new Map,this.preBeatSize=0,this.postBeatSize=0,this.voiceSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateVoiceSize(e){e>this.voiceSize&&(this.voiceSize=e,this.version++)}setPreBeatSize(e,t){(!this.preBeatSizes.has(e.index)||this.preBeatSizes.get(e.index)<t)&&(this.preBeatSizes.set(e.index,t),this.version++)}getPreBeatSize(e){return this.preBeatSizes.has(e.index)?this.preBeatSizes.get(e.index):0}setOnBeatSize(e,t){(!this.onBeatSizes.has(e.index)||this.onBeatSizes.get(e.index)<t)&&(this.onBeatSizes.set(e.index,t),this.version++)}getOnBeatSize(e){return this.onBeatSizes.has(e.index)?this.onBeatSizes.get(e.index):0}getBeatCenterX(e){return this.onBeatCenterX.has(e.index)?this.onBeatCenterX.get(e.index):0}setBeatCenterX(e,t){(!this.onBeatCenterX.has(e.index)||this.onBeatCenterX.get(e.index)<t)&&(this.onBeatCenterX.set(e.index,t),this.version++)}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}addSpring(e,t,i,s,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<i&&(r.graceBeatWidth=i),r.preBeatWidth<s&&(r.preBeatWidth=s),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new xr,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){let e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=i,r.preBeatWidth=s,this.springs.set(e,r);let n=this._timeSortedSprings,o=n.length-1;for(;o>0&&n[o].timePosition>e;)o--;this._timeSortedSprings.splice(o+1,0,r)}return(-1===this._minTime||this._minTime>e)&&(this._minTime=e),r}addBeatSpring(e,t,i){let s=e.absoluteDisplayStart;if(e.graceType!==f.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));let r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<i&&(r.postSpringWidth=i),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new xr;r.timePosition=s,r.postSpringWidth=i,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(s,e.displayDuration,a,t,i)}}finish(){for(const[e,t]of this.allGraceRods){let i=0;if(this.incompleteGraceRods.has(e))for(const e of t)i+=e.preBeatWidth,e.graceBeatWidth=i,i+=e.postSpringWidth;else for(let e=t.length-1;e>=0;e--)t[e].graceBeatWidth=i,i-=t[e].preBeatWidth+t[e].postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){this._xMin=0;let e=this.springs;for(const t of e.values())t.springWidth<this._xMin&&(this._xMin=t.springWidth);let t=0,i=this._timeSortedSprings;if(0===i.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<i.length;e++){let s=i[e],a=0;if(e===i.length-1)a=s.longestDuration;else{let t=i[e+1];a=Math.abs(t.timePosition-s.timePosition)}s.springConstant=this.calculateSpringConstant(s,a),t+=1/s.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<i.length;e++){let t=i[e],s=0;if(e===i.length-1)s=t.postSpringWidth;else{let a=i[e+1];s=t.postSpringWidth+a.preSpringWidth}0===e&&(s+=t.preSpringWidth);let a=s*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,i){}calculateSpringConstant(e,t){return t<=0&&(t=le.toTicks(p.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Pr.MinDuration))*Pr.MinDurationWidth))}spaceToForce(e){return-1!==this.totalSpringConstant?(this._timeSortedSprings.length>0&&(e-=this._timeSortedSprings[0].preSpringWidth),e-=this._incompleteGraceRodsWidth,Math.max(e,0)*this.totalSpringConstant):-1}calculateVoiceWidth(e){let t=0;return-1!==this.totalSpringConstant&&(t=this.calculateWidth(e,this.totalSpringConstant)),this._timeSortedSprings.length>0&&(t+=this._timeSortedSprings[0].preSpringWidth),t+=this._incompleteGraceRodsWidth,t}calculateWidth(e,t){return e/t}buildOnTimePositions(e){if(-1===this.totalSpringConstant)return new Map;if(me.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;let t=new Map;this._onTimePositions=t;let i=this._timeSortedSprings;if(0===i.length)return t;let s=i[0].preSpringWidth;for(let a=0;a<i.length;a++)t.set(i[a].timePosition,s),s+=this.calculateWidth(e,i[a].springConstant);return t}}Pr.MinDuration=30,Pr.MinDurationWidth=7;class Er{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Cr{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInAccolade=null,this.lastStaffInAccolade=null,this.staveGroup=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class Fr{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),this.calculateAccoladeSpacing(e),t.layoutingInfo.preBeatSize=0;let i=0;for(let e=0,s=this.staves.length;e<s;e++){let s=this.staves[e];for(let e=0,a=s.staves.length;e<a;e++){let a=s.staves[e],r=t.renderers[i++];a.addBarRenderer(r)}}return this.updateWidth(),t}addBars(e,t){if(0===e.length)return null;let i=new Er;i.layoutingInfo=new Pr,i.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(i),this.calculateAccoladeSpacing(e);let s=i.layoutingInfo;for(let e of this.staves)for(let a of e.staves){let r=e.track.staves[a.modelStaff.index].bars[t];a.addBar(r,s);let n=a.barRenderers[a.barRenderers.length-1];i.renderers.push(n),n.isLinkedToPrevious&&(i.isLinkedToPrevious=!0),n.canWrap||(i.canWrap=!1)}return s.finish(),i.width=this.updateWidth(),i}revertLastBar(){if(this.masterBarsRenderers.length>1){let e=this.masterBarsRenderers[this.masterBarsRenderers.length-1];this.masterBarsRenderers.splice(this.masterBarsRenderers.length-1,1);let t=0;for(let e=0,i=this._allStaves.length;e<i;e++){let i=this._allStaves[e].revertLastBar();t=Math.max(t,i.width)}return this.width-=t,e}return null}updateWidth(){let e=0;for(let t=0,i=this._allStaves.length;t<i;t++){let i=this._allStaves[t];i.barRenderers[i.barRenderers.length-1].applyLayoutingInfo(),i.barRenderers[i.barRenderers.length-1].width>e&&(e=i.barRenderers[i.barRenderers.length-1].width)}return this.width+=e,e}calculateAccoladeSpacing(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(v.TrackNames)){let t=this.layout.renderer.canvas,i=this.layout.renderer.settings.display.resources.effectFont;t.font=i;for(let i of e)this.accoladeSpacing=Math.ceil(Math.max(this.accoladeSpacing,t.measureText(i.shortName)));this.accoladeSpacing*=this.layout.scale,this.accoladeSpacing+=2*Fr.AccoladeLabelSpacing*this.layout.scale,this.width+=this.accoladeSpacing}else this.accoladeSpacing=0}getStaveTrackGroup(e){for(let t=0,i=this.staves.length;t<i;t++){let i=this.staves[t];if(i.track===e)return i}return null}addStaff(e,t){let i=this.getStaveTrackGroup(e);i||(i=new Cr(this,e),this.staves.push(i)),t.staveTrackGroup=i,t.staveGroup=this,t.index=this._allStaves.length,this._allStaves.push(t),i.addStaff(t),t.isInAccolade&&(this._firstStaffInAccolade||(this._firstStaffInAccolade=t,t.isFirstInAccolade=!0),i.firstStaffInAccolade||(i.firstStaffInAccolade=t),this._lastStaffInAccolade||(this._lastStaffInAccolade=t,t.isLastInAccolade=!0),this._lastStaffInAccolade&&(this._lastStaffInAccolade.isLastInAccolade=!1),this._lastStaffInAccolade=t,this._lastStaffInAccolade.isLastInAccolade=!0,i.lastStaffInAccolade=t)}get height(){return this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height}scaleToWidth(e){for(let t=0,i=this._allStaves.length;t<i;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,i){this.paintPartial(e+this.x,t+this.y,i,0,this.masterBarsRenderers.length)}paintPartial(e,t,i,s,a){for(let r=0,n=this._allStaves.length;r<n;r++)this._allStaves[r].paint(e,t,i,s,a);let r=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===s){if(i.color=r.barSeparatorColor,this._firstStaffInAccolade&&this._lastStaffInAccolade){let s=t+this._firstStaffInAccolade.y+this._firstStaffInAccolade.staveTop+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow,a=t+this._lastStaffInAccolade.y+this._lastStaffInAccolade.topSpacing+this._lastStaffInAccolade.topOverflow+this._lastStaffInAccolade.staveBottom,r=e+this._firstStaffInAccolade.x;i.beginPath(),i.moveTo(r,s),i.lineTo(r,a),i.stroke()}i.font=r.effectFont;for(let s=0,a=this.staves.length;s<a;s++){let a=this.staves[s];if(a.firstStaffInAccolade&&a.lastStaffInAccolade){let s=t+a.firstStaffInAccolade.y+a.firstStaffInAccolade.staveTop+a.firstStaffInAccolade.topSpacing+a.firstStaffInAccolade.topOverflow,r=t+a.lastStaffInAccolade.y+a.lastStaffInAccolade.topSpacing+a.lastStaffInAccolade.topOverflow+a.lastStaffInAccolade.staveBottom,n=e+a.firstStaffInAccolade.x,o=3*this.layout.renderer.settings.display.scale,h=o,l=s-4*o,d=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(v.TrackNames)&&i.fillText(a.track.shortName,e+Fr.AccoladeLabelSpacing*this.layout.scale,s),i.fillRect(n-h-o,l,o,d-l);let c=n-h-o,u=n+2*o;i.beginPath(),i.moveTo(c,l),i.bezierCurveTo(c,l,c,l,u,l-o),i.bezierCurveTo(n,l+o,c,l+o,c,l+o),i.closePath(),i.fill(),i.beginPath(),i.moveTo(c,d),i.bezierCurveTo(c,d,n,d,u,d+o),i.bezierCurveTo(n,d-o,c,d-o,c,d-o),i.closePath(),i.fill()}}}}finalizeGroup(){let e=0;for(let t of this._allStaves)t.x=this.accoladeSpacing,t.y=e,t.finalizeStaff(),e+=t.height}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;if(!this._firstStaffInAccolade||!this._lastStaffInAccolade)return;let i=this._allStaves[this._allStaves.length-1],s=t+this.y+this._firstStaffInAccolade.y,a=t+this.y+this._lastStaffInAccolade.y+this._lastStaffInAccolade.height,r=t+this.y+this._allStaves[0].y,n=t+this.y+i.y+i.height,o=t+this.y+this._firstStaffInAccolade.y+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow+(this._firstStaffInAccolade.barRenderers.length>0?this._firstStaffInAccolade.barRenderers[0].topPadding:0),h=a-s,l=t+this.y+i.y+i.height-i.bottomSpacing-i.bottomOverflow-(i.barRenderers.length>0?i.barRenderers[0].bottomPadding:0)-o,d=n-r,c=this.x+this._firstStaffInAccolade.x,u=new hs;u.visualBounds=new Qe,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new Qe,u.realBounds.x=e,u.realBounds.y=t+this.y,u.realBounds.w=this.width,u.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaveGroup(u);let p=new Map;for(let e=0;e<this.staves.length;e++)for(let i of this.staves[e].stavesRelevantForBoundsLookup)for(let e of i.barRenderers){let a;p.has(e.bar.masterBar.index)?a=p.get(e.bar.masterBar.index):(a=new ns,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new Qe,a.realBounds.x=c+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=d,a.visualBounds=new Qe,a.visualBounds.x=c+e.x,a.visualBounds.y=s,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new Qe,a.lineAlignedBounds.x=c+e.x,a.lineAlignedBounds.y=o,a.lineAlignedBounds.w=e.width,a.lineAlignedBounds.h=l,this.layout.renderer.boundsLookup.addMasterBar(a),p.set(a.index,a)),e.buildBoundingsLookup(a,c,t+this.y+i.y)}}getBarX(e){if(!this._firstStaffInAccolade||0===this.layout.renderer.tracks.length)return 0;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInAccolade.staveId,t).x}}Fr.AccoladeLabelSpacing=10;class Lr extends ca{constructor(e,t,i,s){super(e,t),this._tuning=i,this._trackLabel=s,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}createGlyphs(e){const t=this.renderer.scale,i=this.renderer.resources;this.height=0;const s=15*t;this._trackLabel.length>0&&(this.addGlyph(new Ia(0,this.height,this._trackLabel,i.effectFont,E.Left)),this.height+=s),this.addGlyph(new Ia(0,this.height,e.name,i.effectFont,E.Left));const a=64*t;if(this.renderer.scoreRenderer.canvas.font=i.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel)*t,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name)*t,2*a)),this.height+=s,!e.isStandard){const r=.7,n=Lr.CircleNumberHeight*r*t;let o=0|Math.ceil(e.tunings.length/2),h=0,l=this.height;for(let d=0,c=e.tunings.length;d<c;d++){const c=P.GuitarString0+(d+1);this.addGlyph(new Ns(h,l+n/1.2,r,c));const u="= "+Oe.getTextForTuning(e.tunings[d],!1);this.addGlyph(new Ia(h+n+1*t,l,u,i.effectFont,E.Left)),l+=s,d===o-1&&(l=this.height,h+=a)}this.height+=o*s}this.width+=15*t}}Lr.CircleNumberHeight=20;class Mr extends kr{constructor(e,t){super(e,t,E.Left)}addTuning(e,t){if(e.tunings.length>0){let i=new Lr(0,0,e,t);i.renderer=this.renderer,i.doLayout(),this.glyphs.push(i)}}}class Dr{constructor(e,t){this.args=e,this.renderCallback=t}}class Ir{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let i=this.renderer.settings.display.barCount;i<0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this.lastBarIndex=i,this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){this.renderer.partialLayoutFinished.trigger(e),this.renderer.settings.core.enableLazyLoading?this._lazyPartials.set(e.id,new Dr(e,t)):this.internalRenderLazyPartial(e,t)}internalRenderLazyPartial(e,t){const i=this.renderer.canvas;i.beginRender(e.width,e.height),t(i),e.renderResult=i.endRender(),this.renderer.partialRenderFinished.trigger(e)}renderLazyPartial(e){if(this._lazyPartials.has(e)){const t=this._lazyPartials.get(e);this.internalRenderLazyPartial(t.args,t.renderCallback)}}createScoreInfoGlyphs(){ge.debug("ScoreLayout","Creating score info glyphs");let e=this.renderer.settings.notation,t=this.renderer.score,i=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,t.title&&e.isNotationElementVisible(v.ScoreTitle)&&this.scoreInfoGlyphs.set(v.ScoreTitle,new Ia(0,0,t.title,i.titleFont,E.Center)),t.subTitle&&e.isNotationElementVisible(v.ScoreSubTitle)&&this.scoreInfoGlyphs.set(v.ScoreSubTitle,new Ia(0,0,t.subTitle,i.subTitleFont,E.Center)),t.artist&&e.isNotationElementVisible(v.ScoreArtist)&&this.scoreInfoGlyphs.set(v.ScoreArtist,new Ia(0,0,t.artist,i.subTitleFont,E.Center)),t.album&&e.isNotationElementVisible(v.ScoreAlbum)&&this.scoreInfoGlyphs.set(v.ScoreAlbum,new Ia(0,0,t.album,i.subTitleFont,E.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(v.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(v.ScoreWordsAndMusic,new Ia(0,0,"Music and Words by "+t.words,i.wordsFont,E.Center)):(t.music&&e.isNotationElementVisible(v.ScoreMusic)&&this.scoreInfoGlyphs.set(v.ScoreMusic,new Ia(0,0,"Music by "+t.music,i.wordsFont,E.Right)),t.words&&e.isNotationElementVisible(v.ScoreWords)&&this.scoreInfoGlyphs.set(v.ScoreWords,new Ia(0,0,"Words by "+t.words,i.wordsFont,E.Left)));const s=new Ta(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(v.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let i of t.staves)if(!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature){e.push(i);break}if(e.length>0){this.tuningGlyph=new Mr(0,0),this.tuningGlyph.renderer=s;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(e.isNotationElementVisible(v.ChordDiagrams)){this.chordDiagrams=new vr(0,0),this.chordDiagrams.renderer=s;let e=new Map;for(let t of this.renderer.tracks)for(let i of t.staves){const t=i.chords;for(const[i,s]of t)e.has(i)||s.showDiagram&&(e.set(i,s),this.chordDiagrams.addChord(s))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let t=new Fr;t.layout=this;for(let i=0;i<this.renderer.tracks.length;i++){let s=this.renderer.tracks[i],a=!1;for(let e of s.staves)if(e.showStandardNotation){a=!0;break}for(let r=0;r<s.staves.length;r++){let n,o=s.staves[r];if(o.isPercussion)n=e.StaveProfile.Score;else if(this.renderer.settings.display.staveProfile!==e.StaveProfile.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=e.StaveProfile.ScoreTab;else if(o.showTablature)n=a?e.StaveProfile.TabMixed:e.StaveProfile.Tab;else{if(!o.showStandardNotation)continue;n=e.StaveProfile.Score}let h=mo.staveProfiles.get(n);for(let e of h)e.canCreate(s,o)&&t.addStaff(s,new Nr(i,o,e))}}return t}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let i=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(i)?this._barRendererLookup.get(e).get(i):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",i=this.renderer.settings.display.resources,s=12*this.renderer.settings.display.scale,a=Math.floor(2*s);const r=new ss,n=bi.withFamilyList(i.copyrightFont.families,s,Z.Plain,ee.Bold);this.renderer.canvas.font=n;const o=mo.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return r.width=this.renderer.canvas.measureText(t),r.height=a,r.x=o?(this.width-r.width)/2:this.firstBarX,r.y=e,r.totalWidth=this.width,r.totalHeight=e+a,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=i.mainGlyphColor,e.font=n,e.textAlign=E.Left,e.fillText(t,0,s)})),e+a}}class Rr{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Ar extends Ir{constructor(e){super(e),this._group=null,this._pagePadding=null}get name(){return"HorizontalScreen"}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._group&&(e+=this._group.accoladeSpacing),e}doResize(){}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Ar.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let i=t,s=this.renderer.settings.display.barCount;s<=0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new Rr,o=0;for(;i<=s;){let t=this._group.addBars(this.renderer.tracks,i);if(t)if(0===n.masterBars.length&&t.isLinkedToPrevious&&r.length>0){let s=r[r.length-1];s.masterBars.push(e.masterBars[i]),s.width+=t.width,o+=t.width,n.x+=o}else n.masterBars.push(e.masterBars[i]),n.width+=t.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),o+=n.width,r.push(n),ge.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new Rr,n.x=o);i++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),r.push(n),ge.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],i=0;let h=0;for(let e=0;e<r.length;e++){const t=r[e],s=new ss;s.x=h,s.y=0,s.totalWidth=this.width,s.totalHeight=this.height,s.width=t.width,s.height=this.height,s.firstMasterBarIndex=t.masterBars[0].index,s.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,h+=t.width;const a=i,n=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(s,(e=>{let i=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===n&&(i-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=E.Left,ge.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-i,this._group.y,e,a,t.masterBars.length)})),i+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeGroup(){this._group.scaleToWidth(this._group.width),this._group.finalizeGroup()}}Ar.PagePadding=[20,20,20,20],Ar.GroupSpacing=20;class Or extends Ir{constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}get name(){return"PageView"}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Or.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._groups.length>0&&(e+=this._groups[0].accoladeSpacing),e}doResize(){let e=0;this.width=this.renderer.width;let t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let i=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.width,this.tuningGlyph.doLayout();let s=this.tuningGlyph.height+11*this.scale;const a=new ss;return a.x=0,a.y=e,a.width=this.width,a.height=s,a.totalWidth=this.width,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=i.scoreInfoColor,e.textAlign=E.Center,this.tuningGlyph.paint(0,0,e)})),e+s}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const i=this.renderer.settings.display.resources;this.chordDiagrams.width=this.width,this.chordDiagrams.doLayout();const s=Math.floor(this.chordDiagrams.height),a=new ss;return a.x=0,a.y=e,a.width=this.width,a.height=s,a.totalWidth=this.width,a.totalHeight=t<0?e+s:t,this.registerPartial(a,(e=>{e.color=i.scoreInfoColor,e.textAlign=E.Center,this.chordDiagrams.paint(0,0,e)})),e+s}layoutAndRenderScoreInfo(e,t=-1){ge.debug(this.name,"Layouting score info");const i=new ss;i.x=0,i.y=e;let s=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[v.ScoreTitle,v.ScoreSubTitle,v.ScoreArtist,v.ScoreAlbum,v.ScoreWordsAndMusic];for(let e=0;e<n.length;e++)if(this.scoreInfoGlyphs.has(n[e])){let t=this.scoreInfoGlyphs.get(n[e]);t.x=this.width/2,t.y=s,t.textAlign=E.Center,s+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(v.ScoreMusic)){let e=this.scoreInfoGlyphs.get(v.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=s,e.textAlign=E.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(v.ScoreWords)){let e=this.scoreInfoGlyphs.get(v.ScoreWords);e.x=this._pagePadding[0],e.y=s,e.textAlign=E.Left,o=!0,h=e.font.size*a}return o&&(s+=h),s=Math.floor(s+17*this.scale),i.width=this.width,i.height=s,i.totalWidth=this.width,i.totalHeight=t<0?e+i.height:t,this.registerPartial(i,(e=>{e.color=r.scoreInfoColor,e.textAlign=E.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+s}resizeAndRenderScore(e,t){if(-1!==this.renderer.settings.display.barsPerRow)for(let i=0;i<this._groups.length;i++){let s=this._groups[i];this.fitGroup(s),e+=this.paintGroup(s,t)}else{this._groups=[];let i=0,s=this.maxWidth,a=this.createEmptyStaveGroup();for(a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e;i<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[i];if(a.width+r.width<=s||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),i++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),i--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._groups.push(a),this.fitGroup(a),e+=this.paintGroup(a,t),a=this.createEmptyStaveGroup(),a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitGroup(a),e+=this.paintGroup(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,i=this.lastBarIndex;for(this._groups=[];t<=i;){let s=this.createStaveGroup(t,i);this._groups.push(s),s.x=this._pagePadding[0],s.y=e,t=s.lastBarIndex+1,this.fitGroup(s),ge.debug(this.name,"Rendering partial from bar "+s.firstBarIndex+" to "+s.lastBarIndex,null),e+=this.paintGroup(s,e)}return e}paintGroup(e,t){let i=Math.floor(e.height+20*this.scale);const s=new ss;return s.x=0,s.y=e.y,s.totalWidth=this.width,s.totalHeight=t,s.width=this.width,s.height=i,s.firstMasterBarIndex=e.firstBarIndex,s.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(s,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=E.Left,e.paint(0,-s.y,t)})),t+=i,i}fitGroup(e){e.isFull||e.width>this.maxWidth?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeGroup()}createStaveGroup(e,t){let i=this.createEmptyStaveGroup();i.index=this._groups.length;let s=this.renderer.settings.display.barsPerRow,a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)i.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=i.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}this._barsFromPreviousGroup=[];let e=!1;if((-1===s&&i.width>=a&&0!==i.masterBarsRenderers.length||i.masterBarsRenderers.length===s+1)&&(e=!0),e){let e=i.revertLastBar();if(e)for(this._barsFromPreviousGroup.push(e);e&&!e.canWrap&&i.masterBarsRenderers.length>1;)e=i.revertLastBar(),e&&this._barsFromPreviousGroup.push(e);return i.isFull=!0,i.isLast=!1,this._barsFromPreviousGroup.reverse(),i}i.x=0,n++}return i.isLast=t===i.lastBarIndex,i}get maxWidth(){return this.renderer.width-this._pagePadding[0]-this._pagePadding[2]}}Or.PagePadding=[40,40,40,40],Or.GroupSpacing=20;class Gr extends Ns{constructor(e,t,i,s=!1){super(e,t,s?xs.GraceScale:1,Gr.getMusicSymbol(i)),this._isGrace=s,this._accidentalType=i}static getMusicSymbol(e){switch(e){case Vs.Natural:return P.AccidentalNatural;case Vs.Sharp:return P.AccidentalSharp;case Vs.Flat:return P.AccidentalFlat;case Vs.NaturalQuarterNoteUp:return P.AccidentalQuarterToneNaturalArrowUp;case Vs.SharpQuarterNoteUp:return P.AccidentalQuarterToneSharpArrowUp;case Vs.FlatQuarterNoteUp:return P.AccidentalQuarterToneFlatArrowUp;case Vs.DoubleSharp:return P.AccidentalDoubleSharp;case Vs.DoubleFlat:return P.AccidentalDoubleFlat}return P.None}doLayout(){if(this._accidentalType===Vs.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*(this._isGrace?xs.GraceScale:1)*this.scale}}class Hr extends ks{constructor(e,t,i){super(e,t),this._number=0,this._number=i}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString())+5*this.scale}paint(e,t,i){if(!this.renderer.staff.isFirstInAccolade)return;let s=this.renderer.resources,a=i.color;i.color=s.barNumberColor,i.font=s.barNumberFont,i.fillText(this._number.toString(),e+this.x,t+this.y),i.color=a}}class Vr extends ks{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15*this.scale:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2*this.scale:(this.width=2*this.scale,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2*this.scale))}paint(e,t,i){let s=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a;this.renderer.isLast?(i.fillRect(n+this.width-s-s,a,this.scale,o),i.fillRect(n+this.width-s,a,s,o)):this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart||(i.fillRect(n+this.width-this.scale,a,this.scale,o),this.renderer.bar.masterBar.isDoubleBar&&i.fillRect(n+this.width-5*this.scale,a,this.scale,o))}}class Wr extends Ns{constructor(e,t,i,s){super(e,t,1,Wr.getSymbol(i)),this._clef=i,this._clefOttava=s}doLayout(){switch(this._clef){case n.Neutral:this.width=15*this.scale;break;case n.C3:case n.C4:case n.F4:case n.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case n.Neutral:return P.UnpitchedPercussionClef1;case n.C3:case n.C4:return P.CClef;case n.F4:return P.FClef;case n.G2:return P.GClef;default:return P.None}}paint(e,t,i){let s;super.paint(e,t,i);let a=!1;switch(this._clefOttava){case o._15ma:s=new Ns(-4*this.scale,0,.5,P.Quindicesima),a=!0;break;case o._8va:s=new Ns(-2*this.scale,0,.5,P.Ottava),a=!0;break;case o._8vb:s=new Ns(-6*this.scale,0,.5,P.Ottava);break;case o._15mb:s=new Ns(-8*this.scale,0,.5,P.Quindicesima);break;default:return}let r=0,h=0;switch(this._clef){case n.Neutral:r=a?-12:15,h=0;break;case n.C3:case n.C4:r=a?-19:27,h=0;break;case n.F4:r=a?-9:27,h=-4;break;case n.G2:r=a?-37:30,h=0;break;default:return}s.renderer=this.renderer,s.doLayout();let l=this.width/2;s.paint(e+this.x+l+h*this.scale,t+this.y+r*this.scale,i)}}class zr extends ks{constructor(e,t){super(e,t)}doLayout(){this.width=11*this.scale}paint(e,t,i){let s=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a,h=1.5*this.scale,l=(a+r)/2;i.fillCircle(n,l-3*h,h),i.fillCircle(n,l+3*h,h),n+=4*this.scale,i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke(),n+=3*this.scale+.5,i.fillRect(n,a,s,o)}}class Ur extends ks{constructor(e,t,i){super(e,t),this._count=0,this._count=0,this._count=i}doLayout(){this.width=0}paint(e,t,i){let s=this.renderer.resources,a=i.textAlign;i.font=s.barNumberFont,i.textAlign=E.Right;let r="x"+this._count,n=i.measureText(r)/1.5;i.fillText(r,e+this.x-n,t+this.y),i.textAlign=a}}class Xr extends ks{constructor(e,t,i,s){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=s,this._circleSize=i}doLayout(){this.width=13*this.scale}paint(e,t,i){let s=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x+.5,o=r-a;i.fillRect(n,a,s,o),n+=2*s-.5,i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke(),n+=3*this.scale;let h=this._circleSize*this.scale,l=(a+r)/2;i.fillCircle(n,l-h*this._dotOffset,h),i.fillCircle(n,l+h*this._dotOffset,h)}}class Yr extends Ns{constructor(e,t,i){super(e,t,1,Yr.getSymbol(i))}static getSymbol(e){switch(e){case a.None:return P.None;case a.Normal:return P.ArticAccentAbove;case a.Heavy:return P.ArticMarcatoAbove;default:return P.None}}doLayout(){this.width=9*this.scale,this.height=9*this.scale}paint(e,t,i){super.paint(e-2*this.scale,t+this.height,i)}}class qr extends ks{constructor(e,t,i){super(e,t),this._size=0,this._size=i}doLayout(){this.width=this._size+3*this.scale}paint(e,t,i){i.fillCircle(e+this.x,t+this.y,this._size)}}class Jr extends Ns{constructor(e,t,i){super(e,t,i?xs.GraceScale:1,P.NoteheadXOrnate),this._isGrace=i}doLayout(){this.width=9*(this._isGrace?xs.GraceScale:1)*this.scale,this.height=xs.NoteHeadHeight*this.scale}}class jr extends Ns{constructor(e,t,i,s){super(e,t,s?xs.GraceScale:1,jr.getSymbol(i)),this._isGrace=s}static getSymbol(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:return P.NoteheadDiamondWhiteWide;default:return P.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?xs.GraceScale:1)*this.scale,this.height=xs.NoteHeadHeight*this.scale}}class Qr extends ks{constructor(e,t,i){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=W.Up,this._startX=0,this._startY=0,this._endX=0,this._endY=0,this._tieHeight=0,this._shouldDraw=!1,this.startBeat=e,this.endBeat=t,this.forEnd=i}doLayout(){if(this.width=0,!this.endBeat)return void(this._shouldDraw=!1);let e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=e;let t=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar);this.endNoteRenderer=t,this._startX=0,this._endX=0,this._startY=0,this._endY=0,this.height=0,this._shouldDraw=!1,this.tieDirection=e?this.getBeamDirection(this.startBeat,e):this.getBeamDirection(this.endBeat,t),!this.forEnd&&e?(e!==t?(this._startX=e.x+this.getStartX(),this._startY=e.y+this.getStartY()+this.yOffset,t&&e.staff===t.staff?(this._endX=t.x+this.getEndX(),this._endY=t.y+this.getEndY()+this.yOffset):(this._endX=e.x+e.width,this._endY=this._startY)):(this._startX=e.x+this.getStartX(),this._endX=t.x+this.getEndX(),this._startY=e.y+this.getStartY()+this.yOffset,this._endY=t.y+this.getEndY()+this.yOffset),this._shouldDraw=!0):e&&e.staff===t.staff||(this._startX=t.x,this._endX=t.x+this.getEndX(),this._startY=t.y+this.getEndY()+this.yOffset,this._endY=this._startY,this._shouldDraw=!0),this._shouldDraw&&(this.y=Math.min(this._startY,this._endY),this.shouldDrawBendSlur()?this._tieHeight=0:(this._tieHeight=this.getTieHeight(this._startX,this._startY,this._endX,this._endY),this.height=Qr.calculateActualTieHeight(this.renderer.scale,this._startX,this._startY,this._endX,this._endY,this.tieDirection===W.Down,this._tieHeight,4).h),this.tieDirection===W.Up&&(this.y-=this.height))}paint(e,t,i){this._shouldDraw&&(this.shouldDrawBendSlur()?Qr.drawBendSlur(i,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===W.Down,this.scale):Qr.paintTie(i,this.scale,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===W.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,i,s){return 22}getBeamDirection(e,t){return W.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static calculateActualTieHeight(e,t,i,s,a,r,n,o){const h=Qr.computeBezierControlPoints(e,t,i,s,a,r,n,o);t=h[0],i=h[1];const l=h[2],d=h[3];s=h[6],a=h[7];const c=(t-l)/(t-2*l+s),u=Qr.calculateExtrema(t,i,l,d,s,a,c),p=u.length>0?Math.min(t,s,u[0]):Math.min(t,s),g=u.length>0?Math.max(t,s,u[0]):Math.max(t,s),f=(i-d)/(i-2*d+a),m=Qr.calculateExtrema(t,i,l,d,s,a,f),y=m.length>0?Math.min(i,a,m[1]):Math.min(i,a),b=m.length>0?Math.max(i,a,m[1]):Math.max(i,a),S=new Qe;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,i,s,a,r,n){if(n<=0||1<=n)return[];const o=e+(i-e)*n,h=t+(s-t)*n;return[o+(i+(a-i)*n-o)*n,h+(s+(r-s)*n-h)*n]}static computeBezierControlPoints(e,t,i,s,a,r,n,o){if(t===s&&i===a)return[];if(s<t){let e=t;t=s,s=e,e=i,i=a,a=e}n*=e,o*=e;let h=a-i,l=s-t,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(s+t)/2,u=(a+i)/2;return[t,i,c+n*h,u+n*l,c+(n-o)*h,u+(n-o)*l,s,a]}static paintTie(e,t,i,s,a,r,n=!1,o=22,h=4){const l=Qr.computeBezierControlPoints(t,i,s,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,i,s,a,r,n,o){let h=a-i,l=s-t,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(s+t)/2,u=(a+i)/2,p=Qr.BendSlurHeight*n;s-t<20&&(p/=2);let g=c+p*h,f=u+p*l;if(e.beginPath(),e.moveTo(t,i),e.lineTo(g,f),e.lineTo(s,a),e.stroke(),o){let t=e.measureText(o),i=r?0:-e.font.size;e.fillText(o,g-t/2,f+i)}}}Qr.BendSlurHeight=11;class $r extends ks{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=$r.Size*this.scale}paint(e,t,i){this._isOpen?Qr.paintTie(i,this.scale,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):Qr.paintTie(i,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}$r.Size=6;class Kr{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class Zr extends ks{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){let t=this.renderer,i=t.getNoteLine(e),s=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(v.ParenthesisOnTiedBends);this.addParenthesisOnLine(i,s)}addParenthesisOnLine(e,t){let i=new Kr(e,t);this._infos.push(i),t&&(this.isEmpty=!1)}isTiedBend(e){return!!e.isTieDestination&&(!!e.tieOrigin.hasBend||this.isTiedBend(e.tieOrigin))}doLayout(){let e=this.renderer;this._infos.sort(((e,t)=>e.line-t.line));let t=null,i=e.getScoreHeight(1);for(let s=0,a=this._infos.length;s<a;s++){let a;if(this._infos[s].isGhost)if(t){let a=e.getScoreY(this._infos[s].line)+i;t.height=a-t.y}else a=new $r(this._isOpen),a.renderer=this.renderer,a.y=e.getScoreY(this._infos[s].line)-i,a.height=2*i,a.doLayout(),this._glyphs.push(a),t=a;else t=null}this.width=this._glyphs.length>0?this._glyphs[0].width:0}paint(e,t,i){super.paint(e,t,i);for(let s of this._glyphs)s.paint(e+this.x,t+this.y,i)}}class en{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class tn extends ks{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new oi,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let i=new en(e,t);this._infos.push(i),(!this.minNote||this.minNote.line>i.line)&&(this.minNote=i),(!this.maxNote||this.maxNote.line<i.line)&&(this.maxNote=i)}get hasTopOverflow(){return!!this.minNote&&this.minNote.line<=0}get hasBottomOverflow(){return!!this.maxNote&&this.maxNote.line>8}doLayout(){this._infos.sort(((e,t)=>t.line-e.line));let e=0,t=!1,i=0,s=!1,a=this.direction,r=0;for(let n=0,o=this._infos.length;n<o;n++){let o=this._infos[n].glyph;o.renderer=this.renderer,o.doLayout();let h=!1;0===n?e=o.width:Math.abs(i-this._infos[n].line)<=1?t?t=!1:(h=!0,o.x=e,s=!0,t=!0):t=!1,a===W.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,i=this._infos[n].line,r=Math.max(r,o.x+o.width)}s?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===W.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,i){e+=this.x,t+=this.y;let s=this.renderer,a=3*this.scale,r=this.width-this.noteStartX+2*a;if(this.hasTopOverflow){let n=i.color;i.color=s.resources.staffLineColor;let o=-2;for(;o>=this.minNote.line;){let n=t+s.getScoreY(o);i.fillRect(e-a+this.noteStartX,n,r,this.scale),o-=2}i.color=n}if(this.hasBottomOverflow){let n=i.color;i.color=s.resources.staffLineColor;let o=10;for(;o<=this.maxNote.line;){let n=t+s.getScoreY(o);i.fillRect(e-a+this.noteStartX,n,r,this.scale),o+=2}i.color=n}let n=this._infos,o=e+this._noteHeadPadding;for(let e of n)e.glyph.renderer=this.renderer,e.glyph.paint(o,t,i)}}class sn extends Ns{constructor(e,t,i){super(e,t,1,sn.getSymbol(i))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case p.ThirtySecond:return P.Tremolo3;case p.Sixteenth:return P.Tremolo2;case p.Eighth:return P.Tremolo1;default:return P.None}}}class an extends tn{constructor(){super(),this._noteGlyphLookup=new Map,this._notes=[],this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){let i=this._noteGlyphLookup.get(e.id),s=this.x+i.x+this._noteHeadPadding;switch(t){case zs.Left:break;case zs.Center:s+=i.width/2;break;case zs.Right:s+=i.width}return s}return 0}getNoteY(e,t){if(this._noteGlyphLookup.has(e.id)){const i=this._noteGlyphLookup.get(e.id);let s=this.y+i.y;switch(t){case Ws.TopWithStem:s-=this.renderer.getStemSize(this.beamingHelper);break;case Ws.Top:s-=i.height/2;break;case Ws.Center:break;case Ws.Bottom:s+=i.height/2;break;case Ws.BottomWithStem:s+=this.renderer.getStemSize(this.beamingHelper)}return s}return 0}addNoteGlyph(e,t,i){super.add(e,i),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();let e=this.direction;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout();for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout();if(this.beat.isTremolo){let t=0,i=e===W.Up?this.minNote:this.maxNote,s=e===W.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case p.ThirtySecond:t=e===W.Up?-15:15;break;case p.Sixteenth:t=e===W.Up?-12:15;break;case p.Eighth:t=e===W.Up?-10:10;break;default:t=e===W.Up?-10:15}this._tremoloPicking=new sn(s,i.glyph.y+t*this.scale,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,i){for(let s of this._notes)if(this._noteGlyphLookup.has(s.id)){let a=this._noteGlyphLookup.get(s.id),r=new os;r.note=s,r.noteHeadBounds=new Qe,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=i+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,i){let s=this.renderer,a=0,r=0,n=1,o=-n;this.beamingHelper.direction===W.Up?(r=s.getScoreY(this.minNote.line),a=s.getScoreY(this.maxNote.line-2)):(r=s.getScoreY(this.maxNote.line-1),a=s.getScoreY(this.minNote.line+1),o*=-1,n*=-1);for(const s of this.aboveBeatEffects.values())a+=o*s.height,s.paint(e+this.x+2*this.scale,t+this.y+a,i);for(const s of this.belowBeatEffects.values())r+=n*s.height,s.paint(e+this.x+2*this.scale,t+this.y+r,i);super.paint(e,t,i),this._tremoloPicking&&this._tremoloPicking.paint(e,t,i)}}class rn extends Ns{constructor(e,t,i){super(e,t,1,rn.getSymbol(i)),this._duration=i}static getSymbol(e){switch(e){case p.QuadrupleWhole:return P.RestLonga;case p.DoubleWhole:return P.RestDoubleWhole;case p.Whole:return P.RestWhole;case p.Half:return P.RestHalf;case p.Quarter:return P.RestQuarter;case p.Eighth:return P.RestEighth;case p.Sixteenth:return P.RestSixteenth;case p.ThirtySecond:return P.RestThirtySecond;case p.SixtyFourth:return P.RestSixtyFourth;case p.OneHundredTwentyEighth:return P.RestOneHundredTwentyEighth;case p.TwoHundredFiftySixth:return P.RestTwoHundredFiftySixth;default:return P.None}}static getSize(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:return 9;case p.ThirtySecond:return 12;case p.SixtyFourth:return 14;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=rn.getSize(this._duration)*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class nn{constructor(){this.x=0,this.y=-3e3,this.width=0}}class on extends ca{constructor(){super(0,0)}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);this.glyphs.sort(((e,t)=>e.y<t.y?-1:e.y>t.y?1:0));let e=[];e.push(new nn);let t=21*this.scale;for(let i=0,s=this.glyphs.length;i<s;i++){let s=this.glyphs[i];s.renderer=this.renderer,s.doLayout();let a=0;for(;e[a].y>s.y;)a++,a===e.length&&e.push(new nn);s.x=a,e[a].y=s.y+t,e[a].width<s.width&&(e[a].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];const s=e[i.x];i.x=this.width-s.x}}}class hn extends tn{constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new on,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new Zr(!0),this._postNoteParenthesis=new Zr(!1))}get direction(){return W.Up}containsNoteValue(e){return this._noteValueLookup.has(e)}getNoteValueY(e){return this._noteValueLookup.has(e)?this.y+this._noteValueLookup.get(e).y:0}addGlyph(e,t=!1){let i=this.renderer,s=new xs(0,0,p.Quarter,!0),a=i.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),r=i.accidentalHelper.getNoteLineForValue(e,!1);if(s.y=i.getScoreY(r),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(r,!0),this._postNoteParenthesis.addParenthesisOnLine(r,!0)),a!==Vs.None){let e=new Gr(0,s.y,a,!0);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,s),this.add(s,r),this.isEmpty=!1}doLayout(){let e=0;this._showParenthesis&&(this._preNoteParenthesis.x=e,this._preNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.doLayout(),e+=this._preNoteParenthesis.width+hn.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+hn.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+hn.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+hn.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+hn.ElementPadding*this.scale)}paint(e,t,i){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,i),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,i),this._postNoteParenthesis.paint(e+this.x,t+this.y,i)),super.paint(e,t,i)}}hn.ElementPadding=2;class ln extends ks{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,i,s,a,r,n,o){Qr.drawBendSlur(e,t,i,s,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10*this.scale}getTieDirection(e,t){return t.getBeatDirection(e)===W.Up?W.Down:W.Up}}ln.EndPadding=8;class dn extends de{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class cn extends ks{constructor(){super(0,0),this._notes=[],this._renderPoints=new Map,this._preBendMinValue=-1,this._bendMiddleMinValue=-1,this._bendEndMinValue=-1,this._bendEndContinuedMinValue=-1,this._releaseMinValue=-1,this._releaseContinuedMinValue=-1,this._maxBendValue=-1}addBends(e){this._notes.push(e);let t=this.createRenderingPoints(e);this._renderPoints.set(e.id,t),(-1===this._maxBendValue||this._maxBendValue<e.maxBendPoint.value)&&(this._maxBendValue=e.maxBendPoint.value);let i=0;switch(e.bendType){case d.Bend:i=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||i<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=i):(-1===this._bendEndMinValue||i<this._bendEndMinValue)&&(this._bendEndMinValue=i);break;case d.Release:i=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i);break;case d.BendRelease:i=t[1].value,(-1===this._bendMiddleMinValue||i<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=i),i=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i);break;case d.Prebend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i);break;case d.PrebendBend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i),i=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||i<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=i):(-1===this._bendEndMinValue||i<this._bendEndMinValue)&&(this._bendEndMinValue=i);break;case d.PrebendRelease:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i),i=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i)}}doLayout(){super.doLayout();let e=this._maxBendValue*cn.BendValueHeight*this.scale;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let i=this._renderPoints.get(e.id);switch(e.bendType){case d.Bend:i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case d.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t);break;case d.BendRelease:i[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[2].lineValue=t);break;case d.Prebend:i[0].lineValue=this._preBendMinValue;break;case d.PrebendBend:i[0].lineValue=this._preBendMinValue,i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case d.PrebendRelease:i[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){let t=[];switch(e.bendType){case d.Custom:for(let i of e.bendPoints)t.push(new dn(i.offset,i.value));break;case d.BendRelease:t.push(new dn(0,e.bendPoints[0].value)),t.push(new dn(de.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new dn(de.MaxPosition,e.bendPoints[3].value));break;case d.Bend:case d.Hold:case d.Prebend:case d.PrebendBend:case d.PrebendRelease:case d.Release:t.push(new dn(0,e.bendPoints[0].value)),t.push(new dn(de.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,i){let s=i.color;this._notes.length>1&&(i.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,h=!1,c=null,u=!1,p=a.bendStyle===l.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!c||n.staff!==c.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes){u=!0;break}}g=o.beat,c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let f=0,m=0,y=t+n.y;f=e+n.x,r[0].value>0||a.isContinuedBend?f+=n.getBeatX(a.beat,Hs.MiddleNotes):f+=n.getNoteX(a,zs.Right),m=!g||g.isLastOfVoice&&!u?e+c.x+c.postBeatGlyphsStart:u||!g.nextBeat?e+c.x+c.getBeatX(g,Hs.MiddleNotes):a.bendType===d.Hold?e+c.x+c.getBeatX(g.nextBeat,Hs.OnNotes):e+c.x+c.getBeatX(g.nextBeat,Hs.PreNotes),h||(m-=cn.ArrowSize*this.scale);let b=(m-f)/de.MaxPosition;i.beginPath();for(let e=0,t=r.length-1;e<t;e++){let t=r[e],s=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new dn(0,0),t,f,y,b,p,i),a.bendType!==d.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,s,f,y,b,p,i)):a.isTieOrigin&&a.tieDestination.hasBend&&(s=new dn(de.MaxPosition,t.value),s.lineValue=t.lineValue,this.paintBend(a,t,s,f,y,b,p,i))}i.color=s}}paintBend(e,t,i,s,a,r,n,o){let h=this.renderer,l=this.renderer.resources,d=h.lineOffset/2,c=s+r*t.offset,u=cn.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?i.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,Ws.Top):p+=h.getNoteY(e,Ws.Center):p+=d;let g=s+r*i.offset,f=a-u*i.lineValue;0===i.lineValue?f+=h.getNoteY(e,Ws.Center):f+=d;let m=0,y=cn.ArrowSize*this.scale;if(i.value>t.value?(f+y>p&&(f=p-y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f+y),o.lineTo(g+.5*y,f+y),o.closePath(),o.fill(),m=y):i.value!==t.value&&(f<p&&(f=p+y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f-y),o.lineTo(g+.5*y,f-y),o.closePath(),o.fill(),m=-y),o.stroke(),t.value===i.value){if(t.lineValue>0){let e=g,t=cn.DashSize*this.scale,i=c+t;if((e-c)/(2*t)<1)o.moveTo(e,p),o.lineTo(c,p);else for(;e>i;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>c?(o.moveTo(c,p),o.bezierCurveTo((c+g)/2,p,g,p,g,f+m),o.stroke()):(o.moveTo(c,p),o.lineTo(g,f),o.stroke());if(n&&t.offset<i.offset){o.font=l.graceFont;let e=o.measureText(n),t=0,i=0;if(p>f){let s=Math.abs(p-f);t=s>1.3*o.font.size?p-s/2:p,i=(c+g-e)/2}else t=p,i=g-e;o.fillText(n,i,t)}if(0!==i.value&&t.value!==i.value){let e=i.value,s=i.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){let t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=cn.getFractionSign(e)),""!==r){f=a-u*i.value;let e=f;s||(e=p+1*Math.abs(f-p)/3),o.font=l.tablatureFont;let t=o.measureText(r),n=e-.5*l.tablatureFont.size-2*this.scale,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return e+"/ 4"}}}cn.ArrowSize=6,cn.DashSize=3,cn.BendValueHeight=6;class un extends ks{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===F.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case F.Dive:case F.Hold:case F.PrediveDive:case F.Predive:t.push(new de(0,e.whammyBarPoints[0].value)),t.push(new de(de.MaxPosition,e.whammyBarPoints[1].value));break;case F.Dip:t.push(new de(0,e.whammyBarPoints[0].value)),t.push(new de(de.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new de(de.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===e.NotationMode.SongBook&&this._beat.whammyBarType===F.Dip;let t=null,i=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!t||t.value>s.minWhammyPoint.value)&&(t=s.minWhammyPoint),(!i||i.value<s.maxWhammyPoint.value)&&(i=s.maxWhammyPoint),s=s.nextBeat;let a=i.value>0?Math.abs(this.getOffset(i.value)):0;(a>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(v.ZerosOnDiveWhammys))&&(a+=2*this.renderer.resources.tablatureFont.size);let r=t.value<0?Math.abs(this.getOffset(t.value)):0;this.renderer.registerOverflowTop(a+r),a>this.renderer.staff.getSharedLayoutData(un.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(un.TopOffsetSharedDataKey,a)}getOffset(e){if(0===e)return 0;let t=un.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*un.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(t,i,s){let a=this.renderer,r=this._beat.nextBeat,n=null,o=Hs.PreNotes;r&&(n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.voice.bar),n&&n.staff===a.staff&&(n===a||r.hasWhammyBar)?o=!r.hasWhammyBar||a.settings.notation.notationMode===e.NotationMode.SongBook&&r.whammyBarType===F.Dip?Hs.PreNotes:Hs.MiddleNotes:(r=null,n=null));let h=0,d=0;this._isSimpleDip?(h=t+a.x+a.getBeatX(this._beat,Hs.OnNotes)-2*this.scale,d=t+a.x+a.getBeatX(this._beat,Hs.PostNotes)+2*this.scale):(h=t+a.x+a.getBeatX(this._beat,Hs.MiddleNotes),d=n?t+n.x+n.getBeatX(r,o):t+a.x+a.width-2*this.scale);let c=s.textAlign;if(s.textAlign=E.Center,this._renderPoints.length>=2){let e=(d-h)/de.MaxPosition;s.beginPath();let t=i+this.renderer.staff.getSharedLayoutData(un.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===l.Gradual?"grad.":"";for(let i=0,r=this._renderPoints.length-1;i<r;i++){let n=this._renderPoints[i],o=this._renderPoints[i+1],l=i<r-2?this._renderPoints[i+2]:null,d=0===i;0!==i||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new de(0,0),n,o,h,t,e,s),d=!1),this.paintWhammy(d,n,o,l,h,t,e,s,a),a=""}s.stroke()}s.textAlign=c}paintWhammy(e,t,i,s,a,r,n,o,h){let l=a+n*t.offset,d=a+n*i.offset,c=r-this.getOffset(t.value),u=r-this.getOffset(i.value);if(t.offset===i.offset){let e=un.DashSize*this.scale;if(Math.abs(u-c)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(c,u),i=Math.min(c,u);for(;t>i;)o.moveTo(l,i),o.lineTo(l,i+e),i+=2*e}o.stroke()}else if(t.value===i.value){let e=un.DashSize*this.scale;if(Math.abs(d-l)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(l,d),i=Math.min(l,d);for(;t>i;)o.moveTo(t,c),o.lineTo(t-e,c),t-=2*e}o.stroke()}else o.moveTo(l,c),o.lineTo(d,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=c;e-=p.tablatureFont.size+2*this.scale,this.renderer.settings.notation.isNotationElementVisible(v.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(i.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(v.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==i.value){let e="";if(i.value<0&&(e+="-"),g>=4){let t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=cn.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(c,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===i.offset?Math.min(c,u):u,a-=p.tablatureFont.size+2*this.scale,s&&s.value>i.value&&(a-=2*this.scale));let r=d;o.fillText(e,r,a)}}}un.TopOffsetSharedDataKey="tab.whammy.topoffset",un.PerHalfSize=6,un.DashSize=3;class pn extends ln{constructor(e){super(0,0),this._beat=e}doLayout(){let t=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case F.None:case F.Custom:case F.Hold:return;case F.Dive:case F.PrediveDive:{let e=new hn(this._beat,!1);e.renderer=this.renderer;let t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let i of this._beat.notes)i.isTieOrigin||e.addGlyph(this.getBendNoteValue(i,t),t.value%2!=0);e.doLayout(),this.BendNoteHeads.push(e)}break;case F.Dip:if(t===e.NotationMode.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+pn.SimpleDipHeight*this.scale+pn.SimpleDipPadding*this.scale}else{let t=new hn(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[1];for(let i of this._beat.notes)t.addGlyph(this.getBendNoteValue(i,this._beat.whammyBarPoints[1]),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t);let i=new hn(this._beat,!1);if(i.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let t of this._beat.notes)i.addGlyph(this.getBendNoteValue(t,e),e.value%2!=0)}i.doLayout(),this.BendNoteHeads.push(i)}case F.Predive:}super.doLayout()}paint(t,i,s){let a=this._beat;switch(a.whammyBarType){case F.None:case F.Custom:return}let r=this.renderer.settings.notation.notationMode,n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),o=t+n.x+n.getBeatX(a,Hs.MiddleNotes),h=this.getTieDirection(a,n),d=1===this._beat.notes.length?h:W.Up,c=s.textAlign;for(let c=0;c<a.notes.length;c++){let u=a.notes[c],p=i+n.y;c>0&&c>=(this._beat.notes.length/2|0)&&(d=W.Down),d===W.Down?p+=n.getNoteY(u,Ws.Bottom):p+=n.getNoteY(u,Ws.Top);let g=t+n.x;a.isLastOfVoice?g+=n.width:g+=n.getBeatX(a,Hs.EndBeat),g-=8*this.scale;let f=a.whammyStyle===l.Gradual&&0===c?"grad.":"",m=null;u.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,u.tieDestination.beat.voice.bar),m&&m.staff===n.staff?g=t+m.x+m.getBeatX(u.tieDestination.beat,Hs.MiddleNotes):m=null);let y=xs.NoteHeadHeight*this.scale*xs.GraceScale*.5;d===W.Up&&(y=-y);let b=a.whammyBarPoints.length>0?this.getBendNoteValue(u,a.whammyBarPoints[a.whammyBarPoints.length-1]):0,S=0,_=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,_=!0):m&&(u.isTieOrigin&&u.tieDestination.beat.hasWhammyBar||u.beat.isContinuedWhammy)?(S=i+m.y+m.getNoteY(u.tieDestination,Ws.Top),_=!0,d===W.Down&&(S+=xs.NoteHeadHeight*this.scale)):u.isTieOrigin&&(S=m?i+m.y+m.getNoteY(u.tieDestination,Ws.Top):p,d===W.Down&&(S+=xs.NoteHeadHeight*this.scale)),a.whammyBarType){case F.Hold:u.isTieOrigin&&Qr.paintTie(s,this.scale,o,p,g,S,h===W.Down,22,4);break;case F.Dive:0===c&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(b)&&(S+=this.BendNoteHeads[0].y)),_?this.drawBendSlur(s,o,p,g,S,d===W.Down,this.scale,f):u.isTieOrigin&&Qr.paintTie(s,this.scale,o,p,g,S,h===W.Down,22,4);break;case F.Dip:if(r===e.NotationMode.SongBook){if(0===c){let e=t+n.x+n.getBeatX(this._beat,Hs.OnNotes)-2*this.scale,a=t+n.x+n.getBeatX(this._beat,Hs.PostNotes)+2*this.scale,r=(e+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,r,i+this.y);let h=i+this.y+s.font.size+2*this.scale,l=h+pn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(e,l),s.lineTo(r,h),s.lineTo(a,l)):(s.moveTo(e,h),s.lineTo(r,l),s.lineTo(a,h)),s.stroke()}u.isTieOrigin&&Qr.paintTie(s,this.scale,o,p,g,S,h===W.Down,22,4)}else{let e=(o+g)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s);let t=this.getBendNoteValue(u,a.whammyBarPoints[1]),r=this.BendNoteHeads[0].getNoteValueY(t)+y;this.drawBendSlur(s,o,p,e,r,d===W.Down,this.scale,f),this.BendNoteHeads[1].x=g-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=i+n.y,this.BendNoteHeads[1].paint(0,0,s),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(s,e,r,g,S,d===W.Down,this.scale,f)}break;case F.PrediveDive:case F.Predive:let l=t+n.x+n.getBeatX(u.beat,Hs.PreNotes);l+=n.getPreNotesGlyphForBeat(u.beat).prebendNoteHeadOffset;let m=i+n.y+n.getScoreY(n.accidentalHelper.getNoteLineForValue(u.displayValue-(u.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(s,l,m,o,p,d===W.Down,this.scale,f),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,o,p,g,S,d===W.Down,this.scale,f))}}s.textAlign=c}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}pn.SimpleDipHeight=2*un.PerHalfSize,pn.SimpleDipPadding=2;class gn extends ks{constructor(e,t,i){super(e,t),this.width=i}}class fn extends Ns{constructor(e,t,i,s,a){super(e,t,a?xs.GraceScale:1,i.getSymbol(s)),this._isGrace=a,this._articulation=i}paint(e,t,i){let s=this._isGrace?this.scale:0;i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this.symbol,!1),this._articulation.techniqueSymbol!==P.None&&this._articulation.techniqueSymbolPlacement===C.Middle&&i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?xs.GraceScale:1)*this.scale;switch(this.symbol){case P.NoteheadWhole:this.width=14;break;case P.NoteheadCircleX:case P.NoteheadDiamondWhite:this.width=9;break;case P.NoteheadHeavyXHat:case P.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?xs.GraceScale:1)*this.scale,this.height=xs.NoteHeadHeight*e}}class mn extends Ns{constructor(e,t){super(e,t,xs.GraceScale,P.ArticStaccatoAbove)}doLayout(){this.width=xs.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,i){super.paint(e+3*this.scale,t+5*this.scale,i)}}class yn extends Ns{constructor(e,t){super(e,t,.5,P.PictEdgeOfCymbal)}doLayout(){this.width=22*this.scale,this.height=15*this.scale}paint(e,t,i){super.paint(e-3*this.scale,t+this.height,i)}}class bn extends Ns{constructor(e,t){super(e,t,xs.GraceScale,P.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}}class Sn extends Ea{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.noteHeads=null,this.restGlyph=null}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,i){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,i+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph&&(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset)){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}paint(e,t,i){this._skipPaint||super.paint(e,t,i)}doLayout(){let e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===p.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const i=new rn(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addGlyph(i),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=ba.computeLineHeightsForRest(this.container.beat.duration);let s=i.y-e.getScoreHeight(t[0]),a=i.y+e.getScoreHeight(t[1]);this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,s,a)}else this.renderer.helpers.collisionHelper.registerRest(this.container.beat);if(this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,t),this.container.beat.dots>0){this.addGlyph(new gn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new ca(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new an;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let i=new Zr(!1);i.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),i.addParenthesis(e));if(this.addGlyph(t),i.isEmpty||(this.addGlyph(new gn(0,0,4*(this.container.beat.graceType!==f.None?xs.GraceScale:1)*this.scale)),this.addGlyph(i)),this.container.beat.hasWhammyBar){let e=new pn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new gn(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new ca(0,0);t.renderer=this.renderer;for(let i of this.container.beat.notes)this.createBeatDot(e.getNoteLine(i),t);this.addGlyph(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteHeads.x+this.noteHeads.width/2}createBeatDot(e,t){let i=this.renderer;t.addGlyph(new qr(0,i.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==f.None;if(e.beat.voice.bar.staff.isPercussion){const i=be.getArticulation(e);if(i)return new fn(0,0,i,e.beat.duration,t);ge.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new Jr(0,0,t):e.beat.graceType===f.BendGrace?new xs(0,0,p.Quarter,!0):e.harmonicType===y.Natural?new jr(0,0,e.beat.duration,t):new xs(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===f.BendGrace&&!e.hasBend)return;let t=this.renderer,i=this.createNoteHeadGlyph(e),s=t.getNoteLine(e);if(i.y=t.getScoreY(s),this.noteHeads.addNoteGlyph(i,e,s),e.harmonicType!==y.None&&e.harmonicType!==y.Natural){let a=e.displayValue+e.harmonicPitch;i=new jr(0,0,e.beat.duration,this.container.beat.graceType!==f.None),s=t.accidentalHelper.getNoteLineForValue(a,!1),i.y=t.getScoreY(s),this.noteHeads.addNoteGlyph(i,e,s)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new mn(0,0)),e.accentuated!==a.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new Yr(0,0,a.Normal)),e.accentuated!==a.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new Yr(0,0,a.Heavy)),e.isPercussion){const t=be.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==C.Middle){const e=t.techniqueSymbolPlacement===C.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case P.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new yn(0,0));break;case P.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new mn(0,0));break;case P.StringsUpBow:e.set("StringsUpBow",new rr(0,0,x.Up));break;case P.StringsDownBow:e.set("StringsDownBow",new rr(0,0,x.Down));break;case P.GuitarGolpe:e.set("GuitarGolpe",new bn(0,0))}}}}}class _n extends ks{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,i){let s=this.renderer,a=s.lineOffset,r=t+this.y+(s.getNoteY(this._beat.maxNote,Ws.Bottom)-a),n=t+this.y+s.getNoteY(this._beat.minNote,Ws.Top)+a,o=e+this.x+this.width/2,h=8*this.scale;if(this._beat.brushType!==c.None){let t=new lr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=-t.height/2;if(this._beat.brushType===c.ArpeggioUp){let a=r+h,l=n-h;t.width=Math.abs(l-a),i.beginRotate(e+this.x+5*this.scale,l,-90),t.paint(0,s,i),i.endRotate(),i.beginPath(),i.moveTo(o,n),i.lineTo(o+h/2,n-h),i.lineTo(o-h/2,n-h),i.closePath(),i.fill()}else if(this._beat.brushType===c.ArpeggioDown){let a=r+h,l=n;t.width=Math.abs(l-a),i.beginRotate(e+this.x+5*this.scale,a,90),t.paint(0,s,i),i.endRotate(),i.beginPath(),i.moveTo(o,r),i.lineTo(o+h/2,r+h),i.lineTo(o-h/2,r+h),i.closePath(),i.fill()}}}}class wn extends Pa{constructor(){super(),this._prebends=null,this.accidentals=null}get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new on;e.renderer=this.renderer;let t=new Zr(!0);t.renderer=this.renderer;const i=new hn(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(let s of this.container.beat.notes)if(s.isVisible){if(s.hasBend)switch(s.bendType){case d.PrebendBend:case d.Prebend:case d.PrebendRelease:i.addGlyph(s.displayValue-(s.bendPoints[0].value/2|0),!1)}else if(s.beat.hasWhammyBar)switch(s.beat.whammyBarType){case F.PrediveDive:case F.Predive:this._prebends.addGlyph(s.displayValue-(s.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(s,e),t.addParenthesis(s)}i.isEmpty||(this.addGlyph(i),this.addGlyph(new gn(0,0,4*(this.container.beat.graceType!==f.None?xs.GraceScale:1)*this.scale))),this.container.beat.brushType!==c.None&&(this.addGlyph(new _n(this.container.beat)),this.addGlyph(new gn(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new gn(0,0,4*(this.container.beat.graceType!==f.None?xs.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new gn(0,0,2*(this.container.beat.graceType!==f.None?xs.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new gn(0,0,2*(this.container.beat.graceType!==f.None?xs.GraceScale:1)*this.scale)))}super.doLayout()}createAccidentalGlyph(e,t){let i=this.renderer,s=i.accidentalHelper.applyAccidental(e),a=i.getNoteLine(e),r=this.container.beat.graceType!==f.None;if(s!==Vs.None){let e=new Gr(0,i.getScoreY(a),s,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==y.None&&e.harmonicType!==y.Natural){let n=e.displayValue+e.harmonicPitch;s=i.accidentalHelper.applyAccidentalForValue(e.beat,n,r,!1),a=i.accidentalHelper.getNoteLineForValue(n,!1);let o=new Gr(0,i.getScoreY(a),s,r);o.renderer=this.renderer,t.addGlyph(o)}}}class Bn extends Ns{constructor(e,t,i,s){super(e,t,s,Bn.getSymbol(i)),this._digit=0,this._scale=0,this._digit=i,this._scale=s}doLayout(){this.width=this.getDigitWidth(this._digit)*this.scale*this._scale}getDigitWidth(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return 14;case 1:return 10;default:return 0}}static getSymbol(e){switch(e){case 0:return P.TimeSig0;case 1:return P.TimeSig1;case 2:return P.TimeSig2;case 3:return P.TimeSig3;case 4:return P.TimeSig4;case 5:return P.TimeSig5;case 6:return P.TimeSig6;case 7:return P.TimeSig7;case 8:return P.TimeSig8;case 9:return P.TimeSig9;default:return P.None}}}class Tn extends ca{constructor(e,t,i,s=1){super(e,t),this._number=0,this._scale=0,this._number=i,this._scale=s}doLayout(){let e=this._number;for(;e>0;){let t=new Bn(0,0,e%10,this._scale);this.addGlyph(t),e=e/10|0}if(this.glyphs){this.glyphs.reverse();let e=0;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.x=e,i.y=0,i.renderer=this.renderer,i.doLayout(),e+=i.width}this.width=e}}}Tn.numberHeight=18;class kn extends ca{constructor(e,t,i,s,a){super(e,t),this._numerator=0,this._denominator=0,this._numerator=i,this._denominator=s,this._isCommon=a}doLayout(){if(this._isCommon&&2===this._numerator&&2===this._denominator){let e=new Ns(0,0,this.commonScale,P.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Ns(0,0,this.commonScale,P.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=Tn.numberHeight*this.scale;let t=new Tn(0,-e/2,this._numerator,this.numberScale),i=new Tn(0,e/2,this._denominator,this.numberScale);this.addGlyph(t),this.addGlyph(i),super.doLayout();for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=(this.width-t.width)/2}}}}class vn extends kn{get commonScale(){return 1}get numberScale(){return 1}}class Nn extends ln{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),!e.isTieOrigin)switch(e.bendType){case d.Bend:case d.PrebendRelease:case d.PrebendBend:{let t=this._endNoteGlyph;t||(t=new hn(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let i=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0)}break;case d.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new hn(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let i=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0)}break;case d.BendRelease:{let t=this._middleNoteGlyph;t||(t=new hn(e.beat,!1),this._middleNoteGlyph=t,t.renderer=this.renderer,this.BendNoteHeads.push(t));let i=e.bendPoints[1];t.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),i.value%2!=0);let s=this._endNoteGlyph;s||(s=new hn(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));let a=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,a),a.value%2!=0)}}}paint(e,t,i){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+s.x+s.getBeatX(this._beat,Hs.MiddleNotes),r=e+s.x;this._beat.isLastOfVoice?r+=s.postBeatGlyphsStart:r+=s.getBeatX(this._beat.nextBeat,Hs.PreNotes),r-=8*this.scale;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+s.y,this._middleNoteGlyph.paint(0,0,i)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+s.y,this._endNoteGlyph.paint(0,0,i)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));let o=this._beat.graceType===f.BendGrace?this._beat.nextBeat:this._beat,h=1===this._notes.length?this.getTieDirection(o,s):W.Up;for(let o=0;o<this._notes.length;o++){let c=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(h=W.Down);let u=t+s.y+s.getNoteY(c,Ws.Top),p=xs.NoteHeadHeight*this.scale*xs.GraceScale*.5;h===W.Down&&(u+=xs.NoteHeadHeight*this.scale);let g=c.bendStyle===l.Gradual?"grad.":"";if(c.isTieOrigin){let r=c.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===s.staff){let s=e+n.x+n.getBeatX(r.beat,Hs.MiddleNotes),o=t+n.y+n.getNoteY(r,Ws.Top);h===W.Down&&(o+=xs.NoteHeadHeight*this.scale),c.bendType===d.Hold||c.bendType===d.Prebend?Qr.paintTie(i,this.scale,a,u,s,o,h===W.Down,22,4):this.drawBendSlur(i,a,u,s,o,h===W.Down,this.scale,g)}else{let r=e+s.x+s.width,n=c.tieDestination.realValue;s.accidentalHelper.applyAccidentalForValue(c.beat,n,!1,!0);let o=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(n,!1));c.bendType===d.Hold||c.bendType===d.Prebend?Qr.paintTie(i,this.scale,a,u,r,o,h===W.Down,22,4):this.drawBendSlur(i,a,u,r,o,h===W.Down,this.scale,g)}switch(c.bendType){case d.Prebend:case d.PrebendBend:case d.PrebendRelease:let r=e+s.x+s.getBeatX(c.beat,Hs.PreNotes);r+=s.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let n=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,r,n,a,u,h===W.Down,this.scale)}}else{h===W.Up&&(p=-p);let o=0,l=0;switch(c.bendType){case d.Bend:o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===W.Down,this.scale,g);break;case d.BendRelease:let f=this.getBendNoteValue(c,c.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(i,a,u,n,m,h===W.Down,this.scale,g),o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,n,m,r,l,h===W.Down,this.scale,g);break;case d.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===W.Down,this.scale,g));break;case d.Prebend:case d.PrebendBend:case d.PrebendRelease:let y=e+s.x+s.getBeatX(c.beat,Hs.PreNotes);y+=s.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let b=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,y,b,a,u,h===W.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===W.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class xn extends Qr{constructor(e,t,i=!1){super(e,t,i)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?W.Up:t.getBeatDirection(e)===W.Up?W.Down:W.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===W.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,Ws.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,Ws.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===W.Up?e.getScoreY(9):e.getScoreY(0);const t=this.startNoteRenderer.getBeatDirection(this.startBeat),i=e.getBeatDirection(this.endBeat);return t!==i&&this.startBeat.graceType===f.None?i===this.tieDirection?this.tieDirection===W.Up?e.getNoteY(this.endBeat.maxNote,Ws.TopWithStem):e.getNoteY(this.endBeat.minNote,Ws.BottomWithStem):this.tieDirection===W.Up?e.getNoteY(this.endBeat.maxNote,Ws.BottomWithStem):e.getNoteY(this.endBeat.minNote,Ws.TopWithStem):this.tieDirection===W.Up?e.getNoteY(this.endBeat.maxNote,Ws.Top):e.getNoteY(this.endBeat.minNote,Ws.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,Hs.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>p.Whole&&e===this.tieDirection?Hs.Stem:Hs.MiddleNotes)}}class Pn extends ks{constructor(e,t,i,s){super(0,0),this._outType=t,this._inType=e,this._startNote=i,this._parent=s}doLayout(){this.width=0}paint(e,t,i){this.paintSlideIn(e,t,i),this.drawSlideOut(e,t,i)}paintSlideIn(e,t,i){let s=this.renderer,a=12*this.scale,r=e+s.x+s.getNoteX(this._startNote,zs.Left)-2*this.scale,n=t+s.y+s.getNoteY(this._startNote,Ws.Center),o=r-a,h=t+s.y;switch(this._inType){case S.IntoFromBelow:h+=s.getNoteY(this._startNote,Ws.Bottom);break;case S.IntoFromAbove:h+=s.getNoteY(this._startNote,Ws.Top);break;default:return}let l=this.getAccidentalsWidth(s,this._startNote.beat);o-=l,r-=l,this.paintSlideLine(i,!1,o,r,h,n)}getAccidentalsWidth(e,t){let i=e.getPreNotesGlyphForBeat(t);return i&&i.accidentals?i.accidentals.width:0}drawSlideOut(e,t,i){let s=this.renderer,a=12*this.scale,r=3*this.scale,n=1*this.scale,o=2*this.scale,h=0,l=0,d=0,c=0,u=!1;switch(this._outType){case _.Shift:case _.Legato:if(h=e+s.x+s.getBeatX(this._startNote.beat,Hs.PostNotes)+r,l=t+s.y+s.getNoteY(this._startNote,Ws.Center),this._startNote.slideTarget){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);i&&i.staff===s.staff?(d=e+i.x+i.getBeatX(this._startNote.slideTarget.beat,Hs.PreNotes)-n,c=t+i.y+i.getNoteY(this._startNote.slideTarget,Ws.Center)):(d=e+s.x+this._parent.x,c=l),this._startNote.slideTarget.realValue>this._startNote.realValue?(l+=o,c-=o):(l-=o,c+=o)}else d=e+s.x+this._parent.x,c=l;break;case _.OutUp:h=e+s.x+s.getNoteX(this._startNote,zs.Right),l=t+s.y+s.getNoteY(this._startNote,Ws.Center),d=h+a,c=t+s.y+s.getNoteY(this._startNote,Ws.Top);break;case _.OutDown:h=e+s.x+s.getNoteX(this._startNote,zs.Right),l=t+s.y+s.getNoteY(this._startNote,Ws.Center),d=h+a,c=t+s.y+s.getNoteY(this._startNote,Ws.Bottom);break;case _.PickSlideUp:h=e+s.x+s.getNoteX(this._startNote,zs.Right)+r,l=t+s.y+s.getNoteY(this._startNote,Ws.Center),c=t+s.y+s.getNoteY(this._startNote,Ws.Top),d=e+s.x+s.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(d=e+s.x+s.getBeatX(this._startNote.beat.nextBeat,Hs.PreNotes)),u=!0;break;case _.PickSlideDown:h=e+s.x+s.getNoteX(this._startNote,zs.Right)+r,l=t+s.y+s.getNoteY(this._startNote,Ws.Center),c=t+s.y+s.getNoteY(this._startNote,Ws.Bottom),d=e+s.x+s.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(d=e+s.x+s.getBeatX(this._startNote.beat.nextBeat,Hs.PreNotes)),u=!0;break;default:return}this.paintSlideLine(i,u,h,d,l,c)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new lr(0,0,w.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=s-i,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;let l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(i,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(i,a),e.lineTo(s,r),e.stroke()}}class En extends xn{constructor(e,t,i=!1){super(e.beat,t.beat,i),this._startNote=e,this._endNote=t}getTieHeight(e,t,i,s){return Math.log2(i-e+1)*this.renderer.settings.notation.slurHeight}getStartY(){return this.isStartCentered()?this.tieDirection===W.Up?this.startNoteRenderer.getNoteY(this._startNote,Ws.Top):this.startNoteRenderer.getNoteY(this._startNote,Ws.Bottom):this.startNoteRenderer.getNoteY(this._startNote,Ws.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===W.Up?this.endNoteRenderer.getNoteY(this._endNote,Ws.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,Ws.BottomWithStem):this.tieDirection===W.Up?this.endNoteRenderer.getNoteY(this._endNote,Ws.Top):this.endNoteRenderer.getNoteY(this._endNote,Ws.Bottom):this.endNoteRenderer.getNoteY(this._endNote,Ws.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===W.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===W.Down}isEndCentered(){return this._startNote.beat.graceType===f.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===W.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===W.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===f.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,Hs.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,zs.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,Hs.Stem):this.endNoteRenderer.getNoteX(this._endNote,zs.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,Hs.PreNotes)}}class Cn extends Qr{constructor(e,t,i=!1){super(e?e.beat:null,t?t.beat:null,i),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return t.getBeatDirection(e)===W.Up?W.Down:W.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===W.Up?this.startNoteRenderer.getNoteY(this.startNote,Ws.Top):this.startNoteRenderer.getNoteY(this.startNote,Ws.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===W.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===W.Up?e.getNoteY(this.endNote,Ws.Top):e.getNoteY(this.endNote,Ws.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,Hs.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,Hs.PreNotes)}}class Fn extends Es{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){if(this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new xn(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 xn(e,this.beat,!0))}this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==f.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Cn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Cn(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==S.None||e.slideOutType!==_.None){let t=new Pn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new En(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new En(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new En(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){let t=this.onNotes.beamingHelper.direction,i=t===W.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,s=t===W.Up?e.beat.minNote:e.beat.maxNote;const a=new En(i,s,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new Nn(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}}}}class Ln extends Ta{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new fa(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(Ta.LineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=e.tablatureFont.size/2+.2*e.tablatureFont.size;this.topPadding=t*this.scale,this.bottomPadding=t*this.scale,this.height=4*this.lineOffset+this.topPadding+this.bottomPadding,this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=4*this.lineOffset,t=(this.bar.staff.standardNotationLineCount-1)*this.lineOffset;this._firstLineY=(e-t)/2}doLayout(){if(this.updateFirstLineY(),super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){let e=this.getScoreY(-2),t=this.getScoreY(6),i=this.simpleWhammyOverflow;this.registerOverflowTop(i);let s=this.getScoreY(this.accidentalHelper.maxLine),a=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);a.direction===W.Up&&(s-=this.getStemSize(a),s-=a.fingeringCount*this.resources.graceFont.size,a.hasTuplet&&(s-=2*this.resources.effectFont.size)),a.hasTuplet&&(s-=1.5*this.resources.effectFont.size),s<e&&this.registerOverflowTop(Math.abs(s)+i);let r=this.getScoreY(this.accidentalHelper.minLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);n.direction===W.Down&&(r+=this.getStemSize(n),r+=n.fingeringCount*this.resources.graceFont.size),r>t&&this.registerOverflowBottom(Math.abs(r)-t)}}paint(e,t,i){super.paint(e,t,i),this.paintBeams(e,t,i),this.paintTuplets(e,t,i)}paintTuplets(e,t,i){for(let s of this.bar.voices)if(this.hasVoiceContainer(s)){let a=this.getVoiceContainer(s);for(let s of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,i,s)}}paintBeams(e,t,i){for(let s=0,a=this.helpers.beamHelpers.length;s<a;s++){let a=this.helpers.beamHelpers[s];for(let s=0,r=a.length;s<r;s++){let r=a[s];this.paintBeamHelper(e+this.beatGlyphsStart,t,i,r)}}}paintBeamHelper(e,t,i,s){i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isRestBeamHelper||(1===s.beats.length?this.paintFlag(e,t,i,s):this.paintBar(e,t,i,s))}paintTupletHelper(e,t,i,s){let a,r=this.resources,n=i.textAlign,o=i.textBaseline;i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.textAlign=E.Center,i.textBaseline=C.Middle;let h=s.beats[0].tupletNumerator,l=s.beats[0].tupletDenominator;a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l;let d=10*this.scale,c=5*this.scale;if(1!==s.beats.length&&s.isFull){let n=s.beats[0],o=s.beats[s.beats.length-1],h=null,l=null;for(let e=0;e<s.beats.length;e++)if(!s.beats[e].isRest){h=s.beats[e];break}for(let e=s.beats.length-1;e>=0;e--)if(!s.beats[e].isRest){l=s.beats[e];break}let u=!1;h||(h=n,u=!0),l||(l=o);let p=this.helpers.beamHelperLookup[s.voice.index].get(n.index),g=this.helpers.beamHelperLookup[s.voice.index].get(o.index),f=p.getBeatLineX(n),m=g.getBeatLineX(o),y=this.helpers.beamHelperLookup[s.voice.index].get(h.index),b=this.helpers.beamHelperLookup[s.voice.index].get(l.index),S=p.direction,_=this.calculateBeamYWithDirection(y,f,S),w=this.calculateBeamYWithDirection(b,m,S);u&&(_=Math.max(_,w),w=_),i.font=r.effectFont;let B=i.measureText(a),T=3*this.scale,k=(f+m)/2,v=k-B/2-T,N=k+B/2+T,x=(w-_)/(m-f),P=_-x*f,E=x*v+P,C=x*k+P,F=x*N+P;S===W.Down&&(d*=-1,c*=-1),i.beginPath(),i.moveTo(e+this.x+f,t+this.y+_-d|0),i.lineTo(e+this.x+f,t+this.y+_-d-c|0),i.lineTo(e+this.x+v,t+this.y+E-d-c|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+N,t+this.y+F-d-c|0),i.lineTo(e+this.x+m,t+this.y+w-d-c|0),i.lineTo(e+this.x+m,t+this.y+w-d|0),i.stroke(),i.fillText(a,e+this.x+k,t+this.y+C-d-c)}else for(let n=0,o=s.beats.length;n<o;n++){let o=s.beats[n],h=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(!h)continue;let l=h.direction,u=h.getBeatLineX(o),p=this.calculateBeamYWithDirection(h,u,l);l===W.Down&&(d*=-1,c*=-1),i.font=r.effectFont,i.fillText(a,e+this.x+u,t+this.y+p-d-c)}i.textAlign=n,i.textBaseline=o}getStemSize(e){let t=1===e.beats.length?this.getFlagStemSize(e.shortestDuration):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(t*=xs.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:t=6;break;case p.ThirtySecond:t=8;break;case p.SixtyFourth:case p.OneHundredTwentyEighth:t=9;break;case p.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:case p.ThirtySecond:case p.SixtyFourth:case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let i=super.getNoteY(e,t);if(isNaN(i)){const t=fa.computeLineWithoutAccidentals(this.bar,e);i=this.getScoreY(t)}return i}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,e.direction)}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let e=this.getScoreY(-2),t=this.getScoreY(6),i=this.helpers.collisionHelper.getBeatMinMaxY();i[0]<e&&this.registerOverflowTop(Math.abs(i[0])),i[1]>t&&this.registerOverflowBottom(Math.abs(i[1])-t)}return e}calculateBeamYWithDirection(e,t,i){let s=this.getStemSize(e);if(!e.drawingInfos.has(i)){let t=new ya;e.drawingInfos.set(i,t);const a=e.beats[0],r=e.beats[e.beats.length-1];let n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?i===W.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===W.Up?this.getScoreY(this.accidentalHelper.getMinLine(a))-s:this.getScoreY(this.accidentalHelper.getMaxLine(a))+s,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?i===W.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===W.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-s:this.getScoreY(this.accidentalHelper.getMaxLine(r))+s;let o=10*this.scale;if(i===W.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),i===W.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),i===W.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),i===W.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(i===W.Up){let i=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-s;const a=t.calcY(e.getBeatLineX(e.beatOfHighestNote))-i;a>0&&(t.startY-=a,t.endY-=a)}else{const i=this.getScoreY(this.accidentalHelper.getMaxLine(e.beatOfLowestNote))+s-t.calcY(e.getBeatLineX(e.beatOfLowestNote));i>0&&(t.startY+=i,t.endY+=i)}if(null!==e.minRestLine||null!==e.maxRestLine){const s=me.getIndex(e.shortestDuration)-2;let a=e.isGrace?xs.GraceScale:1,r=s*(Ta.BeamSpacing+Ta.BeamThickness)*this.scale*a;if(r+=Ta.BeamSpacing,i===W.Up&&null!==e.minRestLine){let i=this.getScoreY(e.minRestLine)-r;const s=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-i;s>0&&(t.startY-=s,t.endY-=s)}else if(i===W.Down&&null!==e.maxRestLine){const i=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));i>0&&(t.startY+=i,t.endY+=i)}}}}return e.drawingInfos.get(i).calcY(t)}paintBar(e,t,i,s){for(let a=0,r=s.beats.length;a<r;a++){let r=s.beats[a],n=r.graceType!==f.None?xs.GraceScale:1,o=s.getBeatLineX(r),h=s.direction,l=t+this.y;l+=h===W.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let d=t+this.y;d+=this.calculateBeamY(s,o),i.lineWidth=Ta.StemWidth*this.scale,i.beginPath(),i.moveTo(e+this.x+o,l),i.lineTo(e+this.x+o,d),i.stroke(),i.lineWidth=this.scale;let c=d;h===W.Down?c+=2*i.font.size:0!==a&&(c-=1.5*i.font.size),this.paintFingering(i,r,e+this.x+o,h,c);let u=6*this.scale*n,p=(Ta.BeamSpacing+Ta.BeamThickness)*this.scale*n,g=Ta.BeamThickness*this.scale*n,m=me.getIndex(r.duration)-2,y=t+this.y;h===W.Down&&(p=-p,g=-g);for(let t=0;t<m;t++){let n=0,h=0,l=0,d=0,c=y+t*p;if(a<s.beats.length-1){if(ba.isFullBarJoin(r,s.beats[a+1],t))n=o,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&ba.isFullBarJoin(s.beats[a-1],r,t))continue;n=o,h=n+u}l=c+this.calculateBeamY(s,n),d=c+this.calculateBeamY(s,h),Ln.paintSingleBar(i,e+this.x+n,l,e+this.x+h,d,g)}else a>0&&!ba.isFullBarJoin(r,s.beats[a-1],t)&&(n=o-u,h=o,l=c+this.calculateBeamY(s,n),d=c+this.calculateBeamY(s,h),Ln.paintSingleBar(i,e+this.x+n,l,e+this.x+h,d,g))}}}static paintSingleBar(e,t,i,s,a,r){e.beginPath(),e.moveTo(t,i),e.lineTo(s,a),e.lineTo(s,a+r),e.lineTo(t,i+r),e.closePath(),e.fill()}paintFlag(t,i,s,a){let r=a.beats[0];if(r.graceType===f.BendGrace||r.graceType!==f.None&&this.settings.notation.notationMode===e.NotationMode.SongBook)return;let n=r.graceType!==f.None,o=n?xs.GraceScale:1,h=this.getFlagStemSize(a.shortestDuration),l=a.getBeatLineX(r),d=a.direction,c=this.getScoreY(this.accidentalHelper.getMinLine(r)),u=this.getScoreY(this.accidentalHelper.getMaxLine(r)),p=0,g=0;if(d===W.Down?(u+=h*o,p=u,g=i+this.y+u):(c-=h*o,p=c,g=i+this.y+c),this.paintFingering(s,r,t+this.x+l,d,g),a.hasLine){if(s.lineWidth=Ta.StemWidth*this.scale,s.beginPath(),s.moveTo(t+this.x+l,i+this.y+c),s.lineTo(t+this.x+l,i+this.y+u),s.stroke(),s.lineWidth=this.scale,r.graceType===f.BeforeBeat){let e=15*this.scale,a=12*this.scale;s.beginPath(),d===W.Down?(s.moveTo(t+this.x+l-a/2,i+this.y+u-e),s.lineTo(t+this.x+l+a/2,i+this.y+u)):(s.moveTo(t+this.x+l-a/2,i+this.y+c+e),s.lineTo(t+this.x+l+a/2,i+this.y+c)),s.stroke()}if(a.hasFlag){let e=new Ps(l-this.scale/2,p,r.duration,d,n);e.renderer=this,e.doLayout(),e.paint(t+this.x,i+this.y,s)}}}paintFingering(t,i,s,a,r){let n=this.settings;if(n.notation.fingeringMode!==e.FingeringMode.ScoreDefault&&n.notation.fingeringMode!==e.FingeringMode.ScoreForcePiano)return;a===W.Up?s-=10*this.scale:s+=3*this.scale;let o=i.notes.slice(0);o.sort(((e,t)=>e.realValue-t.realValue));for(let e=0;e<o.length;e++){let a=o[e],h=null;a.leftHandFinger!==m.Unknown?h=me.fingerToString(n,i,a.leftHandFinger,!0):a.rightHandFinger!==m.Unknown&&(h=me.fingerToString(n,i,a.rightHandFinger,!1)),h&&(t.fillText(h,s,r),r-=0|t.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Xr(0,0,1.5,3)),this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case n.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case n.F4:e=2;break;case n.C3:e=4;break;case n.C4:e=2;break;case n.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new Wr(0,this.getScoreY(e)+.5*Ta.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==M.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Hr(0,this.getScoreHeight(-.5),this.bar.index+1))}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(t)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new zr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Ur(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Vr(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new gn(0,0,2*this.scale)),this._startSpacing=!0)}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,i=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case n.Neutral:e=0;break;case n.G2:e=1;break;case n.F4:e=3;break;case n.C3:e=2;break;case n.C4:e=0}let s=new Map,a=[];if(me.keySignatureIsSharp(t))for(let i=0;i<Math.abs(t);i++){let t=Ln.SharpKsSteps[i]+e;a.push(new Gr(0,this.getScoreY(t),Vs.Sharp,!1)),s.set(t,!0)}else for(let i=0;i<Math.abs(t);i++){let t=Ln.FlatKsSteps[i]+e;a.push(new Gr(0,this.getScoreY(t),Vs.Flat,!1)),s.set(t,!0)}let r=Math.abs(i),o=me.keySignatureIsSharp(i)?Ln.SharpKsSteps:Ln.FlatKsSteps;for(let t=0;t<r;t++){let i=o[t]+e;s.has(i)||this.addPreBeatGlyph(new Gr(0,this.getScoreY(o[t]+e),Vs.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new gn(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new vn(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new Fn(i,this.getVoiceContainer(e));s.preNotes=new wn,s.onNotes=new Sn,this.addBeatGlyph(s)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}getScoreY(e){return this._firstLineY+this.lineOffset+this.getScoreHeight(e)}getScoreHeight(e){return this.lineOffset/2*e}paintBackground(e,t,i){super.paintBackground(e,t,i);let s=this.resources;i.color=s.staffLineColor;for(let s=0;s<this.bar.staff.standardNotationLineCount;s++){const a=t+this.y+this.getScoreY(2*s);i.fillRect(e+this.x,0|a,this.width,this.scale*Ta.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,Ws.Center),i=this.getNoteY(e.lowestNoteInHelper,Ws.Center),s=this.getStemSize(e);e.hasTuplet&&(s+=2*this.resources.effectFont.size),e.direction==W.Up?t-=s:i+=s;for(const s of e.beats)this.helpers.collisionHelper.reserveBeatSlot(s,t,i)}}}Ln.StaffId="score",Ln.SharpKsSteps=[-1,2,-2,1,4,0,3],Ln.FlatKsSteps=[3,0,4,1,5,2,6];class Mn extends da{get staffId(){return Ln.StaffId}create(e,t){return new Ln(e,t)}constructor(){super()}}class Dn extends ks{constructor(e,t,i,s){super(0,0),this._inType=e,this._outType=t,this._startNote=i,this._parent=s}doLayout(){this.width=0}paint(e,t,i){this.paintSlideIn(e,t,i),this.paintSlideOut(e,t,i)}paintSlideIn(e,t,i){let s=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0;switch(this._inType){case S.IntoFromBelow:h=e+s.x+s.getNoteX(this._startNote,zs.Left),l=t+s.y+s.getNoteY(this._startNote,Ws.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,Ws.Center)+r;break;case S.IntoFromAbove:h=e+s.x+s.getNoteX(this._startNote,zs.Left),l=t+s.y+s.getNoteY(this._startNote,Ws.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,Ws.Center)-r;break;default:return}this.paintSlideLine(i,!1,n,h,o,l)}paintSlideOut(e,t,i){let s=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0,d=!1;const c=2*this.scale;switch(this._outType){case _.Shift:case _.Legato:if(n=e+s.x+s.getBeatX(this._startNote.beat,Hs.PostNotes),o=t+s.y+s.getNoteY(this._startNote,Ws.Center),this._startNote.slideTarget){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);i&&i.staff===s.staff?(h=e+i.x+i.getBeatX(this._startNote.slideTarget.beat,Hs.OnNotes)-c,l=t+i.y+i.getNoteY(this._startNote.slideTarget,Ws.Center)):(h=e+s.x+this._parent.x,l=o),this._startNote.slideTarget.fret>this._startNote.fret?(o+=r,l-=r):(o-=r,l+=r)}else h=e+s.x+this._parent.x,l=o;break;case _.OutUp:n=e+s.x+s.getNoteX(this._startNote,zs.Right),o=t+s.y+s.getNoteY(this._startNote,Ws.Center),h=n+a-c,l=t+s.y+s.getNoteY(this._startNote,Ws.Center)-r;break;case _.OutDown:n=e+s.x+s.getNoteX(this._startNote,zs.Right),o=t+s.y+s.getNoteY(this._startNote,Ws.Center),h=n+a-c,l=t+s.y+s.getNoteY(this._startNote,Ws.Center)+r;break;case _.PickSlideDown:n=e+s.x+s.getNoteX(this._startNote,zs.Right),o=t+s.y+s.getNoteY(this._startNote,Ws.Center),h=e+s.x+s.getBeatX(this._startNote.beat,Hs.EndBeat),l=o+3*r,d=!0;break;case _.PickSlideUp:n=e+s.x+s.getNoteX(this._startNote,zs.Right),o=t+s.y+s.getNoteY(this._startNote,Ws.Center),h=e+s.x+s.getBeatX(this._startNote.beat,Hs.EndBeat),l=o-3*r,d=!0;break;default:return}this.paintSlideLine(i,d,n,h,o,l)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new lr(0,0,w.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=s-i,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;let l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(i,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(i,a),e.lineTo(s,r),e.stroke()}}class In extends Qr{constructor(e,t,i=!1){super(e.beat,t.beat,i),this.startNote=e,this.endNote=t}getTieHeight(e,t,i,s){return this.startNote===this.endNote?15:super.getTieHeight(e,t,i,s)}getBeamDirection(e,t){return this.startNote===this.endNote?W.Up:In.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?W.Up:W.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,Ws.Center):this.tieDirection===W.Up?this.startNoteRenderer.getNoteY(this.startNote,Ws.Top):this.startNoteRenderer.getNoteY(this.startNote,Ws.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,zs.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,zs.Left):this.endNoteRenderer.getNoteX(this.endNote,zs.Center)}}class Rn extends In{constructor(e,t,i,s=!1){super(e,t,s),this._direction=In.getBeamDirectionForNote(e),this._forSlide=i}getTieHeight(e,t,i,s){return Math.log(i-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,i,s){if(this._forSlide!==i)return!1;if(this.forEnd!==s)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;if(this._direction!==In.getBeamDirectionForNote(e))return!1;switch(this._direction){case W.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 W.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,i){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,s),r="tab.slur."+this.startNote.beat.id+"."+this.endNote.beat.id+"."+a,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,i))}}class An extends Es{constructor(e,t){super(e,t),this._bend=null,this._effectSlurs=[]}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;let t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){let t=new In(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new In(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new In(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(let i of this._effectSlurs)if(i.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){let t=new Rn(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(let i of this._effectSlurs)if(i.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){let t=new Rn(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==S.None||e.slideOutType!==_.None){let t=new Dn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new cn;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class On extends ks{constructor(e,t,i){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=i}doLayout(){let t=this._note,i=t.fret-t.beat.voice.bar.staff.transpositionPitch;if(t.harmonicType===y.Natural&&0!==t.harmonicValue&&(i=t.harmonicValue-t.beat.voice.bar.staff.transpositionPitch),t.isTieDestination)0===t.beat.index&&this.renderer.settings.notation.notationMode==e.NotationMode.GuitarPro||(t.bendType===d.Bend||t.bendType===d.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(v.TabNotesOnTiedBends)?this._noteString="("+(t.tieOrigin.fret-t.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=t.isDead?"x":i.toString(),t.isGhost)this._noteString="("+this._noteString+")";else if(t.harmonicType===y.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(t.isTrill)this._trillNoteString="("+(t.trillFret-t.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(me.isAlmostEqualTo(t.harmonicValue,0))this._trillNoteString="";else switch(t.harmonicType){case y.Artificial:case y.Pinch:case y.Tap:case y.Semi:case y.Feedback:let e=(i+t.harmonicValue).toString(),s=e.indexOf(String.fromCharCode(46));s>=0&&(e=e.substr(0,s+2)),this._trillNoteString="<"+e+">";break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString)*this.scale,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size,!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3*this.scale+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString),this.width+=this._trillNoteStringWidth)}}paint(e,t,i){if(this.isEmpty)return;let s=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-s)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,i.fillText(this._trillNoteString,a+this.noteStringWidth+3*this.scale,t+this.y),this.renderer.scoreRenderer.canvas.font=r,i.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,i){let s=new os;s.note=this._note,s.noteHeadBounds=new Qe,s.noteHeadBounds.x=t+this.x,s.noteHeadBounds.y=i+this.y-this.height/2,s.noteHeadBounds.w=this.width,s.noteHeadBounds.h=this.height,e.addNote(s)}}class Gn extends ks{constructor(e,t,i){super(e,t),this._notes=[],this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=i}buildBoundingsLookup(e,t,i){for(const s of this._notes)s.buildBoundingsLookup(e,t+this.x,i+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){let i=this.notesPerString.get(e.string),s=this.x+i.x;switch(t){case zs.Left:break;case zs.Center:s+=i.noteStringWidth/2;break;case zs.Right:s+=i.width}return s}return 0}getNoteY(e,t){if(this.notesPerString.has(e.string)){const i=this.notesPerString.get(e.string);let s=this.y+i.y;switch(t){case Ws.Top:case Ws.TopWithStem:s-=i.height/2+2*this.scale;break;case Ws.Center:break;case Ws.Bottom:case Ws.BottomWithStem:s+=i.height/2}return s}return 0}doLayout(){let e=0,t=0;for(let i=0,s=this._notes.length;i<s;i++){let s=this._notes[i];s.renderer=this.renderer,s.doLayout(),s.width>e&&(e=s.width),s.noteStringWidth>t&&(t=s.noteStringWidth)}this.noteStringWidth=t;let i=this.renderer.resources.tablatureFont.size,s=this.getNoteY(this.minStringNote,Ws.Center)+i/2,a=7*this.scale;for(const e of this.beatEffects.values())e.y+=s,e.x+=this.width/2,e.renderer=this.renderer,s+=a,e.doLayout();this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,i){e+=this.x,t+=this.y;let s=this.renderer.resources,a=i.textBaseline;i.textBaseline=C.Middle,i.font=this._isGrace?s.graceFont:s.tablatureFont;let r=this._notes,n=this.width;for(let s of r)s.renderer=this.renderer,s.width=n,s.paint(e,t,i);i.textBaseline=a;for(const s of this.beatEffects.values())s.paint(e,t,i)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class Hn extends Ns{constructor(e,t,i,s){super(e,t,1,rn.getSymbol(s)),this._isVisibleRest=i,this._duration=s}doLayout(){this._isVisibleRest?this.width=rn.getSize(this._duration)*this.scale:this.width=10*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,i){this._isVisibleRest&&super.paint(e,t,i)}}class Vn extends Ea{constructor(){super(...arguments),this.noteNumbers=null,this.restGlyph=null}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,i){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,i+this.y)}doLayout(){let t=this.renderer;if(this.container.beat.isRest){let e=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),i=t.getTabY(e);const s=new Hn(0,i,t.showRests,this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addGlyph(s),this.container.beat.dots>0&&t.showRests){this.addGlyph(new gn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new qr(0,i,1.5*this.scale))}}else{let i=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==f.None;const s=new Gn(0,0,i);this.noteNumbers=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(s),this.container.beat.hasWhammyBar){let e=new un(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case p.ThirtySecond:e=10;break;case p.Sixteenth:e=5;break;case p.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new sn(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&t.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden){this.addGlyph(new gn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new qr(0,t.lineOffset*t.bar.staff.tuning.length+t.settings.notation.rhythmHeight*t.scale,1.5*this.scale))}}if(!this.glyphs)return;let i=0;for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=i,t.renderer=this.renderer,t.doLayout(),i+=t.width}this.width=i,this.computedWidth=i,this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2}updateBeamingHelper(){this.container.beat.isRest?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.noteNumbers.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,i=new On(0,0,e),s=e.beat.voice.bar.staff.tuning.length-e.string;i.y=t.getTabY(s),i.renderer=this.renderer,i.doLayout(),this.noteNumbers.addNoteGlyph(i,e);let a=i.y-i.height/2,r=a+i.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class Wn extends ks{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,i){let s=this.renderer,a=t+this.x+s.getNoteY(this._beat.maxStringNote,Ws.Top),r=t+this.y+s.getNoteY(this._beat.minStringNote,Ws.Bottom),n=e+this.x+this.width/2|0,o=8*this.scale;if(this._beat.brushType!==c.None){if(this._beat.brushType===c.BrushUp||this._beat.brushType===c.BrushDown)i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke();else if(this._beat.brushType===c.ArpeggioUp){let t=new lr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=a,n=r-o;t.width=Math.abs(n-s),i.beginRotate(e+this.x+4*this.scale,n,-90),t.paint(0,-t.height/2,i),i.endRotate()}else if(this._beat.brushType===c.ArpeggioDown){let t=new lr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=a+o,n=r;t.width=Math.abs(n-s),i.beginRotate(e+this.x+4*this.scale,s,90),t.paint(0,-t.height/2,i),i.endRotate()}this._beat.brushType===c.BrushUp||this._beat.brushType===c.ArpeggioUp?(i.beginPath(),i.moveTo(n,r),i.lineTo(n+o/2,r-o),i.lineTo(n-o/2,r-o),i.closePath(),i.fill()):(i.beginPath(),i.moveTo(n,a),i.lineTo(n+o/2,a+o),i.lineTo(n-o/2,a+o),i.closePath(),i.fill())}}}class zn extends Pa{doLayout(){this.container.beat.brushType===c.None||this.container.beat.isRest||(this.addGlyph(new Wn(this.container.beat)),this.addGlyph(new gn(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class Un extends ks{constructor(e,t){super(e,t)}doLayout(){this.width=28*this.scale}paint(e,t,i){let s=this.renderer.bar.staff.tuning.length,a=s<=4?P.FourStringTabClef:P.SixStringTabClef,r=s<=4?s/4.5:s/6.5;i.fillMusicFontSymbol(e+this.x+5*this.scale,t+this.y,r*this.scale,a,!1)}}class Xn extends kn{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?xs.GraceScale:1}}class Yn extends Ta{constructor(e,t){super(e,t),this._firstLineY=0,this._tupletSize=0,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._startSpacing=!1}get lineOffset(){return(Yn.TabLineSpacing+1)*this.scale}updateSizes(){let t=this.resources,i=(t.tablatureFont.size/2+.2*t.tablatureFont.size)*this.scale;this.topPadding=i,this.bottomPadding=i,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*i,this.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden&&(this.height+=this.settings.notation.rhythmHeight*this.settings.display.scale,this.bottomPadding+=this.settings.notation.rhythmHeight*this.settings.display.scale),this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=this.resources;this._firstLineY=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale}doLayout(){if(this.updateFirstLineY(),super.doLayout(),this.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden){let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&(this._tupletSize=.8*this.resources.effectFont.size,this.registerOverflowBottom(this._tupletSize))}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Xr(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Un(5*this.scale,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Hr(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new gn(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new gn(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new Xn(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new An(i,this.getVoiceContainer(e));s.preNotes=new zn,s.onNotes=new Vn,this.addBeatGlyph(s)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new zr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Ur(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Vr(0,0))}getTabY(e){return this._firstLineY+this.getTabHeight(e)}getTabHeight(e){return this.lineOffset*e}get middleYPosition(){return this.getTabY(this.bar.staff.tuning.length-1)}paintBackground(e,t,i){super.paintBackground(e,t,i);let s=this.resources;i.color=s.staffLineColor;let a=this.scale,r=[];for(let e=0,t=this.bar.staff.tuning.length;e<t;e++)r.push([]);for(let e of this.bar.voices)if(this.hasVoiceContainer(e)){let t=this.getVoiceContainer(e);for(let e of t.beatGlyphs){let i=e.onNotes,s=i.noteNumbers;if(s)for(const[n,o]of s.notesPerString)o.isEmpty||r[this.bar.staff.tuning.length-n].push(new Float32Array([t.x+e.x+i.x+s.x,s.width+a]))}}for(let e of r)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let s=0,a=this.bar.staff.tuning.length;s<a;s++){const a=this.getTabY(s);let n=0;for(let o of r[s])i.fillRect(e+this.x+n,t+this.y+a|0,o[0]-n,this.scale*Ta.StaffLineThickness),n=o[0]+o[1];i.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*Ta.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}paint(t,i,s){super.paint(t,i,s),this.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden&&(this.paintBeams(t,i,s),this.paintTuplets(t,i,s))}paintBeams(e,t,i){for(let s=0,a=this.helpers.beamHelpers.length;s<a;s++){let a=this.helpers.beamHelpers[s];for(let s=0,r=a.length;s<r;s++){let r=a[s];this.paintBeamHelper(e+this.beatGlyphsStart,t,i,r)}}}paintTuplets(e,t,i){for(let s of this.bar.voices)if(this.hasVoiceContainer(s)){let a=this.getVoiceContainer(s);for(let s of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,i,s)}}paintBeamHelper(t,i,s,a){s.color=0===a.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,a.isRestBeamHelper||(1===a.beats.length||this.settings.notation.rhythmMode===e.TabRhythmMode.ShowWithBeams?this.paintFooter(t,i,s,a):this.paintBar(t,i,s,a))}paintBar(e,t,i,s){for(let a=0,r=s.beats.length;a<r;a++){let r=s.beats[a];if(s.hasBeatLineX(r)){let n=s.getBeatLineX(r),o=t+this.y,h=t+this.y+this.height-this._tupletSize,l=this.getOnNotesGlyphForBeat(r);l.noteNumbers&&r.duration!==p.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,Ws.Bottom)+this.lineOffset/2:o+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(r,t+this.y,e+this.x+n,o,h,i);let d=6*this.scale,c=-6*this.scale,u=3*this.scale,g=me.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,p=0,g=f+t*c;if(1===s.beats.length)o=n,h=n+d,l=g,p=g,Yn.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u);else if(a<s.beats.length-1){if(ba.isFullBarJoin(r,s.beats[a+1],t))o=n,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&ba.isFullBarJoin(s.beats[a-1],r,t))continue;o=n,h=o+d}l=g,p=g,Yn.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u)}else a>0&&!ba.isFullBarJoin(r,s.beats[a-1],t)&&(o=n-d,h=n,l=g,p=g,Yn.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u))}}}}paintTupletHelper(e,t,i,s){let a,r=this.resources,n=i.textAlign,o=i.textBaseline;i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.textAlign=E.Center,i.textBaseline=C.Middle;let h=s.beats[0].tupletNumerator,l=s.beats[0].tupletDenominator;if(a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l,1!==s.beats.length&&s.isFull){let n=s.beats[0],o=s.beats[s.beats.length-1],h=this.helpers.beamHelperLookup[s.voice.index].get(n.index),l=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(h&&l){let s=h.getBeatLineX(n),d=l.getBeatLineX(o);i.font=r.effectFont;let c=i.measureText(a),u=3*this.scale,p=(s+d)/2,g=p-c/2-u,f=p+c/2+u,m=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size,y=.25*-r.effectFont.size,b=-5*this.scale;i.beginPath(),i.moveTo(e+this.x+s,m-y|0),i.lineTo(e+this.x+s,m-y-b|0),i.lineTo(e+this.x+g,m-y-b|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+f,m-y-b|0),i.lineTo(e+this.x+d,m-y-b|0),i.lineTo(e+this.x+d,m-y|0),i.stroke(),i.fillText(a,e+this.x+p,m-y-b)}}else for(let n=0,o=s.beats.length;n<o;n++){let o=s.beats[n],h=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(!h)continue;let l=h.getBeatLineX(o),d=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size;i.font=r.effectFont,i.fillText(a,e+this.x+l,d)}i.textAlign=n,i.textBaseline=o}static paintSingleBar(e,t,i,s,a,r){e.beginPath(),e.moveTo(t,i),e.lineTo(s,a),e.lineTo(s,a-r),e.lineTo(t,i-r),e.closePath(),e.fill()}paintBeamingStem(e,t,i,s,a,r){r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>s;){r.moveTo(i,o);let e=s;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(i,e);break}{const s=n.pop();e=t+s.bottomY,r.lineTo(i,e),o=t+s.topY}}r.stroke()}paintFooter(e,t,i,s){for(let a of s.beats){if(a.graceType!==f.None||a.duration===p.Whole||a.duration===p.DoubleWhole||a.duration===p.QuadrupleWhole)return;let r=s.getBeatLineX(a),n=t+this.y,o=t+this.y+this.height-this._tupletSize,h=this.getOnNotesGlyphForBeat(a);if(h.noteNumbers&&a.duration!==p.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,Ws.Bottom):n+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(a,t+this.y,e+this.x+r,n,o,i),a.duration>p.Quarter){let t=new Ps(0,0,a.duration,W.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,i)}}}}Yn.StaffId="tab",Yn.TabLineSpacing=10;class qn extends da{constructor(e,t,i){super(),this._showTimeSignature=e,this._showRests=t,this._showTiedNotes=i,this.hideOnPercussionTrack=!0}get staffId(){return Yn.StaffId}canCreate(e,t){return t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let i=new Yn(e,t);return i.showRests=this._showRests,i.showTimeSignature=this._showTimeSignature,i.showTiedNotes=this._showTiedNotes,i}}class Jn extends vs{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+Jn.Padding*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=E.Center,i.fillText("T",e+this.x,t+this.y+i.font.size/2),i.textAlign=a,i.strokeCircle(e+this.x,t+this.y+i.font.size/2+(Jn.Padding-1)*this.scale,i.font.size/1.6)}}Jn.Padding=4;class jn extends Ja{get notationElement(){return v.EffectTap}get sizingMode(){return Us.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new Jn}}class Qn{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"}(Ys||(Ys={}));class $n extends Qn{constructor(){super(...arguments),this.align=E.Left,this.frame=Ys.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class Kn extends Qn{constructor(){super(...arguments),this.chord=new Pe}}class Zn extends Qn{}class eo extends Qn{}class to extends Qn{constructor(){super(...arguments),this.number=0}}class io extends Qn{constructor(){super(...arguments),this.decrescendo=!1}}class so extends Qn{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class ao extends Qn{constructor(){super(...arguments),this.octave=1}}class ro extends Qn{}class no{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class oo{constructor(){this.from=0,this.to=0,this.curly=!1}}class ho{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class lo{constructor(){this._trackChannel=0,this._beamingMode=L.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new Ce,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;let i=new st;try{i.parse(e)}catch(e){throw new ne("Could not parse XML",e)}this.parseDom(i),this.consolidate(),this.score.finish(t)}consolidate(){let e=this.score.tempo;for(const t of this.score.tracks){const i=this._voiceCounts.get(t.index);for(const s of t.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const t of s.bars){for(;t.voices.length<i;)t.addVoice(new Ve);for(const e of t.voices)if(0===e.beats.length){const t=new xe;t.isEmpty=!0,e.addBeat(t)}const s=t.masterBar;s.tempoAutomation&&(s.tempoAutomation.value!==e?e=s.tempoAutomation.value:s.tempoAutomation=null)}}}lo.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),lo.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?u.Decrescendo:u.Crescendo}))}static applyEffectRange(e,t){for(const[i,s]of e){const e=s.noteRange;let a=i;for(let i=0;i<e;i++)if(t(s,a),a.index+1<a.voice.beats.length)a=a.voice.beats[a.index+1];else{if(!(a.voice.bar.index+1<a.voice.bar.staff.bars.length))break;a=a.voice.bar.staff.bars[a.voice.bar.index+1].voices[a.voice.index].beats[0]}}}parseDom(e){let t=e.firstElement;if(!t)throw new ne("No valid XML");if("score"!==t.localName)throw new ne('Root node of XML was not "score"');this.score=new Me,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"info":this.parseInfo(e);break;case"layout":this.parseLayout(e);break;case"gallery":this.parseGallery(e);break;case"pageObjects":this.parsePageObjects(e);break;case"systems":this.parseSystems(e)}}parseLayout(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"staves":this.parseLayoutStaves(t);break;case"brackets":this.parseBrackets(t)}const t=this._brackets.filter((e=>!!e.curly));t.sort(((e,t)=>e.from-t.from));let i=0,s=null;for(let e=0;e<this._staffLayouts.length;e++){const a=this._staffLayouts[e];for(;i<t.length&&e>t[i].to;)i++;s&&i<t.length&&e>t[i].from&&e<=t[i].to?s.ensureStaveCount(s.staves.length+1):(s=new He,s.ensureStaveCount(1),s.name=a.description,s.playbackInfo.volume=Math.floor(a.volume/128*16),s.playbackInfo.program=a.instrument,a.percussion?(s.playbackInfo.primaryChannel=9,s.playbackInfo.secondaryChannel=9):(s.playbackInfo.primaryChannel=this._trackChannel++,s.playbackInfo.secondaryChannel=this._trackChannel++),this.score.addTrack(s));const r=s.staves[s.staves.length-1];r.isPercussion=a.percussion,r.transpositionPitch=a.transpose,r.displayTranspositionPitch=0,r.showTablature=!1,this._staffLookup.set(a.index,r)}}parseBrackets(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new oo;t.from=parseInt(e.getAttribute("from")),t.to=parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new no;t.description=e.getAttribute("description");for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"notation":i.attributes.has("defaultClef")&&(t.defaultClef=this.parseClef(i.attributes.get("defaultClef")));break;case"sound":i.attributes.has("percussion")&&(t.percussion="true"===i.attributes.get("percussion")),i.attributes.has("instr")&&(t.instrument=parseInt(i.attributes.get("instr"))),i.attributes.has("volume")&&(t.volume=parseInt(i.attributes.get("volume"))),i.attributes.has("transpose")&&(t.transpose=parseInt(i.attributes.get("transpose")))}this._staffLayoutLookup.set(t.description,t),t.index=this._staffLayouts.length,this._staffLayouts.push(t)}parseClef(e){switch(e){case"treble":return n.G2;case"bass":return n.F4;case"alto":case"tenor":return n.C4}return n.G2}parseClefOttava(e){return e.endsWith("-")?o._8vb:e.endsWith("+")?o._8va:o.Regular}parseSystems(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=L.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===H.Element&&"staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){let i=this.score.masterBars.length;for(let s of t.childNodes)if(s.nodeType===H.Element&&"staff"===s.localName)this.parseStaff(e,i,s)}parseStaff(e,t,i){const s=i.getAttribute("layout");this._currentStaffLayout=this._staffLayoutLookup.get(s),this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!1,this.parseTime(i.getAttribute("defaultTime"));const a=this._staffLookup.get(this._currentStaffLayout.index);for(;a.bars.length<t;)this.addNewBar(a);for(let r of i.childNodes)if(r.nodeType===H.Element&&"voices"===r.localName)this.parseVoices(s,a,e,t,r)}parseTime(e){switch(e){case"allaBreve":case"C":this._timeSignature.timeSignatureNumerator=2,this._timeSignature.timeSignatureDenominator=2,this._timeSignature.timeSignatureCommon=!0;break;case"longAllaBreve":this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!0;break;default:if(e.indexOf("/")>0){const t=e.split("/");this._timeSignature.timeSignatureNumerator=parseInt(t[0]),this._timeSignature.timeSignatureDenominator=parseInt(t[1]),this._timeSignature.timeSignatureCommon=!1}}}parseVoices(e,t,i,s,a){let r=0;for(let n of a.childNodes)if(n.nodeType===H.Element&&"voice"===n.localName)this.parseVoice(e,t,i,r,s,n),r++}getOrCreateBar(e,t){return t<e.bars.length?e.bars[t]:this.addNewBar(e)}addNewBar(e){let t=new he;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){let e=new Ce;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,i,s,a,n){const o=e+"_"+s;if(this._currentVoiceState&&!this._currentVoiceState.currentBarComplete&&(this._currentBar.masterBar.isAnacrusis=!0),this._voiceStates.has(o)?(this._currentVoiceState=this._voiceStates.get(o),this._currentBar=this.getOrCreateBar(t,this._currentVoiceState.currentBarIndex),this.ensureVoice(t,s)):(this._currentVoiceState=new ho,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(o,this._currentVoiceState),this.newBar(t,s)),n.attributes.has("stemDir"))switch(n.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=W.Up;break;case"down":this._currentVoiceState.voiceStemDir=W.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(i.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new oe,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=r.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(i.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===H.Element)switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,s),e.localName){case"clefSign":this._currentBar.clef=this.parseClef(e.getAttribute("clef")),this._currentBar.clefOttava=this.parseClefOttava(e.getAttribute("clef"));break;case"keySign":this._currentBar.masterBar.keySignature=parseInt(e.getAttribute("fifths"));break;case"timeSign":this.parseTime(e.getAttribute("time")),this._currentBar.masterBar.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,this._currentBar.masterBar.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,this._currentBar.masterBar.timeSignatureCommon=this._timeSignature.timeSignatureCommon,this._currentVoiceState.currentPosition=0,this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1);break;case"barline":switch(e.getAttribute("type")){case"double":this._currentBar.masterBar.isDoubleBar=!0,this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"end":this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0);break;case"repEnd":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"repBegin":this.newBar(t,s),this._currentBar.masterBar.isRepeatStart=!0,this._currentVoiceState.repeatEnd=null,this._currentVoiceState.repeatCount=0;break;case"repEndBegin":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this.newBar(t,s),this._currentBar.masterBar.isRepeatStart=!0;break;default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":let i=new xe;this.initFromPreviousBeat(i,this._currentVoice),i.beamingMode=this._beamingMode,this._currentVoiceState.voiceStemDir&&(i.preferredBeamDirection=this._currentVoiceState.voiceStemDir),this.parseDuration(this._currentBar,i,e.findChildElement("duration")),i.updateDurations(),this._currentVoiceState.currentPosition+=i.playbackDuration,this._currentVoice.addBeat(i),this.parseChord(i,e),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0);break;case"rest":const a=this.parseRestDurations(this._currentBar,e.findChildElement("duration"));a&&(this.initFromPreviousBeat(a,this._currentVoice),a.updateDurations(),this._currentVoiceState.currentPosition+=a.playbackDuration,this._currentVoice.addBeat(a),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0))}}initFromPreviousBeat(e,t){let i=this.getLastBeat(t);i&&(e.dynamics=i.dynamics)}getLastBeat(e){if(e.beats.length>0)return e.beats[e.beats.length-1];if(e.bar.index>0){const t=e.bar.staff.bars[e.bar.index-1];if(e.index<t.voices.length){const i=t.voices[e.index];return this.getLastBeat(i)}}return null}ensureVoice(e,t){for(;this._currentBar.voices.length<t+1;)this._currentBar.addVoice(new Ve);(!this._voiceCounts.has(e.track.index)||this._voiceCounts.get(e.track.index)<this._currentBar.voices.length)&&this._voiceCounts.set(e.track.index,this._currentBar.voices.length),this._currentVoice=this._currentBar.voices[t]}parseChord(e,t){const i=new _e;for(let s of t.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"stem":switch(s.getAttribute("dir")){case"up":e.preferredBeamDirection=W.Up;break;case"down":e.preferredBeamDirection=W.Down}break;case"articulation":switch(s.getAttribute("type")){case"staccato":i.isStaccato=!0;break;case"normalAccent":i.accentuated=a.Normal;break;case"strongAccent":i.accentuated=a.Heavy}break;case"lyric":this.parseLyric(e,s);break;case"drawObjects":this.parseBeatDrawObject(e,s);break;case"heads":this.parseHeads(e,i,s);break;case"beam":switch(s.getAttribute("group")){case"force":e.beamingMode=L.ForceMergeWithNext;break;case"divide":e.beamingMode=L.ForceSplitToNext}}}parseHeads(e,t,i){for(let s of i.childNodes)if(s.nodeType===H.Element&&"head"===s.localName)this.parseHead(e,t,s)}parseHead(e,t,i){const s=new _e,a=me.parseTuning(i.getAttribute("pitch"));s.octave=a.octave-1,s.tone=a.noteValue,s.isStaccato=t.isStaccato,s.accentuated=t.accentuated,e.addNote(s);for(let e of i.childNodes)if(e.nodeType===H.Element)switch(e.localName){case"alter":e.attributes.has("step")&&(s.tone+=parseInt(e.attributes.get("step")));break;case"tie":e.attributes.has("begin")?this._tieStartIds.has(s.id)||(this._tieStartIds.set(s.id,!0),this._tieStarts.push(s)):e.attributes.has("end")&&this._tieStarts.length>0&&!s.isTieDestination&&(s.isTieDestination=!0,s.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(s.id))}}parseBeatDrawObject(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"drawObj"===i.localName){const t=this.parseDrawObj(i);if(t)if(t instanceof $n)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new Ke,e.fermata.type=G.Medium):"f"===t.text?e.dynamics=g.F:"j"===t.text&&(e.dynamics=g.MF):this._isFirstSystem&&""===this.score.title&&t.align===E.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===E.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===E.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof Kn);else if(t instanceof eo)e.vibrato=w.Slight;else if(t instanceof io)e.crescendo=t.decrescendo?u.Decrescendo:u.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof Zn){const i=t;this._slurs.set(e,i)}else t instanceof so&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof so&&this.applyVolta(e)}}applyVolta(e){if(e.lastNumber>0?(this._currentVoiceState.repeatCount=e.lastNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)):e.firstNumber>0&&(this._currentVoiceState.repeatCount=e.firstNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)),e.lastNumber>0&&e.firstNumber>0){let t=0;for(let i=e.firstNumber;i<=e.lastNumber;i++)t|=1<<i-1;this._currentBar.masterBar.alternateEndings=t}else e.lastNumber>0?this._currentBar.masterBar.alternateEndings=1<<e.lastNumber-1:e.firstNumber>0&&(this._currentBar.masterBar.alternateEndings=1<<e.firstNumber-1)}parseLyric(e,t){for(let i of t.childNodes)if(i.nodeType===H.Element&&"verse"===i.localName){e.lyrics||(e.lyrics=[]);let t=i.innerText;"true"===i.getAttribute("hyphen")&&(t+="-"),e.lyrics.push(t)}}parseRestDurations(e,t){const i=t.getAttribute("base");if(-1!==i.indexOf("/")){let i=new xe;return i.beamingMode=this._beamingMode,this.parseDuration(e,i,t),i}if(1===parseInt(i)){let e=new xe;return e.beamingMode=this._beamingMode,e.duration=p.Whole,e}return ge.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return p.DoubleWhole;case"1/1":return p.Whole;case"1/2":return p.Half;case"1/4":return p.Quarter;case"1/8":return p.Eighth;case"1/16":return p.Sixteenth;case"1/32":return p.ThirtySecond;case"1/64":return p.SixtyFourth;case"1/128":return p.OneHundredTwentyEighth;default:return ge.warning("Importer","Unsupported duration"),p.Quarter}}parseDuration(e,t,i){const s=i.getAttribute("base");t.duration=this.parseDurationValue(s),i.attributes.has("dots")&&(t.dots=parseInt(i.attributes.get("dots")));const a=i.findChildElement("tuplet");if(a){t.tupletNumerator=parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,i="true"===a.getAttribute("prolong")?0:1;let s=0;for(;e*Math.pow(2,s+i)<t.tupletNumerator;)s++;t.tupletDenominator=e*Math.pow(2,s)}}parsePageObjects(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof $n)switch(e.align){case E.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case E.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===H.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,i=1;for(let s of e.childNodes)if(s.nodeType===H.Element)switch(s.localName){case"text":t=this.parseText(s);break;case"guitar":t=this.parseGuitar(s);break;case"slur":t=this.parseSlur(s);break;case"wavyLine":t=this.parseWavyLine(s);break;case"bracket":t=this.parseTupletBracket(s);break;case"wedge":t=this.parseWedge(s);break;case"volta":t=this.parseVolta(s);break;case"octaveClef":t=this.parseOctaveClef(s);break;case"trill":t=this.parseTrill(s);break;case"basic":s.attributes.has("noteRange")&&(i=parseInt(s.attributes.get("noteRange")))}return t&&(t.noteRange=i),t}parseTrill(e){return new ro}parseOctaveClef(e){const t=new ao;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new so;return t.allNumbers="true"===e.attributes.get("allNumbers"),e.attributes.has("firstNumber")&&(t.firstNumber=parseInt(e.attributes.get("firstNumber"))),e.attributes.has("lastNumber")&&(t.lastNumber=parseInt(e.attributes.get("lastNumber"))),t}parseWedge(e){const t=new io;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new to;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new eo}parseSlur(e){return new Zn}parseGuitar(e){const t=new Kn,i=e.innerText.trim();for(let e=0;e<i.length;e++)"/"===i.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(parseInt(i.charAt(e)));return t}parseText(e){const t=new $n;switch(e.attributes.has("x")&&(t.x=parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=E.Left;break;case"center":t.align=E.Center;break;case"right":t.align=E.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=Ys.Rectangle;break;case"ellipse":t.frame=Ys.Ellipse;break;case"circle":t.frame=Ys.Circle;break;case"none":t.frame=Ys.None}if(e.firstElement){for(let i of e.childNodes)if(i.nodeType===H.Element)switch(i.localName){case"font":t.fontFace=i.getAttribute("face"),i.attributes.has("weight")&&(t.weight=parseInt(i.attributes.get("weight"))),i.attributes.has("height")&&(t.height=parseInt(i.attributes.get("height")));break;case"content":t.text=i.innerText}}else t.text=e.innerText;return t}parseInfo(e){for(let t of e.childNodes)if(t.nodeType===H.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class co extends ae{get name(){return"Capella"}constructor(){super()}readScore(){ge.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new bt(this.data).read(),ge.debug(this.name,"Zip entries loaded"),e.length>0){for(let i of e)if("score.xml"===i.fileName)t=ze.toString(i.data,this.settings.importer.encoding)}else this.data.reset(),t=ze.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new ne("No valid capella file");ge.debug(this.name,"Start Parsing score.xml");try{let e=new lo;return e.parseXml(t,this.settings),ge.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new ne("Failed to parse CapXML",e)}}}class uo{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 po{constructor(e){this._elements=[];let t=null;const i=this._check.bind(this);this._check=()=>{t||(t=setTimeout((()=>{i(),t=null}),100))},this._callback=e,window.addEventListener("resize",this._check,!0),document.addEventListener("scroll",this._check,!0)}observe(e){this._elements.indexOf(e)>=0||(this._elements.push(e),this._check())}unobserve(e){this._elements=this._elements.filter((t=>t!=e))}_check(){const e=[];this._elements.forEach((t=>{const i=t.getBoundingClientRect();i.top+i.height>=0&&i.top<=window.innerHeight&&i.left+i.width>=0&&i.left<=window.innerWidth&&e.push({target:t,isIntersecting:!0})})),e.length&&this._callback(e,this)}}class go{constructor(e,t){this.vertical=e,this.createLayout=t}}class fo{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class mo{static createStyleElement(e,t){let i=e.getElementById("alphaTabStyle");if(!i){if(!t)return void ge.error("AlphaTab","Font directory could not be detected, cannot create style element");i=e.createElement("style"),i.id="alphaTabStyle";let s=`\n @font-face {\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n } \n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${mo.MusicFontSize}px;\n overflow: visible !important;\n }`;i.innerHTML=s,e.getElementsByTagName("head").item(0).appendChild(i),mo.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===mo._globalThis){try{mo._globalThis=globalThis}catch(e){}void 0===mo._globalThis&&(mo._globalThis=self),void 0===mo._globalThis&&(mo._globalThis=global),void 0===mo._globalThis&&(mo._globalThis=window),void 0===mo._globalThis&&(mo._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in mo.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in mo.globalThis}static createAlphaTabWorker(t){if(mo.isWebPackBundled)return new Worker(new URL("@coderline/alphatab",{}));if(!t)throw new re(e.AlphaTabErrorType.General,"Could not detect alphaTab script file, cannot initialize renderer");try{if(mo.webPlatform===Os.BrowserModule){const e=`import * as alphaTab from '${t}'`,i=new Blob([e],{type:"text/javascript"});return new Worker(URL.createObjectURL(i),{type:"module"})}{const e=`importScripts('${t}')`,i=new Blob([e]);return new Worker(URL.createObjectURL(i))}}catch(e){return ge.warning("Rendering","Could not create inline worker, fallback to normal worker"),new Worker(t)}}static throttle(e,t){let i=0;return()=>{mo.globalThis.clearTimeout(i),i=mo.globalThis.setTimeout(e,t)}}static detectScriptFile(){try{const e={};if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in mo.globalThis&&document.currentScript?document.currentScript.src:null}static registerJQueryPlugin(){if(!mo.isRunningInWorker&&mo.globalThis&&"jQuery"in mo.globalThis){let e=mo.globalThis.jQuery,t=new oa;e.fn.alphaTab=function(e){const i=Array.prototype.slice.call(arguments,1);return 1===this.length?t.exec(this[0],e,i):this.each(((s,a)=>{t.exec(a,e,i)}))},e.alphaTab={restore:oa.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&mo.renderEngines.has(e)?mo.renderEngines.get(e):mo.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&mo.layoutEngines.has(t)?mo.layoutEngines.get(t):mo.layoutEngines.get(e.LayoutMode.Page)}static buildImporters(){return[new qe,new kt,new St,new vt,new co,new Ye]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new fo(!0,(()=>new la))),e.set("default",e.get("svg")),mo.createPlatformSpecificRenderEngines(e),e}static createPlatformSpecificRenderEngines(e){e.set("html5",new fo(!1,(()=>new us)))}static createDefaultStaveProfiles(){const t=new Map;t.set(e.StaveProfile.ScoreTab,[new Fa("score-effects",[new pr,new br,new er,new gr,new Aa,new Ya,new Sr,new mr,new ir(!0),new _r,new hr,new wr,new dr,new jn,new Da]),new Mn,new Fa("tab-effects",[new Ha,new ir(!1),new Wa,new Za,new mr,new _r,new hr,new wr,new dr,new cr,new Ua,new Qa(y.Natural),new Qa(y.Artificial),new Qa(y.Pinch),new Qa(y.Tap),new Qa(y.Semi),new Qa(y.Feedback),new $a,new Ra,new qa,new sr,new nr,new ar,new jn]),new qn(!1,!1,!1)]),t.set(e.StaveProfile.Score,[new Fa("score-effects",[new pr,new br,new er,new gr,new Aa,new Ya,new Sr,new mr,new ir(!0),new _r,new hr,new wr,new dr,new Ua,new $a,new sr,new nr,new ar,new jn,new Da]),new Mn,new Fa("score-bottom-effects",[new Ha,new ir(!1),new Wa,new Za])]);let i=[new pr,new br,new er,new gr,new Aa,new Ya,new mr,new _r,new hr,new wr,new dr,new cr,new Ua,new Qa(y.Artificial),new Qa(y.Pinch),new Qa(y.Tap),new Qa(y.Semi),new Qa(y.Feedback),new $a,new Ra,new qa,new sr,new nr,new ar,new jn,new Da];return t.set(e.StaveProfile.Tab,[new Fa("tab-effects",i),new qn(!0,!0,!0),new Fa("tab-bottom-effects",[new Za])]),t.set(e.StaveProfile.TabMixed,[new Fa("tab-effects",i),new qn(!1,!1,!1),new Fa("tab-bottom-effects",[new Za])]),t}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.LayoutMode.Page,new go(!0,(e=>new Or(e)))),t.set(e.LayoutMode.Horizontal,new go(!1,(e=>new Ar(e)))),t}static platformInit(){mo.isRunningInAudioWorklet?ia.init():mo.isRunningInWorker?(cs.init(),ts.init()):mo.webPlatform!==Os.Browser&&mo.webPlatform!==Os.BrowserModule||(mo.registerJQueryPlugin(),mo.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in mo.globalThis||(mo.globalThis.ResizeObserver=uo),"IntersectionObserver"in mo.globalThis||(mo.globalThis.IntersectionObserver=po),"replaceChildren"in Element.prototype||(Element.prototype.replaceChildren=function(...e){this.innerHTML="",this.append(...e)},Document.prototype.replaceChildren=Element.prototype.replaceChildren,DocumentFragment.prototype.replaceChildren=Element.prototype.replaceChildren),"replaceAll"in String.prototype||(String.prototype.replaceAll=function(e,t){return this.replace(new RegExp(e,"g"),t)}))}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return Os.NodeJs}catch(e){}try{const e={};if(e&&"string"==typeof e&&!e.startsWith("file://"))return Os.BrowserModule}catch(e){}return Os.Browser}}mo.MusicFontSize=34,mo.HighDpiFactor=1,mo._globalThis=void 0,mo.webPlatform=mo.detectWebPlatform(),mo.isWebPackBundled=mo.detectWebPack(),mo.scriptFile=mo.detectScriptFile(),mo.bravuraFontChecker=new Js(["alphaTab"]),mo.renderEngines=mo.createDefaultRenderEngines(),mo.layoutEngines=mo.createDefaultLayoutEngines(),mo.staveProfiles=mo.createDefaultStaveProfiles(),mo.platformInit();class yo{constructor(){if(this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=e.LogLevel.Info,this.useWorkers=!0,this.includeNoteBounds=!1,!mo.isRunningInWorker&&mo.globalThis.ALPHATAB_ROOT?(this.scriptFile=mo.globalThis.ALPHATAB_ROOT,this.scriptFile=yo.ensureFullUrl(this.scriptFile),this.scriptFile=yo.appendScriptName(this.scriptFile)):this.scriptFile=mo.scriptFile,!mo.isRunningInWorker&&mo.globalThis.ALPHATAB_FONT)this.fontDirectory=mo.globalThis.ALPHATAB_FONT,this.fontDirectory=yo.ensureFullUrl(this.fontDirectory);else if(this.fontDirectory=this.scriptFile,this.fontDirectory){let e=this.fontDirectory.lastIndexOf(String.fromCharCode(47));e>=0&&(this.fontDirectory=this.fontDirectory.substr(0,e)+"/font/")}}static ensureFullUrl(e){var t,i,s;if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let a="",r=mo.globalThis.location;if(a+=null===(t=r.protocol)||void 0===t?void 0:t.toString(),a+="//".toString(),r.hostname&&(a+=null===(i=r.hostname)||void 0===i?void 0:i.toString()),r.port&&(a+=":".toString(),a+=null===(s=r.port)||void 0===s?void 0:s.toString()),!e.startsWith("/")){let e=r.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString())}return e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString(),a}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}}class bo{}bo.version="1.2.3",bo.date="2022-10-16T13:33:07.436Z";var So,_o=Object.freeze({__proto__:null,ScoreImporter:ae,ScoreLoader:Is,UnsupportedFormatError:ne});class wo{init(e,t){this.data=e,this.settings=t}export(e,t=null){const i=Ue.withCapacity(1024);return this.init(i,null!=t?t:new Di),this.writeScore(e),i.toArray()}}!function(e){e[e.SteelGuitar=1]="SteelGuitar",e[e.AcousticGuitar=2]="AcousticGuitar",e[e.TwelveStringGuitar=3]="TwelveStringGuitar",e[e.ElectricGuitar=4]="ElectricGuitar",e[e.Bass=5]="Bass",e[e.ClassicalGuitar=23]="ClassicalGuitar",e[e.UprightBass=6]="UprightBass",e[e.Ukulele=7]="Ukulele",e[e.Banjo=8]="Banjo",e[e.Mandolin=9]="Mandolin",e[e.Piano=10]="Piano",e[e.Synth=12]="Synth",e[e.Strings=11]="Strings",e[e.Brass=13]="Brass",e[e.Reed=14]="Reed",e[e.Woodwind=15]="Woodwind",e[e.Vocal=16]="Vocal",e[e.PitchedIdiophone=17]="PitchedIdiophone",e[e.Fx=21]="Fx",e[e.PercussionKit=18]="PercussionKit",e[e.Idiophone=19]="Idiophone",e[e.Membraphone=20]="Membraphone"}(So||(So={}));class Bo{constructor(e,t,i=null){if(this.icon=So.Piano,this.icon=e,this.instrumentSetName=t,i)this.instrumentSetType=i;else{const e=t.split(" ");e[0]=e[0].substr(0,1).toLowerCase()+e[0].substr(1),this.instrumentSetType=e.join("")}}}class To{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new st;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const i=e.addElement("GPIF");i.addElement("GPVersion").innerText="7";const s=i.addElement("GPRevision");s.innerText="7",s.attributes.set("required","12021"),s.attributes.set("recommended","12023"),s.innerText="12025",i.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(i,t),this.writeMasterTrackNode(i,t),this.writeAudioTracksNode(i,t),this.writeTracksNode(i,t),this.writeMasterBarsNode(i,t);const a=i.addElement("Bars"),r=i.addElement("Voices"),n=i.addElement("Beats"),o=i.addElement("Notes"),h=i.addElement("Rhythms");for(const e of t.tracks)for(const t of e.staves)for(const e of t.bars){this.writeBarNode(a,e);for(const t of e.voices){this.writeVoiceNode(r,t);for(const e of t.beats){this.writeBeatNode(n,e,h);for(const t of e.notes)this.writeNoteNode(o,t)}}}}writeNoteNode(e,t){const i=e.addElement("Note");i.attributes.set("id",t.id.toString()),this.writeNoteProperties(i,t),t.isGhost&&(i.addElement("AntiAccent").innerText="normal"),t.isLetRing&&i.addElement("LetRing"),t.isTrill&&(i.addElement("Trill").innerText=t.trillValue.toString());let s=0;switch(t.isStaccato&&(s|=1),t.accentuated){case a.Normal:s|=8;break;case a.Heavy:s|=4}if(s>0&&(i.addElement("Accent").innerText=s.toString()),t.isTieOrigin||t.isTieDestination){const e=i.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case w.Slight:i.addElement("Vibrato").innerText="Slight";break;case w.Wide:i.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case m.Thumb:i.addElement("LeftFingering").innerText="P";break;case m.IndexFinger:i.addElement("LeftFingering").innerText="I";break;case m.MiddleFinger:i.addElement("LeftFingering").innerText="M";break;case m.AnnularFinger:i.addElement("LeftFingering").innerText="A";break;case m.LittleFinger:i.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case m.Thumb:i.addElement("RightFingering").innerText="P";break;case m.IndexFinger:i.addElement("RightFingering").innerText="I";break;case m.MiddleFinger:i.addElement("RightFingering").innerText="M";break;case m.AnnularFinger:i.addElement("RightFingering").innerText="A";break;case m.LittleFinger:i.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?i.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():i.addElement("InstrumentArticulation").innerText="0"}writeNoteProperties(e,t){const i=e.addElement("Properties");if(this.writeConcertPitch(i,t),this.writeTransposedPitch(i,t),t.isStringed&&(this.writeSimplePropertyNode(i,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(i,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(i,"Midi","Number",t.realValue.toString())),t.isPiano&&(this.writeSimplePropertyNode(i,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(i,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(i,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(i,"Tapped","Enable",null),t.harmonicType!==y.None){switch(t.harmonicType){case y.Natural:this.writeSimplePropertyNode(i,"HarmonicType","HType","Natural");break;case y.Artificial:this.writeSimplePropertyNode(i,"HarmonicType","HType","Artificial");break;case y.Pinch:this.writeSimplePropertyNode(i,"HarmonicType","HType","Pinch");break;case y.Tap:this.writeSimplePropertyNode(i,"HarmonicType","HType","Tap");break;case y.Semi:this.writeSimplePropertyNode(i,"HarmonicType","HType","Semi");break;case y.Feedback:this.writeSimplePropertyNode(i,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(i,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(i,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(i,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(i,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(i,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(i,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(i,"LeftHandTapped","Enable",null);let s=0;switch(t.slideInType){case S.IntoFromAbove:s|=32;break;case S.IntoFromBelow:s|=16}switch(t.slideOutType){case _.Shift:s|=1;break;case _.Legato:s|=2;break;case _.OutDown:s|=4;break;case _.OutUp:s|=8;break;case _.PickSlideDown:s|=64;break;case _.PickSlideUp:s|=128}s>0&&this.writeSimplePropertyNode(i,"Slide","Flags",s.toString())}writeTransposedPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"TransposedPitch",t.displayValueWithoutBend,t.accidentalMode)}writeConcertPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"ConcertPitch",t.realValueWithoutHarmonic,t.accidentalMode)}writePitchForValue(e,t,i,s){let a=0,r=0,n="",o="";const h=()=>{a=i%12,r=i/12|0,n=Oe.defaultSteps[a],o=Oe.defaultAccidentals[a]};switch(h(),s){case b.Default:break;case b.ForceNone:case b.ForceNatural:o="";break;case b.ForceSharp:o="#";break;case b.ForceDoubleSharp:"#"===o&&(i-=2,h()),o="x";break;case b.ForceFlat:"#"===o&&(i+=1,h()),o="b";break;case b.ForceDoubleFlat:"#"===o&&(i+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,i,s,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=i,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=s}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);var i,s,a=t[0],r=t[t.length-1];switch(t.length){case 4:i=t[1],s=t[2];break;case 3:i=t[1],s=t[1];break;default:s=i=new de((a.offset+r.offset)/2,(a.value+r.value)/2)}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(r.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(i.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(i.value).toString()),this.writeSimplePropertyNode(e,"BendOriginOffset","Float",this.toBendOffset(a.offset).toString()),this.writeSimplePropertyNode(e,"BendOriginValue","Float",this.toBendValue(a.value).toString())}toBendValue(e){return 25*e}toBendOffset(e){return e/de.MaxPosition*100}writeBeatNode(e,t,i){const s=e.addElement("Beat");if(s.attributes.set("id",t.id.toString()),s.addElement("Dynamic").innerText=g[t.dynamics],t.fadeIn&&(s.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case p.Eighth:s.addElement("Tremolo").innerText="1/2";break;case p.Sixteenth:s.addElement("Tremolo").innerText="1/4";break;case p.ThirtySecond:s.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&s.addElement("Chord").setCData(t.chordId),t.crescendo!==u.None&&(s.addElement("Hairpin").innerText=u[t.crescendo]),t.brushType){case c.ArpeggioUp:s.addElement("Arpeggio").innerText="Up";break;case c.ArpeggioDown:s.addElement("Arpeggio").innerText="Down"}switch(t.text&&s.addElement("FreeText").setCData(t.text),t.graceType){case f.OnBeat:case f.BeforeBeat:s.addElement("GraceNotes").innerText=f[t.graceType]}if(t.ottava!==o.Regular&&(s.addElement("Ottavia").innerText=o[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(s,t),t.isLegatoOrigin||t.isLegatoDestination){const e=s.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(s,t,i),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case W.Up:s.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case W.Down:s.addElement("TransposedPitchStemOrientation").innerText="Downward"}s.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.isRest||(s.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),this.writeBeatProperties(s,t),this.writeBeatXProperties(s,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(s,t.lyrics)}writeBeatLyrics(e,t){const i=e.addElement("Lyrics");for(const e of t){i.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const i=e.addElement("XProperties");t.brushDuration>0&&this.writeSimpleXPropertyNode(i,"687935489","Int",t.brushDuration.toString())}writeBeatProperties(e,t){const i=e.addElement("Properties");switch(t.brushType){case c.BrushUp:this.writeSimplePropertyNode(i,"Brush","Direction","Up");break;case c.BrushDown:this.writeSimplePropertyNode(i,"Brush","Direction","Down")}switch(t.pickStroke){case x.Up:this.writeSimplePropertyNode(i,"PickStroke","Direction","Up");break;case x.Down:this.writeSimplePropertyNode(i,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(i,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(i,"Popped","Enable",null),t.vibrato){case w.Wide:this.writeSimplePropertyNode(i,"VibratoWTremBar","Strength","Wide");break;case w.Slight:this.writeSimplePropertyNode(i,"VibratoWTremBar","Strength","Slight")}}writeRhythm(e,t,i){const s=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(s))a=this._rhythmIdLookup.get(s);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(s,a);const e=i.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const i=e.addElement("PrimaryTuplet");i.attributes.set("num",t.tupletNumerator.toString()),i.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case p.QuadrupleWhole:r="Long";break;case p.DoubleWhole:r="DoubleWhole";break;case p.Whole:r="Whole";break;case p.Half:r="Half";break;case p.Quarter:r="Quarter";break;case p.Eighth:r="Eighth";break;case p.Sixteenth:r="16th";break;case p.ThirtySecond:r="32nd";break;case p.SixtyFourth:r="64th";break;case p.OneHundredTwentyEighth:r="128th";break;case p.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const i=e.addElement("Whammy");var s,a,r=t[0],n=t[t.length-1];switch(t.length){case 4:s=t[1],a=t[2];break;case 3:s=t[1],a=t[1];break;default:a=s=new de((r.offset+n.offset)/2,(r.value+n.value)/2)}i.attributes.set("destinationOffset",this.toBendOffset(n.offset).toString()),i.attributes.set("destinationValue",this.toBendValue(n.value).toString()),i.attributes.set("middleOffset1",this.toBendOffset(s.offset).toString()),i.attributes.set("middleOffset2",this.toBendOffset(a.offset).toString()),i.attributes.set("middleValue",this.toBendValue(s.value).toString()),i.attributes.set("originOffset",this.toBendOffset(r.offset).toString()),i.attributes.set("originValue",this.toBendValue(r.value).toString())}writeScoreNode(e,t){const i=e.addElement("Score");i.addElement("Title").setCData(t.title),i.addElement("SubTitle").setCData(t.subTitle),i.addElement("Artist").setCData(t.artist),i.addElement("Album").setCData(t.album),i.addElement("Words").setCData(t.words),i.addElement("Music").setCData(t.music),i.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),i.addElement("Copyright").setCData(t.copyright),i.addElement("Tabber").setCData(t.tab),i.addElement("Instructions").setCData(t.instructions),i.addElement("Notices").setCData(t.notices),i.addElement("FirstPageHeader").setCData(""),i.addElement("FirstPageFooter").setCData(""),i.addElement("PageHeader").setCData(""),i.addElement("PageFooter").setCData(""),i.addElement("ScoreSystemsDefaultLayout").setCData("4"),i.addElement("ScoreSystemsLayout").setCData("4"),i.addElement("ScoreZoomPolicy").innerText="Value",i.addElement("ScoreZoom").innerText="1",i.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const i=e.addElement("MasterTrack");i.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const s=i.addElement("Automations");t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&i.addElement("Anacrusis");const a=s.addElement("Automation");a.addElement("Type").innerText="Tempo",a.addElement("Linear").innerText="false",a.addElement("Bar").innerText="0",a.addElement("Position").innerText="0",a.addElement("Visible").innerText="true",a.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(a.addElement("Text").innerText=t.tempoLabel);for(const e of t.masterBars)if(e.index>0&&e.tempoAutomation){const t=s.addElement("Automation");t.addElement("Type").innerText="Tempo",t.addElement("Linear").innerText=e.tempoAutomation.isLinear?"true":"false",t.addElement("Bar").innerText=e.index.toString(),t.addElement("Position").innerText=e.tempoAutomation.ratioPosition.toString(),t.addElement("Visible").innerText="true",t.addElement("Value").innerText=`${e.tempoAutomation.value} 2`,e.tempoAutomation.text&&(t.addElement("Text").innerText=e.tempoAutomation.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const i=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(i,e)}writeTrackNode(e,t){const i=e.addElement("Track");i.attributes.set("id",t.index.toString()),i.addElement("Name").setCData(t.name),i.addElement("ShortName").setCData(t.shortName),i.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,i.addElement("SystemsDefautLayout").innerText="3",i.addElement("SystemsLayout").innerText="1",i.addElement("AutoBrush"),i.addElement("PalmMute").innerText="0",i.addElement("PlayingStyle").innerText=se.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",i.addElement("UseOneChannelPerString"),i.addElement("IconId").innerText=To.getIconId(t.playbackInfo).toString(),this.writeInstrumentSetNode(i,t),this.writeTransposeNode(i,t),this.writeRseNode(i,t),i.addElement("ForcedSound").innerText="-1",this.writeMidiConnectionNode(i,t),t.playbackInfo.isSolo?i.addElement("PlaybackState").innerText="Solo":t.playbackInfo.isMute?i.addElement("PlaybackState").innerText="Mute":i.addElement("PlaybackState").innerText="Default",i.addElement("AudioEngineState").innerText="MIDI",this.writeLyricsNode(i,t),this.writeStavesNode(i,t),this.writeSoundsAndAutomations(i,t)}static getIconId(e){return 9===e.primaryChannel?To.DrumKitProgramInfo.icon:To.MidiProgramInfoLookup.has(e.program)?To.MidiProgramInfoLookup.get(e.program).icon:So.SteelGuitar}writeSoundAndAutomation(e,t,i,s,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(i),h.addElement("Label").setCData(i),h.addElement("Path").setCData(s),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const d=t.addElement("Automation");d.addElement("Type").innerText="Sound",d.addElement("Linear").innerText="false",d.addElement("Bar").innerText=r.toString(),d.addElement("Position").innerText=o.toString(),d.addElement("Visible").innerText="true",d.addElement("Value").setCData(`${s};${i};${a}`)}writeSoundsAndAutomations(e,t){const i=e.addElement("Sounds"),s=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,a=`Midi/${t.playbackInfo.program}`,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const d of h.beats){const h=d.getAutomation(r.Instrument),c=0===l.index&&0===d.index;if(h){const r=c?e:`ProgramChange_${d.id}`,u=c?a:`Midi/${h.value}`,p=c?n:"User";c||o||(this.writeSoundAndAutomation(i,s,e,a,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(i,s,r,u,p,l.index,h.value,h.ratioPosition),c&&(o=!0)}}}}writeMidiConnectionNode(e,t){const i=e.addElement("MidiConnection");i.addElement("Port").innerText=t.playbackInfo.port.toString(),i.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),i.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),i.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const i=e.addElement("RSE").addElement("ChannelStrip");i.attributes.set("version","E56");i.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const i=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(i,e)}writeStaffNode(e,t){const i=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(i,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(i,"FretCount","Fret","24"),t.tuning.length>0){const e=i.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(i,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(i,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(i,"TuningFlat","Enable",null),this.writeDiagramCollection(i,t,"DiagramCollection"),this.writeDiagramCollection(i,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,i){const s=e.addElement("Property");s.attributes.set("name",i);const a=s.addElement("Items"),r=t.chords;for(const[e,t]of r){const i=a.addElement("Item");i.attributes.set("id",e),i.attributes.set("name",t.name);const s=i.addElement("Diagram");s.attributes.set("stringCount",t.strings.length.toString()),s.attributes.set("fretCount","5"),s.attributes.set("baseFret",(t.firstFret-1).toString()),s.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){let i=t.strings[e];if(-1!==i){const a=s.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(i-t.firstFret+1).toString()),n.has(i)||(n.set(i,[]),r.push(i)),n.get(i).push(o)}}r.sort();const o=s.addElement("Fingering");if(t.barreFrets.length>0){const e=[m.LittleFinger,m.AnnularFinger,m.MiddleFinger,m.IndexFinger];for(const i of r){const s=n.get(i);if(s.length>1&&t.barreFrets.indexOf(i)>=0){const a=e.length>0?e.pop():m.IndexFinger;for(const e of s){const s=o.addElement("Position");switch(a){case m.LittleFinger:s.attributes.set("finger","Pinky");break;case m.AnnularFinger:s.attributes.set("finger","Ring");break;case m.MiddleFinger:s.attributes.set("finger","Middle");break;case m.IndexFinger:s.attributes.set("finger","Index")}s.attributes.set("fret",(i-t.firstFret+1).toString()),s.attributes.set("string",e.toString())}}}}const h=s.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=s.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const d=s.addElement("Property");d.attributes.set("name","ShowFingering"),d.attributes.set("type","bool"),d.attributes.set("value",t.showFingering?"true":"false");const c=s.addElement("Chord"),u=c.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=c.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=c.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const f=c.addElement("Degree");f.attributes.set("interval","Fifth"),f.attributes.set("alteration","Perfect"),f.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,i,s){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(i);return null!==s&&(r.innerText=s),a}writeSimpleXPropertyNode(e,t,i,s){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(i);return null!==s&&(r.innerText=s),a}writeLyricsNode(e,t){const i=e.addElement("Lyrics");i.attributes.set("dispatched","true");let s=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const i of t.beats)if(i.lyrics)for(let t=0;t<i.lyrics.length;t++){for(;t>=s.length;){const t=new Ee;t.startBar=e.index,t.text="[Empty]",s.push(t)}const a=s[t];a.text="[Empty]"==a.text?i.lyrics[t]:a.text+" "+i.lyrics[t].split(" ").join("+")}for(let e=0;e<s.length;e++){const t=i.addElement("Line");t.addElement("Text").setCData(s[e].text),t.addElement("Offset").innerText=s[e].startBar.toString()}}writeTransposeNode(e,t){const i=e.addElement("Transpose"),s=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*s;i.addElement("Chromatic").innerText=a.toString(),i.addElement("Octave").innerText=s.toString()}writeInstrumentSetNode(e,t){const i=e.addElement("InstrumentSet"),s=t.staves[0];if(i.addElement("LineCount").innerText=s.standardNotationLineCount.toString(),t.percussionArticulations.length>0||s.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(be.instrumentArticulations.values());i.addElement("Name").innerText=To.DrumKitProgramInfo.instrumentSetName,i.addElement("Type").innerText=To.DrumKitProgramInfo.instrumentSetType;let s="",r=new Ze,n=new Map;const o=i.addElement("Elements");for(const t of e){{var a=o.addElement("Element");let e=t.elementType;if(n.has(e)){const t=n.get(e);e+=" "+t,n.set(e,t+1)}else n.set(e,1);s=e,a.addElement("Name").innerText=e,a.addElement("Type").innerText=t.elementType,r=a.addElement("Articulations")}const e=r.addElement("Articulation");switch(e.addElement("Name").innerText=s+" "+r.childNodes.length,e.addElement("StaffLine").innerText=t.staffLine.toString(),e.addElement("Noteheads").innerText=[this.mapMusicSymbol(t.noteHeadDefault),this.mapMusicSymbol(t.noteHeadHalf),this.mapMusicSymbol(t.noteHeadWhole)].join(" "),t.techniqueSymbolPlacement){case C.Top:e.addElement("TechniquePlacement").innerText="below";break;case C.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case C.Bottom:e.addElement("TechniquePlacement").innerText="above"}e.addElement("TechniqueSymbol").innerText=this.mapMusicSymbol(t.techniqueSymbol),e.addElement("InputMidiNumbers").innerText="",e.addElement("OutputMidiNumber").innerText=t.outputMidiNumber.toString()}}else{const e=To.MidiProgramInfoLookup.has(t.playbackInfo.program)?To.MidiProgramInfoLookup.get(t.playbackInfo.program):To.MidiProgramInfoLookup.get(0);i.addElement("Name").innerText=e.instrumentSetName,i.addElement("Type").innerText=e.instrumentSetType;const s=i.addElement("Elements").addElement("Element");s.addElement("Pitched").innerText="Pitched",s.addElement("Type").innerText="pitched",s.addElement("SoundbankName").innerText="";const a=s.addElement("Articulations").addElement("Articulation");a.addElement("Name").innerText="",a.addElement("StaffLine").innerText="0",a.addElement("Noteheads").innerText="noteheadBlack noteheadHalf noteheadWhole",a.addElement("TechniquePlacement").innerText="outside",a.addElement("TechniqueSymbol").innerText="",a.addElement("InputMidiNumbers").innerText="",a.addElement("OutputRSESound").innerText="",a.addElement("OutputMidiNumber").innerText="0"}}mapMusicSymbol(e){if(e===P.None)return"";let t=P[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const i=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(i,e)}writeMasterBarNode(e,t){const i=e.addElement("MasterBar"),s=i.addElement("Key");s.addElement("AccidentalCount").innerText=t.keySignature.toString(),s.addElement("Mode").innerText=I[t.keySignatureType],s.addElement("Sharps").innerText="Sharps",i.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`;let a=[];for(const e of t.score.tracks)for(const i of e.staves)a.push(i.bars[t.index].id.toString());if(i.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&i.addElement("DoubleBar"),t.isSectionStart){const e=i.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=i.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const s=[];let a=0;for(;e>0;)1==(e>>a&1)&&(s.push(a+1),e&=~(1<<a)),a++;i.addElement("AlternateEndings").innerText=s.join(" ")}t.tripletFeel!==R.NoTripletFeel&&(i.addElement("TripletFeel").innerText=R[t.tripletFeel]),this.writeFermatas(i,t)}writeFermatas(e,t){const i=t.fermata.size;if(0!==i&&i>0){const i=e.addElement("Fermatas");for(const[e,s]of t.fermata)this.writeFermata(i,e,s)}}writeFermata(e,t,i){let s=-1,a=1;if(t>0)for(;a<10&&(s=t/le.QuarterTime*a,s!==Math.floor(s));)s=-1,a++;else s=0,a=1;if(-1===s)return;const r=e.addElement("Fermata");r.addElement("Type").innerText=G[i.type],r.addElement("Length").innerText=i.length.toString(),r.addElement("Offset").innerText=`${s}/${a}`}writeBarNode(e,t){const i=e.addElement("Bar");i.attributes.set("id",t.id.toString()),i.addElement("Voices").innerText=t.voices.map((e=>e.isEmpty?"-1":e.id.toString())).join(" "),i.addElement("Clef").innerText=n[t.clef],t.clefOttava!==o.Regular&&(i.addElement("Ottavia").innerText=o[t.clefOttava].substr(1)),t.simileMark!==h.None&&(i.addElement("SimileMark").innerText=h[t.simileMark])}writeVoiceNode(e,t){if(t.isEmpty)return;const i=e.addElement("Voice");i.attributes.set("id",t.id.toString()),i.addElement("Beats").innerText=t.beats.map((e=>e.id)).join(" ")}}To.MidiProgramInfoLookup=new Map([[0,new Bo(So.Piano,"Acoustic Piano")],[1,new Bo(So.Piano,"Acoustic Piano")],[2,new Bo(So.Piano,"Electric Piano")],[3,new Bo(So.Piano,"Acoustic Piano")],[4,new Bo(So.Piano,"Electric Piano")],[5,new Bo(So.Piano,"Electric Piano")],[6,new Bo(So.Piano,"Harpsichord")],[7,new Bo(So.Piano,"Harpsichord")],[8,new Bo(So.PitchedIdiophone,"Celesta")],[9,new Bo(So.PitchedIdiophone,"Vibraphone")],[10,new Bo(So.PitchedIdiophone,"Vibraphone")],[11,new Bo(So.PitchedIdiophone,"Vibraphone")],[12,new Bo(So.PitchedIdiophone,"Xylophone")],[13,new Bo(So.PitchedIdiophone,"Xylophone")],[14,new Bo(So.PitchedIdiophone,"Vibraphone")],[15,new Bo(So.Banjo,"Banjo")],[16,new Bo(So.Piano,"Electric Organ")],[17,new Bo(So.Piano,"Electric Organ")],[18,new Bo(So.Piano,"Electric Organ")],[19,new Bo(So.Piano,"Electric Organ")],[20,new Bo(So.Piano,"Electric Organ")],[21,new Bo(So.Piano,"Electric Organ")],[22,new Bo(So.Woodwind,"Recorder")],[23,new Bo(So.Piano,"Electric Organ")],[24,new Bo(So.ClassicalGuitar,"Nylon Guitar")],[25,new Bo(So.SteelGuitar,"Steel Guitar")],[26,new Bo(So.SteelGuitar,"Electric Guitar")],[27,new Bo(So.ElectricGuitar,"Electric Guitar")],[28,new Bo(So.ElectricGuitar,"Electric Guitar")],[29,new Bo(So.ElectricGuitar,"Electric Guitar")],[30,new Bo(So.SteelGuitar,"Electric Guitar")],[31,new Bo(So.SteelGuitar,"Electric Guitar")],[32,new Bo(So.Bass,"Acoustic Bass")],[33,new Bo(So.Bass,"Electric Bass")],[34,new Bo(So.Bass,"Electric Bass")],[35,new Bo(So.Bass,"Acoustic Bass")],[36,new Bo(So.Bass,"Electric Bass")],[37,new Bo(So.Bass,"Electric Bass")],[38,new Bo(So.Synth,"Synth Bass")],[39,new Bo(So.Synth,"Synth Bass")],[40,new Bo(So.Strings,"Violin")],[41,new Bo(So.Strings,"Viola")],[42,new Bo(So.Strings,"Cello")],[43,new Bo(So.Strings,"Contrabass")],[44,new Bo(So.Strings,"Violin")],[45,new Bo(So.Strings,"Violin")],[46,new Bo(So.Piano,"Harp")],[47,new Bo(So.Membraphone,"Timpani")],[48,new Bo(So.Strings,"Violin")],[49,new Bo(So.Strings,"Violin")],[50,new Bo(So.Strings,"Violin")],[51,new Bo(So.Strings,"Violin")],[52,new Bo(So.Vocal,"Voice")],[53,new Bo(So.Vocal,"Voice")],[54,new Bo(So.Vocal,"Voice")],[55,new Bo(So.Synth,"Pad Synthesizer")],[56,new Bo(So.Brass,"Trumpet")],[57,new Bo(So.Brass,"Trombone")],[58,new Bo(So.Brass,"Tuba")],[59,new Bo(So.Brass,"Trumpet")],[60,new Bo(So.Brass,"French Horn")],[61,new Bo(So.Brass,"Trumpet")],[62,new Bo(So.Brass,"Trumpet")],[63,new Bo(So.Brass,"Trumpet")],[64,new Bo(So.Reed,"Saxophone")],[65,new Bo(So.Reed,"Saxophone")],[66,new Bo(So.Reed,"Saxophone")],[67,new Bo(So.Reed,"Saxophone")],[68,new Bo(So.Reed,"Oboe")],[69,new Bo(So.Reed,"English Horn")],[70,new Bo(So.Reed,"Bassoon")],[71,new Bo(So.Reed,"Clarinet")],[72,new Bo(So.Reed,"Piccolo")],[73,new Bo(So.Woodwind,"Flute")],[74,new Bo(So.Woodwind,"Recorder")],[75,new Bo(So.Woodwind,"Flute")],[76,new Bo(So.Woodwind,"Recorder")],[77,new Bo(So.Woodwind,"Flute")],[78,new Bo(So.Woodwind,"Recorder")],[79,new Bo(So.Woodwind,"Flute")],[80,new Bo(So.Synth,"Lead Synthesizer")],[81,new Bo(So.Synth,"Lead Synthesizer")],[82,new Bo(So.Synth,"Lead Synthesizer")],[83,new Bo(So.Synth,"Lead Synthesizer")],[84,new Bo(So.Synth,"Lead Synthesizer")],[85,new Bo(So.Synth,"Lead Synthesizer")],[86,new Bo(So.Synth,"Lead Synthesizer")],[87,new Bo(So.Synth,"Lead Synthesizer")],[88,new Bo(So.Synth,"Pad Synthesizer")],[89,new Bo(So.Synth,"Pad Synthesizer")],[90,new Bo(So.Synth,"Pad Synthesizer")],[91,new Bo(So.Synth,"Pad Synthesizer")],[92,new Bo(So.Synth,"Pad Synthesizer")],[93,new Bo(So.Synth,"Pad Synthesizer")],[94,new Bo(So.Synth,"Pad Synthesizer")],[95,new Bo(So.Synth,"Pad Synthesizer")],[96,new Bo(So.Fx,"Pad Synthesizer")],[97,new Bo(So.Fx,"Pad Synthesizer")],[98,new Bo(So.Fx,"Pad Synthesizer")],[99,new Bo(So.Fx,"Pad Synthesizer")],[100,new Bo(So.Fx,"Lead Synthesizer")],[101,new Bo(So.Fx,"Lead Synthesizer")],[102,new Bo(So.Fx,"Lead Synthesizer")],[103,new Bo(So.Fx,"Trumpet")],[104,new Bo(So.ElectricGuitar,"Banjo")],[105,new Bo(So.Banjo,"Banjo")],[106,new Bo(So.Ukulele,"Ukulele")],[107,new Bo(So.Banjo,"Banjo")],[108,new Bo(So.PitchedIdiophone,"Xylophone")],[109,new Bo(So.Reed,"Bassoon")],[110,new Bo(So.Strings,"Violin")],[111,new Bo(So.Woodwind,"Flute")],[112,new Bo(So.PitchedIdiophone,"Xylophone")],[113,new Bo(So.Idiophone,"Celesta")],[114,new Bo(So.PitchedIdiophone,"Vibraphone")],[115,new Bo(So.Idiophone,"Xylophone")],[116,new Bo(So.Membraphone,"Xylophone")],[117,new Bo(So.Membraphone,"Xylophone")],[118,new Bo(So.Membraphone,"Xylophone")],[119,new Bo(So.Idiophone,"Celesta")],[120,new Bo(So.Fx,"Steel Guitar")],[121,new Bo(So.Fx,"Recorder")],[122,new Bo(So.Fx,"Recorder")],[123,new Bo(So.Fx,"Recorder")],[124,new Bo(So.Fx,"Recorder")],[125,new Bo(So.Fx,"Recorder")],[126,new Bo(So.Fx,"Recorder")],[127,new Bo(So.Fx,"Timpani")]]),To.DrumKitProgramInfo=new Bo(So.PercussionKit,"Drums","drumKit");class ko{constructor(){this._checkValue=ko.CrcInit,this.reset()}static buildCrc32Lookup(){const e=new Uint32Array(256);for(let t=0;t<e.length;t++){let i=t;for(let e=0;e<8;e++)i=1==(1&i)?i>>>1^3988292384:i>>>1;e[t]=i}return e}get value(){return~this._checkValue}update(e,t,i){for(let s=0;s<i;s++)this._checkValue=ko.Crc32Lookup[255&(this._checkValue^e[t+s])]^this._checkValue>>>8}reset(){this._checkValue=ko.CrcInit}}ko.Crc32Lookup=ko.buildCrc32Lookup(),ko.CrcInit=4294967295;class vo{}vo.MAX_WBITS=15,vo.WSIZE=1<<vo.MAX_WBITS,vo.WMASK=vo.WSIZE-1,vo.MIN_MATCH=3,vo.MAX_MATCH=258,vo.DEFAULT_MEM_LEVEL=8,vo.PENDING_BUF_SIZE=1<<vo.DEFAULT_MEM_LEVEL+8,vo.HASH_BITS=vo.DEFAULT_MEM_LEVEL+7,vo.HASH_SIZE=1<<vo.HASH_BITS,vo.HASH_SHIFT=(vo.HASH_BITS+vo.MIN_MATCH-1)/vo.MIN_MATCH,vo.HASH_MASK=vo.HASH_SIZE-1,vo.MIN_LOOKAHEAD=vo.MAX_MATCH+vo.MIN_MATCH+1,vo.MAX_DIST=vo.WSIZE-vo.MIN_LOOKAHEAD;class No{constructor(e,t,i,s){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=i,this.maxLength=s,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(s)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){let e=this.freqs.length,t=new Int32Array(e),i=0,s=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=i++;for(;r>0;){let i=Math.floor((r-1)/2);if(!(this.freqs[t[i]]>e))break;t[r]=t[i],r=i}t[r]=a,s=a}}for(;i<2;){let e=s<2?++s:0;t[i++]=e}this.numCodes=Math.max(s+1,this.minNumCodes);let a=i,r=new Int32Array(4*i-2),n=new Int32Array(2*i-1),o=a;for(let e=0;e<i;e++){let i=t[e];r[2*e]=i,r[2*e+1]=-1,n[e]=this.freqs[i]<<8,t[e]=e}do{let e=t[0],s=t[--i],a=0,h=1;for(;h<i;)h+1<i&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[s];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=s;let d=t[0];s=o++,r[2*s]=e,r[2*s+1]=d;let c=Math.min(255&n[e],255&n[d]);for(l=n[e]+n[d]-c+1,n[s]=l,a=0,h=1;h<i;)h+1<i&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=s}while(i>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);let t=Math.floor(e.length/2),i=Math.floor((t+1)/2),s=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let a=new Int32Array(t);a[t-1]=0;for(let i=t-1;i>=0;i--)if(-1!=e[2*i+1]){let t=a[i]+1;t>this.maxLength&&(t=this.maxLength,s++),a[e[2*i]]=t,a[e[2*i+1]]=t}else{let t=a[i];this.bitLengthCounts[t-1]++,this.length[e[2*i]]=a[i]}if(0==s)return;let r=this.maxLength-1;do{for(;0==this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,s-=1<<this.maxLength-1-r}while(s>0&&r<this.maxLength-1)}while(s>0);this.bitLengthCounts[this.maxLength-1]+=s,this.bitLengthCounts[this.maxLength-2]-=s;let n=2*i;for(let t=this.maxLength;0!=t;t--){let i=this.bitLengthCounts[t-1];for(;i>0;){let s=2*e[n++];-1==e[s+1]&&(this.length[e[s]]=t,i--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,i,s,a=-1,r=0;for(;r<this.numCodes;){s=1;let n=this.length[r];for(0==n?(t=138,i=3):(t=6,i=3,a!=n&&(e.freqs[n]++,s=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++s>=t)););s<i?e.freqs[a]+=s:0!=a?e.freqs[No.Repeat3To6]++:s<=10?e.freqs[No.Repeat3To10]++:e.freqs[No.Repeat11To138]++}}setStaticCodes(e,t){this.codes=e,this.length=t}buildCodes(){let e=new Int32Array(this.maxLength),t=0;this.codes=new Int16Array(this.freqs.length);for(let i=0;i<this.maxLength;i++)e[i]=t,t+=this.bitLengthCounts[i]<<15-i;for(let t=0;t<this.numCodes;t++){let i=this.length[t];i>0&&(this.codes[t]=xo.bitReverse(e[i-1]),e[i-1]+=1<<16-i)}}writeTree(e){let t,i,s,a=-1,r=0;for(;r<this.numCodes;){s=1;let n=this.length[r];for(0==n?(t=138,i=3):(t=6,i=3,a!=n&&(e.writeSymbol(n),s=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++s>=t)););if(s<i)for(;s-- >0;)e.writeSymbol(a);else 0!=a?(e.writeSymbol(No.Repeat3To6),this.huffman.pending.writeBits(s-3,2)):s<=10?(e.writeSymbol(No.Repeat3To10),this.huffman.pending.writeBits(s-3,3)):(e.writeSymbol(No.Repeat11To138),this.huffman.pending.writeBits(s-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}No.Repeat3To6=16,No.Repeat3To10=17,No.Repeat11To138=18;class xo{constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new No(this,xo.LITERAL_NUM,257,15),this.distTree=new No(this,xo.DIST_NUM,1,15),this.blTree=new No(this,xo.BITLEN_NUM,4,7),this.d_buf=new Int16Array(xo.BUFSIZE),this.l_buf=new Uint8Array(xo.BUFSIZE)}static staticInit(){let e=0;for(;e<144;)xo.staticLCodes[e]=xo.bitReverse(48+e<<8),xo.staticLLength[e++]=8;for(;e<256;)xo.staticLCodes[e]=xo.bitReverse(256+e<<7),xo.staticLLength[e++]=9;for(;e<280;)xo.staticLCodes[e]=xo.bitReverse(-256+e<<9),xo.staticLLength[e++]=7;for(;e<xo.LITERAL_NUM;)xo.staticLCodes[e]=xo.bitReverse(-88+e<<8),xo.staticLLength[e++]=8;for(e=0;e<xo.DIST_NUM;e++)xo.staticDCodes[e]=xo.bitReverse(e<<11),xo.staticDLength[e]=5}static bitReverse(e){return xo.bit4Reverse[15&e]<<12|xo.bit4Reverse[e>>4&15]<<8|xo.bit4Reverse[e>>8&15]<<4|xo.bit4Reverse[e>>12]}isFull(){return this.last_lit>=xo.BUFSIZE}reset(){this.last_lit=0,this.extra_bits=0,this.literalTree.reset(),this.distTree.reset(),this.blTree.reset()}flushStoredBlock(e,t,i,s){this.pending.writeBits((xo.STORED_BLOCK<<1)+(s?1:0),3),this.pending.alignToByte(),this.pending.writeShort(i),this.pending.writeShort(~i),this.pending.writeBlock(e,t,i),this.reset()}flushBlock(e,t,i,s){this.literalTree.freqs[xo.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[xo.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<xo.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*xo.staticLLength[e];for(let e=0;e<xo.DIST_NUM;e++)n+=this.distTree.freqs[e]*xo.staticDLength[e];r>=n&&(r=n),t>=0&&i+4<r>>3?this.flushStoredBlock(e,t,i,s):r==n?(this.pending.writeBits((xo.STATIC_TREES<<1)+(s?1:0),3),this.literalTree.setStaticCodes(xo.staticLCodes,xo.staticLLength),this.distTree.setStaticCodes(xo.staticDCodes,xo.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((xo.DYN_TREES<<1)+(s?1:0),3),this.sendAllTrees(a),this.compressBlock(),this.reset())}sendAllTrees(e){this.blTree.buildCodes(),this.literalTree.buildCodes(),this.distTree.buildCodes(),this.pending.writeBits(this.literalTree.numCodes-257,5),this.pending.writeBits(this.distTree.numCodes-1,5),this.pending.writeBits(e-4,4);for(let t=0;t<e;t++)this.pending.writeBits(this.blTree.length[xo.BL_ORDER[t]],3);this.literalTree.writeTree(this.blTree),this.distTree.writeTree(this.blTree)}compressBlock(){for(let e=0;e<this.last_lit;e++){let t=255&this.l_buf[e],i=this.d_buf[e];if(0!=i--){let e=xo.Lcode(t);this.literalTree.writeSymbol(e);let s=Math.floor((e-261)/4);s>0&&s<=5&&this.pending.writeBits(t&(1<<s)-1,s);let a=xo.Dcode(i);this.distTree.writeSymbol(a),s=Math.floor(a/2)-1,s>0&&this.pending.writeBits(i&(1<<s)-1,s)}else this.literalTree.writeSymbol(t)}this.literalTree.writeSymbol(xo.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let i=xo.Lcode(t-3);this.literalTree.freqs[i]++,i>=265&&i<285&&(this.extra_bits+=Math.floor((i-261)/4));let s=xo.Dcode(e-1);return this.distTree.freqs[s]++,s>=4&&(this.extra_bits+=Math.floor(s/2)-1),this.isFull()}tallyLit(e){return this.d_buf[this.last_lit]=0,this.l_buf[this.last_lit++]=e,this.literalTree.freqs[e]++,this.isFull()}static Lcode(e){if(255==e)return 285;let t=257;for(;e>=8;)t+=4,e>>=1;return t+e}static Dcode(e){let t=0;for(;e>=4;)t+=2,e>>=1;return t+e}}xo.BUFSIZE=1<<vo.DEFAULT_MEM_LEVEL+6,xo.LITERAL_NUM=286,xo.STORED_BLOCK=0,xo.STATIC_TREES=1,xo.DYN_TREES=2,xo.DIST_NUM=30,xo.staticLCodes=new Int16Array(xo.LITERAL_NUM),xo.staticLLength=new Uint8Array(xo.LITERAL_NUM),xo.staticDCodes=new Int16Array(xo.DIST_NUM),xo.staticDLength=new Uint8Array(xo.DIST_NUM),xo.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],xo.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),xo.BITLEN_NUM=19,xo.EOF_SYMBOL=256,xo.staticInit();class Po{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 xo(e),this.inputCrc=new ko,this.window=new Uint8Array(2*vo.WSIZE),this.head=new Int16Array(vo.HASH_SIZE),this.prev=new Int16Array(vo.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=vo.MIN_MATCH-1;for(let e=0;e<vo.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<vo.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<vo.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd==this.inputOff}setInput(e,t,i){let s=t+i;this.inputBuf=e,this.inputOff=t,this.inputEnd=s}deflate(e,t){let i;do{this.fillWindow();let s=e&&this.inputOff==this.inputEnd;i=this.deflateSlow(s,t)}while(this.pending.isFlushed&&i);return i}deflateSlow(e,t){if(this.lookahead<vo.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=vo.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*vo.WSIZE-vo.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,i=this.matchLen;if(this.lookahead>=vo.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=vo.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==vo.MIN_MATCH&&this.strstart-this.matchStart>Po.TooFar&&(this.matchLen=vo.MIN_MATCH-1)}if(i>=vo.MIN_MATCH&&this.matchLen<=i){this.huffman.tallyDist(this.strstart-1-e,i),i-=2;do{this.strstart++,this.lookahead--,this.lookahead>=vo.MIN_MATCH&&this.insertString()}while(--i>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=vo.MIN_MATCH-1}else this.prevAvailable&&this.huffman.tallyLit(255&this.window[this.strstart-1]),this.prevAvailable=!0,this.strstart++,this.lookahead--;if(this.huffman.isFull()){let e=this.strstart-this.blockStart;this.prevAvailable&&e--;let i=t&&0==this.lookahead&&!this.prevAvailable;return this.huffman.flushBlock(this.window,this.blockStart,e,i),this.blockStart+=e,!i}}return!0}findLongestMatch(e){let t,i=this.strstart,s=i+Math.min(vo.MAX_MATCH,this.lookahead)-1,a=Math.max(i-vo.MAX_DIST,0),r=this.window,n=this.prev,o=this.maxChain,h=Math.min(this.niceLength,this.lookahead);if(this.matchLen=Math.max(this.matchLen,vo.MIN_MATCH-1),i+this.matchLen>s)return!1;let l=r[i+this.matchLen-1],d=r[i+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,i=this.strstart,r[t+this.matchLen]==d&&r[t+this.matchLen-1]==l&&r[t]==r[i]&&r[++t]==r[++i]){switch((s-i)%8){case 1:if(r[++i]==r[++t])break;break;case 2:if(r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 3:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 4:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 5:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 6:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 7:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break}if(r[i]==r[t])do{if(i==s){++i,++t;break}}while(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]);if(i-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=i-this.strstart,this.matchLen>=h)break;l=r[i-1],d=r[i]}e=65535&n[e&vo.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=vo.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<vo.HASH_SHIFT^this.window[this.strstart+(vo.MIN_MATCH-1)])&vo.HASH_MASK;return e=this.head[t],this.prev[this.strstart&vo.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=vo.WSIZE+vo.MAX_DIST&&this.slideWindow(),this.lookahead<vo.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*vo.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>=vo.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(vo.WSIZE,vo.WSIZE+vo.WSIZE),0),this.matchStart-=vo.WSIZE,this.strstart-=vo.WSIZE,this.blockStart-=vo.WSIZE;for(let e=0;e<vo.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=vo.WSIZE?t-vo.WSIZE:0}for(let e=0;e<vo.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=vo.WSIZE?t-vo.WSIZE:0}}}Po.TooFar=4096;class Eo{constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}get isFlushed(){return 0===this._end}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,i){this._buffer.set(e.subarray(t,t+i),this._end),this._end+=i}flush(e,t,i){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),i>this._end-this._start?(i=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+i),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+i),t),this._start+=i),i}writeBits(e,t){this._bits|=e<<this.bitCount,this.bitCount+=t,this.bitCount>=16&&(this._buffer[this._end++]=255&this._bits,this._buffer[this._end++]=this._bits>>8&255,this._bits>>=16,this.bitCount-=16)}alignToByte(){this.bitCount>0&&(this._buffer[this._end++]=255&this._bits,this.bitCount>8&&(this._buffer[this._end++]=this._bits>>8&255)),this._bits=0,this.bitCount=0}}class Co{constructor(){this._state=0,this._pending=new Eo(vo.PENDING_BUF_SIZE),this._engine=new Po(this._pending),this.reset()}get inputCrc(){return this._engine.inputCrc.value}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Co.FinishedState&&this._pending.isFlushed}reset(){this._state=Co.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,i){this._engine.setInput(e,t,i)}deflate(e,t,i){let s=i;for(;;){let a=this._pending.flush(e,t,i);if(t+=a,0==(i-=a)||this._state==Co.FinishedState)break;if(!this._engine.deflate(0!=(this._state&Co.IsFlushing),0!=(this._state&Co.IsFinishing)))switch(this._state){case Co.BusyState:return s-i;case Co.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Co.BusyState;break;case Co.FinishingState:this._pending.alignToByte(),this._state=Co.FinishedState}}return s-i}finish(){this._state|=Co.IsFlushing|Co.IsFinishing}}Co.IsFlushing=4,Co.IsFinishing=8,Co.BusyState=16,Co.FlushingState=20,Co.FinishingState=28,Co.FinishedState=30;class Fo{constructor(e,t,i,s,a){this.entry=e,this.crc32=t,this.localHeaderOffset=i,this.compressionMode=s,this.compressedSize=a}}class Lo{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Co,this._data=e}writeEntry(e){const t=yt.CompressionMethodDeflate,i=Ue.empty(),s=this.compress(i,e.data,t),a=i.toArray(),r=new Fo(e,s,this._data.bytesWritten,t,i.length);this._centralDirectoryHeaders.push(r),ze.writeInt32LE(this._data,yt.LocalFileHeaderSignature),ze.writeUInt16LE(this._data,10),ze.writeUInt16LE(this._data,2048),ze.writeUInt16LE(this._data,t),ze.writeInt16LE(this._data,0),ze.writeInt16LE(this._data,0),ze.writeInt32LE(this._data,s),ze.writeInt32LE(this._data,a.length),ze.writeInt32LE(this._data,e.data.length),ze.writeInt16LE(this._data,e.fullName.length),ze.writeInt16LE(this._data,0);const n=ze.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,i){if(i!=yt.CompressionMethodDeflate){const i=new ko;return i.update(t,0,t.length),e.write(t,0,t.length),i.value}{let i=new Uint8Array(512);for(this._deflater.reset(),this._deflater.setInput(t,0,t.length);!this._deflater.isNeedingInput;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}for(this._deflater.finish();!this._deflater.isFinished;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}return this._deflater.inputCrc}}end(){const e=this._data.bytesWritten;for(const e of this._centralDirectoryHeaders)this.writeCentralDirectoryHeader(e);const t=this._data.bytesWritten;this.writeEndOfCentralDirectoryRecord(e,t)}writeEndOfCentralDirectoryRecord(e,t){ze.writeInt32LE(this._data,yt.EndOfCentralDirSignature),ze.writeInt16LE(this._data,0),ze.writeInt16LE(this._data,0),ze.writeInt16LE(this._data,this._centralDirectoryHeaders.length),ze.writeInt16LE(this._data,this._centralDirectoryHeaders.length),ze.writeInt32LE(this._data,t-e),ze.writeInt32LE(this._data,e),ze.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){ze.writeInt32LE(this._data,yt.CentralFileHeaderSignature),ze.writeUInt16LE(this._data,10),ze.writeUInt16LE(this._data,10),ze.writeUInt16LE(this._data,2048),ze.writeUInt16LE(this._data,e.compressionMode),ze.writeInt16LE(this._data,0),ze.writeInt16LE(this._data,0),ze.writeInt32LE(this._data,e.crc32),ze.writeInt32LE(this._data,e.compressedSize),ze.writeInt32LE(this._data,e.entry.data.length),ze.writeInt16LE(this._data,e.entry.fullName.length),ze.writeInt16LE(this._data,0),ze.writeInt16LE(this._data,0),ze.writeInt16LE(this._data,0),ze.writeInt16LE(this._data,0),ze.writeInt32LE(this._data,0),ze.writeInt32LE(this._data,e.localHeaderOffset);const t=ze.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Mo=Object.freeze({__proto__:null,ScoreExporter:wo,Gp7Exporter:class extends wo{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){ge.debug(this.name,"Writing data entries");const t=(new To).writeXml(e),i=$e.writeForScore(e),s=lt.writeForScore(e);ge.debug(this.name,"Writing ZIP entries");let a=new Lo(this.data);a.writeEntry(new yt("VERSION",ze.stringToBytes("7.0"))),a.writeEntry(new yt("Content/",new Uint8Array(0))),a.writeEntry(new yt("Content/BinaryStylesheet",i)),a.writeEntry(new yt("Content/PartConfiguration",s)),a.writeEntry(new yt("Content/score.gpif",ze.stringToBytes(t))),a.end()}}}),Do=Object.freeze({__proto__:null,BeatTickLookup:gs,MasterBarTickLookup:ys,MidiTickLookup:Ss,MidiTickLookupFindBeatResult:bs,MidiFile:ui,get ControllerType(){return ie},MetaDataEvent:pi,MetaEvent:xt,get MetaEventType(){return X},MetaNumberEvent:gi,MidiEvent:Nt,get MidiEventType(){return U},Midi20PerNotePitchBendEvent:Ii,SystemCommonEvent:Pt,get SystemCommonType(){return Y},SystemExclusiveEvent:Et,MidiFileGenerator:Bs,AlphaSynthMidiFileHandler:ps}),Io=Object.freeze({__proto__:null,get AccentuationType(){return a},get AccidentalType(){return Vs},get AutomationType(){return r},Automation:oe,Bar:he,Beat:xe,BendPoint:de,get BendStyle(){return l},get BendType(){return d},get BrushType(){return c},Chord:Pe,get Clef(){return n},Color:Re,get CrescendoType(){return u},get Duration(){return p},get DynamicValue(){return g},get FermataType(){return G},Fermata:Ke,get Fingers(){return m},get FontStyle(){return Z},Font:bi,get GraceType(){return f},get HarmonicType(){return y},InstrumentArticulation:ye,JsonConverter:Zi,get KeySignature(){return M},get KeySignatureType(){return I},Lyrics:Ee,MasterBar:Ce,get MusicFontSymbol(){return P},Note:_e,get NoteAccidentalMode(){return b},get Ottavia(){return o},get PickStroke(){return x},PlaybackInformation:Ae,RenderStylesheet:Fe,RepeatGroup:Le,Score:Me,Section:De,get SimileMark(){return h},get SlideInType(){return S},get SlideOutType(){return _},Staff:Ge,Track:He,get TripletFeel(){return R},Tuning:Oe,TupletGroup:we,get VibratoType(){return w},Voice:Ve,get WhammyType(){return F}}),Ro=Object.freeze({__proto__:null,RenderFinishedEventArgs:ss,ScoreRenderer:ds,BarBounds:as,BeatBounds:rs,Bounds:Qe,BoundsLookup:ls,MasterBarBounds:ns,NoteBounds:os,StaveGroupBounds:hs}),Ao=Object.freeze({__proto__:null,AlphaSynth:ci,CircularSampleBuffer:js,PlaybackRange:Ts,get PlayerState(){return J},PlayerStateChangedEventArgs:It,PlaybackRangeChangedEventArgs:di,PositionChangedEventArgs:Rt,MidiEventsPlayedEventArgs:li,ActiveBeatsChangedEventArgs:Fs,AlphaSynthWebWorkerApi:Zs,AlphaSynthWebAudioOutputBase:Qs,AlphaSynthScriptProcessorOutput:$s,AlphaSynthAudioWorkletOutput:sa});e.AlphaTabApi=na,e.AlphaTabError=re,e.CoreSettings=yo,e.DisplaySettings=_i,e.FileLoadError=Ds,e.FormatError=Ie,e.ImporterSettings=wi,e.Logger=ge,e.NotationSettings=ce,e.PlayerSettings=ki,e.ProgressEventArgs=Ks,e.RenderingResources=Si,e.ResizeEventArgs=Cs,e.Settings=Di,e.VibratoPlaybackSettings=Bi,e.exporter=Mo,e.importer=_o,e.meta=bo,e.midi=Do,e.model=Io,e.rendering=Ro,e.synth=Ao,Object.defineProperty(e,"__esModule",{value:!0})}));