MusicSheetReader.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. import {MusicSheet} from "../MusicSheet";
  2. import {SourceMeasure} from "../VoiceData/SourceMeasure";
  3. import {Fraction} from "../../Common/DataObjects/Fraction";
  4. import {InstrumentReader} from "./InstrumentReader";
  5. import {IXmlElement} from "../../Common/FileIO/Xml";
  6. import {Instrument} from "../Instrument";
  7. import {ITextTranslation} from "../Interfaces/ITextTranslation";
  8. import {MusicSheetReadingException} from "../Exceptions";
  9. import log from "loglevel";
  10. import {IXmlAttribute} from "../../Common/FileIO/Xml";
  11. import {RhythmInstruction} from "../VoiceData/Instructions/RhythmInstruction";
  12. import {RhythmSymbolEnum} from "../VoiceData/Instructions/RhythmInstruction";
  13. import {SourceStaffEntry} from "../VoiceData/SourceStaffEntry";
  14. import {VoiceEntry} from "../VoiceData/VoiceEntry";
  15. import {InstrumentalGroup} from "../InstrumentalGroup";
  16. import {SubInstrument} from "../SubInstrument";
  17. import {MidiInstrument} from "../VoiceData/Instructions/ClefInstruction";
  18. import {AbstractNotationInstruction} from "../VoiceData/Instructions/AbstractNotationInstruction";
  19. import {Label} from "../Label";
  20. import {MusicSymbolModuleFactory} from "./MusicSymbolModuleFactory";
  21. import {IAfterSheetReadingModule} from "../Interfaces/IAfterSheetReadingModule";
  22. import {RepetitionInstructionReader} from "./MusicSymbolModules/RepetitionInstructionReader";
  23. import {RepetitionCalculator} from "./MusicSymbolModules/RepetitionCalculator";
  24. import {EngravingRules} from "../Graphical/EngravingRules";
  25. export class MusicSheetReader /*implements IMusicSheetReader*/ {
  26. constructor(afterSheetReadingModules: IAfterSheetReadingModule[] = undefined, rules: EngravingRules = new EngravingRules()) {
  27. if (!afterSheetReadingModules) {
  28. this.afterSheetReadingModules = [];
  29. } else {
  30. this.afterSheetReadingModules = afterSheetReadingModules;
  31. }
  32. this.repetitionInstructionReader = MusicSymbolModuleFactory.createRepetitionInstructionReader();
  33. this.repetitionCalculator = MusicSymbolModuleFactory.createRepetitionCalculator();
  34. this.rules = rules;
  35. }
  36. private repetitionInstructionReader: RepetitionInstructionReader;
  37. private repetitionCalculator: RepetitionCalculator;
  38. private afterSheetReadingModules: IAfterSheetReadingModule[];
  39. private musicSheet: MusicSheet;
  40. private completeNumberOfStaves: number = 0;
  41. private currentMeasure: SourceMeasure;
  42. private previousMeasure: SourceMeasure;
  43. private currentFraction: Fraction;
  44. public rules: EngravingRules;
  45. public get CompleteNumberOfStaves(): number {
  46. return this.completeNumberOfStaves;
  47. }
  48. private static doCalculationsAfterDurationHasBeenSet(instrumentReaders: InstrumentReader[]): void {
  49. for (const instrumentReader of instrumentReaders) {
  50. instrumentReader.doCalculationsAfterDurationHasBeenSet();
  51. }
  52. }
  53. /**
  54. * Read a music XML file and saves the values in the MusicSheet class.
  55. * @param root
  56. * @param path
  57. * @returns {MusicSheet}
  58. */
  59. public createMusicSheet(root: IXmlElement, path: string): MusicSheet {
  60. try {
  61. return this._createMusicSheet(root, path);
  62. } catch (e) {
  63. log.error("MusicSheetReader.CreateMusicSheet", e);
  64. return undefined;
  65. }
  66. }
  67. private _removeFromArray(list: any[], elem: any): void {
  68. const i: number = list.indexOf(elem);
  69. if (i !== -1) {
  70. list.splice(i, 1);
  71. }
  72. }
  73. // Trim from a string also newlines
  74. private trimString(str: string): string {
  75. return str.replace(/^\s+|\s+$/g, "");
  76. }
  77. private _lastElement<T>(list: T[]): T {
  78. return list[list.length - 1];
  79. }
  80. //public SetPhonicScoreInterface(phonicScoreInterface: IPhonicScoreInterface): void {
  81. // this.phonicScoreInterface = phonicScoreInterface;
  82. //}
  83. //public ReadMusicSheetParameters(sheetObject: MusicSheetParameterObject, root: IXmlElement, path: string): MusicSheetParameterObject {
  84. // this.musicSheet = new MusicSheet();
  85. // if (root) {
  86. // this.pushSheetLabels(root, path);
  87. // if (this.musicSheet.Title) {
  88. // sheetObject.Title = this.musicSheet.Title.text;
  89. // }
  90. // if (this.musicSheet.Composer) {
  91. // sheetObject.Composer = this.musicSheet.Composer.text;
  92. // }
  93. // if (this.musicSheet.Lyricist) {
  94. // sheetObject.Lyricist = this.musicSheet.Lyricist.text;
  95. // }
  96. // let partlistNode: IXmlElement = root.element("part-list");
  97. // let partList: IXmlElement[] = partlistNode.elements();
  98. // this.createInstrumentGroups(partList);
  99. // for (let idx: number = 0, len: number = this.musicSheet.Instruments.length; idx < len; ++idx) {
  100. // let instr: Instrument = this.musicSheet.Instruments[idx];
  101. // sheetObject.InstrumentList.push(__init(new MusicSheetParameterObject.LibrarySheetInstrument(), { name: instr.name }));
  102. // }
  103. // }
  104. // return sheetObject;
  105. //}
  106. private _createMusicSheet(root: IXmlElement, path: string): MusicSheet {
  107. const instrumentReaders: InstrumentReader[] = [];
  108. let sourceMeasureCounter: number = 0;
  109. this.musicSheet = new MusicSheet();
  110. this.musicSheet.Path = path;
  111. this.musicSheet.Rules = this.rules;
  112. if (!root) {
  113. throw new MusicSheetReadingException("Undefined root element");
  114. }
  115. this.pushSheetLabels(root, path);
  116. const partlistNode: IXmlElement = root.element("part-list");
  117. if (!partlistNode) {
  118. throw new MusicSheetReadingException("Undefined partListNode");
  119. }
  120. const partInst: IXmlElement[] = root.elements("part");
  121. const partList: IXmlElement[] = partlistNode.elements();
  122. this.initializeReading(partList, partInst, instrumentReaders);
  123. let couldReadMeasure: boolean = true;
  124. this.currentFraction = new Fraction(0, 1);
  125. let guitarPro: boolean = false;
  126. let encoding: IXmlElement = root.element("identification");
  127. if (encoding) {
  128. encoding = encoding.element("encoding");
  129. }
  130. if (encoding) {
  131. encoding = encoding.element("software");
  132. }
  133. if (encoding !== undefined && encoding.value === "Guitar Pro 5") {
  134. guitarPro = true;
  135. }
  136. while (couldReadMeasure) {
  137. // TODO changing this.rules.PartAndSystemAfterFinalBarline requires a reload of the piece for measure numbers to be updated
  138. if (this.currentMeasure !== undefined && this.currentMeasure.HasEndLine && this.rules.NewPartAndSystemAfterFinalBarline) {
  139. sourceMeasureCounter = 0;
  140. }
  141. this.currentMeasure = new SourceMeasure(this.completeNumberOfStaves, this.musicSheet.Rules);
  142. for (const instrumentReader of instrumentReaders) {
  143. try {
  144. couldReadMeasure = couldReadMeasure && instrumentReader.readNextXmlMeasure(this.currentMeasure, this.currentFraction, guitarPro);
  145. } catch (e) {
  146. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/InstrumentError", "Error while reading instruments.");
  147. throw new MusicSheetReadingException(errorMsg, e);
  148. }
  149. }
  150. if (couldReadMeasure) {
  151. this.musicSheet.addMeasure(this.currentMeasure);
  152. this.checkIfRhythmInstructionsAreSetAndEqual(instrumentReaders);
  153. this.checkSourceMeasureForNullEntries();
  154. sourceMeasureCounter = this.setSourceMeasureDuration(instrumentReaders, sourceMeasureCounter);
  155. MusicSheetReader.doCalculationsAfterDurationHasBeenSet(instrumentReaders);
  156. this.currentMeasure.AbsoluteTimestamp = this.currentFraction.clone();
  157. this.musicSheet.SheetErrors.finalizeMeasure(this.currentMeasure.MeasureNumber);
  158. this.currentFraction.Add(this.currentMeasure.Duration);
  159. this.previousMeasure = this.currentMeasure;
  160. }
  161. }
  162. if (this.repetitionInstructionReader) {
  163. this.repetitionInstructionReader.removeRedundantInstructions();
  164. if (this.repetitionCalculator) {
  165. this.repetitionCalculator.calculateRepetitions(this.musicSheet, this.repetitionInstructionReader.repetitionInstructions);
  166. }
  167. }
  168. this.musicSheet.checkForInstrumentWithNoVoice();
  169. this.musicSheet.fillStaffList();
  170. //this.musicSheet.DefaultStartTempoInBpm = this.musicSheet.SheetPlaybackSetting.BeatsPerMinute;
  171. for (let idx: number = 0, len: number = this.afterSheetReadingModules.length; idx < len; ++idx) {
  172. const afterSheetReadingModule: IAfterSheetReadingModule = this.afterSheetReadingModules[idx];
  173. afterSheetReadingModule.calculate(this.musicSheet);
  174. }
  175. //this.musicSheet.DefaultStartTempoInBpm = this.musicSheet.SourceMeasures[0].TempoInBPM;
  176. this.musicSheet.userStartTempoInBPM = this.musicSheet.userStartTempoInBPM || this.musicSheet.DefaultStartTempoInBpm;
  177. return this.musicSheet;
  178. }
  179. private initializeReading(partList: IXmlElement[], partInst: IXmlElement[], instrumentReaders: InstrumentReader[]): void {
  180. const instrumentDict: { [_: string]: Instrument } = this.createInstrumentGroups(partList);
  181. this.completeNumberOfStaves = this.getCompleteNumberOfStavesFromXml(partInst);
  182. if (partInst.length !== 0) {
  183. this.repetitionInstructionReader.MusicSheet = this.musicSheet;
  184. this.currentFraction = new Fraction(0, 1);
  185. this.currentMeasure = undefined;
  186. this.previousMeasure = undefined;
  187. }
  188. let counter: number = 0;
  189. for (const node of partInst) {
  190. const idNode: IXmlAttribute = node.attribute("id");
  191. if (idNode) {
  192. const currentInstrument: Instrument = instrumentDict[idNode.value];
  193. const xmlMeasureList: IXmlElement[] = node.elements("measure");
  194. let instrumentNumberOfStaves: number = 1;
  195. try {
  196. instrumentNumberOfStaves = this.getInstrumentNumberOfStavesFromXml(node);
  197. } catch (err) {
  198. const errorMsg: string = ITextTranslation.translateText(
  199. "ReaderErrorMessages/InstrumentStavesNumberError",
  200. "Invalid number of staves at instrument: "
  201. );
  202. this.musicSheet.SheetErrors.push(errorMsg + currentInstrument.Name);
  203. continue;
  204. }
  205. currentInstrument.createStaves(instrumentNumberOfStaves);
  206. instrumentReaders.push(new InstrumentReader(this.repetitionInstructionReader, xmlMeasureList, currentInstrument));
  207. if (this.repetitionInstructionReader) {
  208. this.repetitionInstructionReader.xmlMeasureList[counter] = xmlMeasureList;
  209. }
  210. counter++;
  211. }
  212. }
  213. }
  214. /**
  215. * Check if all (should there be any apart from the first Measure) [[RhythmInstruction]]s in the [[SourceMeasure]] are the same.
  216. *
  217. * If not, then the max [[RhythmInstruction]] (Fraction) is set to all staves.
  218. * Also, if it happens to have the same [[RhythmInstruction]]s in RealValue but given in Symbol AND Fraction, then the Fraction prevails.
  219. * @param instrumentReaders
  220. */
  221. private checkIfRhythmInstructionsAreSetAndEqual(instrumentReaders: InstrumentReader[]): void {
  222. const rhythmInstructions: RhythmInstruction[] = [];
  223. for (let i: number = 0; i < this.completeNumberOfStaves; i++) {
  224. if (this.currentMeasure.FirstInstructionsStaffEntries[i]) {
  225. const last: AbstractNotationInstruction = this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions[
  226. this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions.length - 1
  227. ];
  228. if (last instanceof RhythmInstruction) {
  229. rhythmInstructions.push(<RhythmInstruction>last);
  230. }
  231. }
  232. }
  233. let maxRhythmValue: number = 0.0;
  234. let index: number = -1;
  235. for (let idx: number = 0, len: number = rhythmInstructions.length; idx < len; ++idx) {
  236. const rhythmInstruction: RhythmInstruction = rhythmInstructions[idx];
  237. if (rhythmInstruction.Rhythm.RealValue > maxRhythmValue) {
  238. if (this.areRhythmInstructionsMixed(rhythmInstructions) && rhythmInstruction.SymbolEnum !== RhythmSymbolEnum.NONE) {
  239. continue;
  240. }
  241. maxRhythmValue = rhythmInstruction.Rhythm.RealValue;
  242. index = rhythmInstructions.indexOf(rhythmInstruction);
  243. }
  244. }
  245. if (rhythmInstructions.length > 0 && rhythmInstructions.length < this.completeNumberOfStaves) {
  246. const rhythmInstruction: RhythmInstruction = rhythmInstructions[index].clone();
  247. for (let i: number = 0; i < this.completeNumberOfStaves; i++) {
  248. if (
  249. this.currentMeasure.FirstInstructionsStaffEntries[i] !== undefined &&
  250. !(this._lastElement(this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions) instanceof RhythmInstruction)
  251. ) {
  252. this.currentMeasure.FirstInstructionsStaffEntries[i].removeAllInstructionsOfTypeRhythmInstruction();
  253. this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions.push(rhythmInstruction.clone());
  254. }
  255. if (!this.currentMeasure.FirstInstructionsStaffEntries[i]) {
  256. this.currentMeasure.FirstInstructionsStaffEntries[i] = new SourceStaffEntry(undefined, undefined);
  257. this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions.push(rhythmInstruction.clone());
  258. }
  259. }
  260. for (let idx: number = 0, len: number = instrumentReaders.length; idx < len; ++idx) {
  261. const instrumentReader: InstrumentReader = instrumentReaders[idx];
  262. instrumentReader.ActiveRhythm = rhythmInstruction;
  263. }
  264. }
  265. if (rhythmInstructions.length === 0 && this.currentMeasure === this.musicSheet.SourceMeasures[0]) {
  266. const rhythmInstruction: RhythmInstruction = new RhythmInstruction(new Fraction(4, 4, 0, false), RhythmSymbolEnum.NONE);
  267. for (let i: number = 0; i < this.completeNumberOfStaves; i++) {
  268. if (!this.currentMeasure.FirstInstructionsStaffEntries[i]) {
  269. this.currentMeasure.FirstInstructionsStaffEntries[i] = new SourceStaffEntry(undefined, undefined);
  270. } else {
  271. this.currentMeasure.FirstInstructionsStaffEntries[i].removeAllInstructionsOfTypeRhythmInstruction();
  272. }
  273. this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions.push(rhythmInstruction);
  274. }
  275. for (let idx: number = 0, len: number = instrumentReaders.length; idx < len; ++idx) {
  276. const instrumentReader: InstrumentReader = instrumentReaders[idx];
  277. instrumentReader.ActiveRhythm = rhythmInstruction;
  278. }
  279. }
  280. for (let idx: number = 0, len: number = rhythmInstructions.length; idx < len; ++idx) {
  281. const rhythmInstruction: RhythmInstruction = rhythmInstructions[idx];
  282. if (rhythmInstruction.Rhythm.RealValue < maxRhythmValue) {
  283. if (this._lastElement(
  284. this.currentMeasure.FirstInstructionsStaffEntries[rhythmInstructions.indexOf(rhythmInstruction)].Instructions
  285. ) instanceof RhythmInstruction) {
  286. // TODO Test correctness
  287. const instrs: AbstractNotationInstruction[] =
  288. this.currentMeasure.FirstInstructionsStaffEntries[rhythmInstructions.indexOf(rhythmInstruction)].Instructions;
  289. instrs[instrs.length - 1] = rhythmInstructions[index].clone();
  290. }
  291. }
  292. if (
  293. Math.abs(rhythmInstruction.Rhythm.RealValue - maxRhythmValue) < 0.000001 &&
  294. rhythmInstruction.SymbolEnum !== RhythmSymbolEnum.NONE &&
  295. this.areRhythmInstructionsMixed(rhythmInstructions)
  296. ) {
  297. rhythmInstruction.SymbolEnum = RhythmSymbolEnum.NONE;
  298. }
  299. }
  300. }
  301. /**
  302. * True in case of 4/4 and COMMON TIME (or 2/2 and CUT TIME)
  303. * @param rhythmInstructions
  304. * @returns {boolean}
  305. */
  306. private areRhythmInstructionsMixed(rhythmInstructions: RhythmInstruction[]): boolean {
  307. for (let i: number = 1; i < rhythmInstructions.length; i++) {
  308. if (
  309. Math.abs(rhythmInstructions[i].Rhythm.RealValue - rhythmInstructions[0].Rhythm.RealValue) < 0.000001 &&
  310. rhythmInstructions[i].SymbolEnum !== rhythmInstructions[0].SymbolEnum
  311. ) {
  312. return true;
  313. }
  314. }
  315. return false;
  316. }
  317. /**
  318. * Set the [[Measure]]'s duration taking into account the longest [[Instrument]] duration and the active Rhythm read from XML.
  319. * @param instrumentReaders
  320. * @param sourceMeasureCounter
  321. * @returns {number}
  322. */
  323. private setSourceMeasureDuration(instrumentReaders: InstrumentReader[], sourceMeasureCounter: number): number {
  324. let activeRhythm: Fraction = new Fraction(0, 1);
  325. const instrumentsMaxTieNoteFractions: Fraction[] = [];
  326. for (const instrumentReader of instrumentReaders) {
  327. instrumentsMaxTieNoteFractions.push(instrumentReader.MaxTieNoteFraction);
  328. const activeRythmMeasure: Fraction = instrumentReader.ActiveRhythm.Rhythm;
  329. if (activeRhythm.lt(activeRythmMeasure)) {
  330. activeRhythm = new Fraction(activeRythmMeasure.Numerator, activeRythmMeasure.Denominator, 0, false);
  331. }
  332. }
  333. const instrumentsDurations: Fraction[] = this.currentMeasure.calculateInstrumentsDuration(this.musicSheet, instrumentsMaxTieNoteFractions);
  334. let maxInstrumentDuration: Fraction = new Fraction(0, 1);
  335. for (const instrumentsDuration of instrumentsDurations) {
  336. if (maxInstrumentDuration.lt(instrumentsDuration)) {
  337. maxInstrumentDuration = instrumentsDuration;
  338. }
  339. }
  340. if (Fraction.Equal(maxInstrumentDuration, activeRhythm)) {
  341. this.checkFractionsForEquivalence(maxInstrumentDuration, activeRhythm);
  342. } else {
  343. if (maxInstrumentDuration.lt(activeRhythm)) {
  344. maxInstrumentDuration = this.currentMeasure.reverseCheck(this.musicSheet, maxInstrumentDuration);
  345. this.checkFractionsForEquivalence(maxInstrumentDuration, activeRhythm);
  346. }
  347. }
  348. this.currentMeasure.ImplicitMeasure = this.checkIfMeasureIsImplicit(maxInstrumentDuration, activeRhythm);
  349. if (!this.currentMeasure.ImplicitMeasure) {
  350. sourceMeasureCounter++;
  351. }
  352. this.currentMeasure.Duration = maxInstrumentDuration; // can be 1/1 in a 4/4 time signature
  353. this.currentMeasure.ActiveTimeSignature = activeRhythm;
  354. this.currentMeasure.MeasureNumber = sourceMeasureCounter;
  355. for (let i: number = 0; i < instrumentsDurations.length; i++) {
  356. const instrumentsDuration: Fraction = instrumentsDurations[i];
  357. if (
  358. (this.currentMeasure.ImplicitMeasure && instrumentsDuration !== maxInstrumentDuration) ||
  359. !Fraction.Equal(instrumentsDuration, activeRhythm) &&
  360. !this.allInstrumentsHaveSameDuration(instrumentsDurations, maxInstrumentDuration)
  361. ) {
  362. const firstStaffIndexOfInstrument: number = this.musicSheet.getGlobalStaffIndexOfFirstStaff(this.musicSheet.Instruments[i]);
  363. for (let staffIndex: number = 0; staffIndex < this.musicSheet.Instruments[i].Staves.length; staffIndex++) {
  364. if (!this.graphicalMeasureIsEmpty(firstStaffIndexOfInstrument + staffIndex)) {
  365. this.currentMeasure.setErrorInGraphicalMeasure(firstStaffIndexOfInstrument + staffIndex, true);
  366. const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/MissingNotesError",
  367. "Given Notes don't correspond to measure duration.");
  368. this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
  369. }
  370. }
  371. }
  372. }
  373. return sourceMeasureCounter;
  374. }
  375. /**
  376. * Check the Fractions for Equivalence and if so, sets maxInstrumentDuration's members accordingly.
  377. * *
  378. * Example: if maxInstrumentDuration = 1/1 and sourceMeasureDuration = 4/4, maxInstrumentDuration becomes 4/4.
  379. * @param maxInstrumentDuration
  380. * @param activeRhythm
  381. */
  382. private checkFractionsForEquivalence(maxInstrumentDuration: Fraction, activeRhythm: Fraction): void {
  383. if (activeRhythm.Denominator > maxInstrumentDuration.Denominator) {
  384. const factor: number = activeRhythm.Denominator / maxInstrumentDuration.Denominator;
  385. maxInstrumentDuration.expand(factor);
  386. }
  387. }
  388. /**
  389. * Handle the case of an implicit [[SourceMeasure]].
  390. * @param maxInstrumentDuration
  391. * @param activeRhythm
  392. * @returns {boolean}
  393. */
  394. private checkIfMeasureIsImplicit(maxInstrumentDuration: Fraction, activeRhythm: Fraction): boolean {
  395. if (!this.previousMeasure && maxInstrumentDuration.lt(activeRhythm)) {
  396. return true;
  397. }
  398. if (this.previousMeasure) {
  399. return Fraction.plus(this.previousMeasure.Duration, maxInstrumentDuration).Equals(activeRhythm);
  400. }
  401. return false;
  402. }
  403. /**
  404. * Check the Duration of all the given Instruments.
  405. * @param instrumentsDurations
  406. * @param maxInstrumentDuration
  407. * @returns {boolean}
  408. */
  409. private allInstrumentsHaveSameDuration(instrumentsDurations: Fraction[], maxInstrumentDuration: Fraction): boolean {
  410. let counter: number = 0;
  411. for (let idx: number = 0, len: number = instrumentsDurations.length; idx < len; ++idx) {
  412. const instrumentsDuration: Fraction = instrumentsDurations[idx];
  413. if (instrumentsDuration.Equals(maxInstrumentDuration)) {
  414. counter++;
  415. }
  416. }
  417. return (counter === instrumentsDurations.length && maxInstrumentDuration !== new Fraction(0, 1));
  418. }
  419. private graphicalMeasureIsEmpty(index: number): boolean {
  420. let counter: number = 0;
  421. for (let i: number = 0; i < this.currentMeasure.VerticalSourceStaffEntryContainers.length; i++) {
  422. if (!this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries[index]) {
  423. counter++;
  424. }
  425. }
  426. return (counter === this.currentMeasure.VerticalSourceStaffEntryContainers.length);
  427. }
  428. /**
  429. * Check a [[SourceMeasure]] for possible empty / undefined entries ([[VoiceEntry]], [[SourceStaffEntry]], VerticalContainer)
  430. * (caused from TieAlgorithm removing EndTieNote) and removes them if completely empty / null
  431. */
  432. private checkSourceMeasureForNullEntries(): void {
  433. for (let i: number = this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1; i >= 0; i--) {
  434. for (let j: number = this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries.length - 1; j >= 0; j--) {
  435. const sourceStaffEntry: SourceStaffEntry = this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries[j];
  436. if (sourceStaffEntry) {
  437. for (let k: number = sourceStaffEntry.VoiceEntries.length - 1; k >= 0; k--) {
  438. const voiceEntry: VoiceEntry = sourceStaffEntry.VoiceEntries[k];
  439. if (voiceEntry.Notes.length === 0) {
  440. this._removeFromArray(voiceEntry.ParentVoice.VoiceEntries, voiceEntry);
  441. this._removeFromArray(sourceStaffEntry.VoiceEntries, voiceEntry);
  442. }
  443. }
  444. }
  445. if (sourceStaffEntry !== undefined && sourceStaffEntry.VoiceEntries.length === 0) {
  446. this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries[j] = undefined;
  447. }
  448. }
  449. }
  450. for (let i: number = this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1; i >= 0; i--) {
  451. let counter: number = 0;
  452. for (let idx: number = 0, len: number = this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries.length; idx < len; ++idx) {
  453. const sourceStaffEntry: SourceStaffEntry = this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries[idx];
  454. if (!sourceStaffEntry) {
  455. counter++;
  456. }
  457. }
  458. if (counter === this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries.length) {
  459. this._removeFromArray(this.currentMeasure.VerticalSourceStaffEntryContainers, this.currentMeasure.VerticalSourceStaffEntryContainers[i]);
  460. }
  461. }
  462. }
  463. /**
  464. * Read the XML file and creates the main sheet Labels.
  465. * @param root
  466. * @param filePath
  467. */
  468. private pushSheetLabels(root: IXmlElement, filePath: string): void {
  469. this.readComposer(root);
  470. this.readTitle(root);
  471. try {
  472. if (!this.musicSheet.Title || !this.musicSheet.Composer) {
  473. this.readTitleAndComposerFromCredits(root); // this can also throw an error
  474. }
  475. } catch (ex) {
  476. log.info("MusicSheetReader.pushSheetLabels", "readTitleAndComposerFromCredits", ex);
  477. }
  478. try {
  479. if (!this.musicSheet.Title) {
  480. const barI: number = Math.max(
  481. 0, filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")
  482. );
  483. const filename: string = filePath.substr(barI);
  484. const filenameSplits: string[] = filename.split(".", 1);
  485. this.musicSheet.Title = new Label(filenameSplits[0]);
  486. }
  487. } catch (ex) {
  488. log.info("MusicSheetReader.pushSheetLabels", "read title from file name", ex);
  489. }
  490. }
  491. // Checks whether _elem_ has an attribute with value _val_.
  492. private presentAttrsWithValue(elem: IXmlElement, val: string): boolean {
  493. for (const attr of elem.attributes()) {
  494. if (attr.value === val) {
  495. return true;
  496. }
  497. }
  498. return false;
  499. }
  500. private readComposer(root: IXmlElement): void {
  501. const identificationNode: IXmlElement = root.element("identification");
  502. if (identificationNode) {
  503. const creators: IXmlElement[] = identificationNode.elements("creator");
  504. for (let idx: number = 0, len: number = creators.length; idx < len; ++idx) {
  505. const creator: IXmlElement = creators[idx];
  506. if (creator.hasAttributes) {
  507. if (this.presentAttrsWithValue(creator, "composer")) {
  508. this.musicSheet.Composer = new Label(this.trimString(creator.value));
  509. continue;
  510. }
  511. if (this.presentAttrsWithValue(creator, "lyricist") || this.presentAttrsWithValue(creator, "poet")) {
  512. this.musicSheet.Lyricist = new Label(this.trimString(creator.value));
  513. }
  514. }
  515. }
  516. }
  517. }
  518. private readTitleAndComposerFromCredits(root: IXmlElement): void {
  519. const systemYCoordinates: number = this.computeSystemYCoordinates(root);
  520. if (systemYCoordinates === 0) {
  521. return;
  522. }
  523. let largestTitleCreditSize: number = 1;
  524. let finalTitle: string = undefined;
  525. let largestCreditYInfo: number = 0;
  526. let finalSubtitle: string = undefined;
  527. let possibleTitle: string = undefined;
  528. const creditElements: IXmlElement[] = root.elements("credit");
  529. for (let idx: number = 0, len: number = creditElements.length; idx < len; ++idx) {
  530. const credit: IXmlElement = creditElements[idx];
  531. if (!credit.attribute("page")) {
  532. return;
  533. }
  534. if (credit.attribute("page").value === "1") {
  535. let creditChild: IXmlElement = undefined;
  536. if (credit) {
  537. creditChild = credit.element("credit-words");
  538. if (!creditChild.attribute("justify")) {
  539. break;
  540. }
  541. const creditJustify: string = creditChild.attribute("justify")?.value;
  542. const creditY: string = creditChild.attribute("default-y")?.value;
  543. // eslint-disable-next-line no-null/no-null
  544. const creditYGiven: boolean = creditY !== undefined && creditY !== null;
  545. const creditYInfo: number = creditYGiven ? parseFloat(creditY) : Number.MIN_VALUE;
  546. if (creditYGiven && creditYInfo > systemYCoordinates) {
  547. if (!this.musicSheet.Title) {
  548. const creditSize: string = creditChild.attribute("font-size").value;
  549. const titleCreditSizeInt: number = parseFloat(creditSize);
  550. if (largestTitleCreditSize < titleCreditSizeInt) {
  551. largestTitleCreditSize = titleCreditSizeInt;
  552. finalTitle = creditChild.value;
  553. }
  554. }
  555. if (!this.musicSheet.Subtitle) {
  556. if (creditJustify !== "right" && creditJustify !== "left") {
  557. if (largestCreditYInfo < creditYInfo) {
  558. largestCreditYInfo = creditYInfo;
  559. if (possibleTitle) {
  560. finalSubtitle = possibleTitle;
  561. possibleTitle = creditChild.value;
  562. } else {
  563. possibleTitle = creditChild.value;
  564. }
  565. }
  566. }
  567. }
  568. if (!(this.musicSheet.Composer !== undefined && this.musicSheet.Lyricist)) {
  569. switch (creditJustify) {
  570. case "right":
  571. this.musicSheet.Composer = new Label(this.trimString(creditChild.value));
  572. break;
  573. case "left":
  574. this.musicSheet.Lyricist = new Label(this.trimString(creditChild.value));
  575. break;
  576. default:
  577. break;
  578. }
  579. }
  580. }
  581. }
  582. }
  583. }
  584. if (!this.musicSheet.Title && finalTitle) {
  585. this.musicSheet.Title = new Label(this.trimString(finalTitle));
  586. }
  587. if (!this.musicSheet.Subtitle && finalSubtitle) {
  588. this.musicSheet.Subtitle = new Label(this.trimString(finalSubtitle));
  589. }
  590. }
  591. private computeSystemYCoordinates(root: IXmlElement): number {
  592. if (!root.element("defaults")) {
  593. return 0;
  594. }
  595. let paperHeight: number = 0;
  596. let topSystemDistance: number = 0;
  597. try {
  598. const defi: string = root.element("defaults").element("page-layout").element("page-height").value;
  599. paperHeight = parseFloat(defi);
  600. } catch (e) {
  601. log.info("MusicSheetReader.computeSystemYCoordinates(): couldn't find page height, not reading title/composer.");
  602. return 0;
  603. }
  604. let found: boolean = false;
  605. const parts: IXmlElement[] = root.elements("part");
  606. for (let idx: number = 0, len: number = parts.length; idx < len; ++idx) {
  607. const measures: IXmlElement[] = parts[idx].elements("measure");
  608. for (let idx2: number = 0, len2: number = measures.length; idx2 < len2; ++idx2) {
  609. const measure: IXmlElement = measures[idx2];
  610. if (measure.element("print")) {
  611. const systemLayouts: IXmlElement[] = measure.element("print").elements("system-layout");
  612. for (let idx3: number = 0, len3: number = systemLayouts.length; idx3 < len3; ++idx3) {
  613. const syslab: IXmlElement = systemLayouts[idx3];
  614. if (syslab.element("top-system-distance")) {
  615. const topSystemDistanceString: string = syslab.element("top-system-distance").value;
  616. topSystemDistance = parseFloat(topSystemDistanceString);
  617. found = true;
  618. break;
  619. }
  620. }
  621. break;
  622. }
  623. }
  624. if (found) {
  625. break;
  626. }
  627. }
  628. if (root.element("defaults").element("system-layout")) {
  629. const syslay: IXmlElement = root.element("defaults").element("system-layout");
  630. if (syslay.element("top-system-distance")) {
  631. const topSystemDistanceString: string = root.element("defaults").element("system-layout").element("top-system-distance").value;
  632. topSystemDistance = parseFloat(topSystemDistanceString);
  633. }
  634. }
  635. if (topSystemDistance === 0) {
  636. return 0;
  637. }
  638. return paperHeight - topSystemDistance;
  639. }
  640. private readTitle(root: IXmlElement): void {
  641. const titleNode: IXmlElement = root.element("work");
  642. let titleNodeChild: IXmlElement = undefined;
  643. if (titleNode) {
  644. titleNodeChild = titleNode.element("work-title");
  645. if (titleNodeChild && titleNodeChild.value) {
  646. this.musicSheet.Title = new Label(this.trimString(titleNodeChild.value));
  647. }
  648. }
  649. const movementNode: IXmlElement = root.element("movement-title");
  650. let finalSubTitle: string = "";
  651. if (movementNode) {
  652. if (!this.musicSheet.Title) {
  653. this.musicSheet.Title = new Label(this.trimString(movementNode.value));
  654. } else {
  655. finalSubTitle = this.trimString(movementNode.value);
  656. }
  657. }
  658. if (titleNode) {
  659. const subtitleNodeChild: IXmlElement = titleNode.element("work-number");
  660. if (subtitleNodeChild) {
  661. const workNumber: string = subtitleNodeChild.value;
  662. if (workNumber) {
  663. if (finalSubTitle === "") {
  664. finalSubTitle = workNumber;
  665. } else {
  666. finalSubTitle = finalSubTitle + ", " + workNumber;
  667. }
  668. }
  669. }
  670. }
  671. if (finalSubTitle
  672. ) {
  673. this.musicSheet.Subtitle = new Label(finalSubTitle);
  674. }
  675. }
  676. /**
  677. * Build the [[InstrumentalGroup]]s and [[Instrument]]s.
  678. * @param entryList
  679. * @returns {{}}
  680. */
  681. private createInstrumentGroups(entryList: IXmlElement[]): { [_: string]: Instrument; } {
  682. let instrumentId: number = 0;
  683. const instrumentDict: { [_: string]: Instrument; } = {};
  684. let currentGroup: InstrumentalGroup;
  685. try {
  686. const entryArray: IXmlElement[] = entryList;
  687. for (let idx: number = 0, len: number = entryArray.length; idx < len; ++idx) {
  688. const node: IXmlElement = entryArray[idx];
  689. if (node.name === "score-part") {
  690. const instrIdString: string = node.attribute("id").value;
  691. const instrument: Instrument = new Instrument(instrumentId, instrIdString, this.musicSheet, currentGroup);
  692. instrumentId++;
  693. const partElements: IXmlElement[] = node.elements();
  694. for (let idx2: number = 0, len2: number = partElements.length; idx2 < len2; ++idx2) {
  695. const partElement: IXmlElement = partElements[idx2];
  696. try {
  697. if (partElement.name === "part-name") {
  698. instrument.Name = partElement.value;
  699. if (partElement.attribute("print-object") &&
  700. partElement.attribute("print-object").value === "no") {
  701. instrument.NameLabel.print = false;
  702. }
  703. } else if (partElement.name === "part-abbreviation") {
  704. instrument.PartAbbreviation = partElement.value;
  705. } else if (partElement.name === "score-instrument") {
  706. const subInstrument: SubInstrument = new SubInstrument(instrument);
  707. subInstrument.idString = partElement.firstAttribute.value;
  708. instrument.SubInstruments.push(subInstrument);
  709. const subElement: IXmlElement = partElement.element("instrument-name");
  710. if (subElement) {
  711. subInstrument.name = subElement.value;
  712. subInstrument.setMidiInstrument(subElement.value);
  713. }
  714. } else if (partElement.name === "midi-instrument") {
  715. let subInstrument: SubInstrument = instrument.getSubInstrument(partElement.firstAttribute.value);
  716. for (let idx3: number = 0, len3: number = instrument.SubInstruments.length; idx3 < len3; ++idx3) {
  717. const subInstr: SubInstrument = instrument.SubInstruments[idx3];
  718. if (subInstr.idString === partElement.value) {
  719. subInstrument = subInstr;
  720. break;
  721. }
  722. }
  723. const instrumentElements: IXmlElement[] = partElement.elements();
  724. for (let idx3: number = 0, len3: number = instrumentElements.length; idx3 < len3; ++idx3) {
  725. const instrumentElement: IXmlElement = instrumentElements[idx3];
  726. try {
  727. if (instrumentElement.name === "midi-channel") {
  728. if (parseInt(instrumentElement.value, 10) === 10) {
  729. instrument.MidiInstrumentId = MidiInstrument.Percussion;
  730. }
  731. } else if (instrumentElement.name === "midi-program") {
  732. if (instrument.SubInstruments.length > 0 && instrument.MidiInstrumentId !== MidiInstrument.Percussion) {
  733. subInstrument.midiInstrumentID = <MidiInstrument>Math.max(0, parseInt(instrumentElement.value, 10) - 1);
  734. }
  735. } else if (instrumentElement.name === "midi-unpitched") {
  736. subInstrument.fixedKey = Math.max(0, parseInt(instrumentElement.value, 10));
  737. } else if (instrumentElement.name === "volume") {
  738. try {
  739. const result: number = parseFloat(instrumentElement.value);
  740. subInstrument.volume = result / 127.0;
  741. } catch (ex) {
  742. log.debug("ExpressionReader.readExpressionParameters", "read volume", ex);
  743. }
  744. } else if (instrumentElement.name === "pan") {
  745. try {
  746. const result: number = parseFloat(instrumentElement.value);
  747. subInstrument.pan = result / 64.0;
  748. } catch (ex) {
  749. log.debug("ExpressionReader.readExpressionParameters", "read pan", ex);
  750. }
  751. }
  752. } catch (ex) {
  753. log.info("MusicSheetReader.createInstrumentGroups midi settings: ", ex);
  754. }
  755. }
  756. }
  757. } catch (ex) {
  758. log.info("MusicSheetReader.createInstrumentGroups: ", ex);
  759. }
  760. }
  761. if (instrument.SubInstruments.length === 0) {
  762. const subInstrument: SubInstrument = new SubInstrument(instrument);
  763. instrument.SubInstruments.push(subInstrument);
  764. }
  765. instrumentDict[instrIdString] = instrument;
  766. if (currentGroup) {
  767. currentGroup.InstrumentalGroups.push(instrument);
  768. this.musicSheet.Instruments.push(instrument);
  769. } else {
  770. this.musicSheet.InstrumentalGroups.push(instrument);
  771. this.musicSheet.Instruments.push(instrument);
  772. }
  773. } else {
  774. if ((node.name === "part-group") && (node.attribute("type").value === "start")) {
  775. const iG: InstrumentalGroup = new InstrumentalGroup("group", this.musicSheet, currentGroup);
  776. if (currentGroup) {
  777. currentGroup.InstrumentalGroups.push(iG);
  778. } else {
  779. this.musicSheet.InstrumentalGroups.push(iG);
  780. }
  781. currentGroup = iG;
  782. } else {
  783. if ((node.name === "part-group") && (node.attribute("type").value === "stop")) {
  784. if (currentGroup) {
  785. if (currentGroup.InstrumentalGroups.length === 1) {
  786. const instr: InstrumentalGroup = currentGroup.InstrumentalGroups[0];
  787. if (currentGroup.Parent) {
  788. currentGroup.Parent.InstrumentalGroups.push(instr);
  789. this._removeFromArray(currentGroup.Parent.InstrumentalGroups, currentGroup);
  790. } else {
  791. this.musicSheet.InstrumentalGroups.push(instr);
  792. this._removeFromArray(this.musicSheet.InstrumentalGroups, currentGroup);
  793. }
  794. }
  795. currentGroup = currentGroup.Parent;
  796. }
  797. }
  798. }
  799. }
  800. }
  801. } catch (e) {
  802. const errorMsg: string = ITextTranslation.translateText(
  803. "ReaderErrorMessages/InstrumentError", "Error while reading Instruments"
  804. );
  805. throw new MusicSheetReadingException(errorMsg, e);
  806. }
  807. for (let idx: number = 0, len: number = this.musicSheet.Instruments.length; idx < len; ++idx) {
  808. const instrument: Instrument = this.musicSheet.Instruments[idx];
  809. if (!instrument.Name) {
  810. instrument.Name = "Instr. " + instrument.IdString;
  811. }
  812. }
  813. return instrumentDict;
  814. }
  815. /**
  816. * Read from each xmlInstrumentPart the first xmlMeasure in order to find out the [[Instrument]]'s number of Staves
  817. * @param partInst
  818. * @returns {number} - Complete number of Staves for all Instruments.
  819. */
  820. private getCompleteNumberOfStavesFromXml(partInst: IXmlElement[]): number {
  821. let num: number = 0;
  822. for (const partNode of partInst) {
  823. const xmlMeasureList: IXmlElement[] = partNode.elements("measure");
  824. if (xmlMeasureList.length > 0) {
  825. const xmlMeasure: IXmlElement = xmlMeasureList[0];
  826. if (xmlMeasure) {
  827. let stavesNode: IXmlElement = xmlMeasure.element("attributes");
  828. if (stavesNode) {
  829. stavesNode = stavesNode.element("staves");
  830. }
  831. if (!stavesNode) {
  832. num++;
  833. } else {
  834. num += parseInt(stavesNode.value, 10);
  835. }
  836. }
  837. }
  838. }
  839. if (isNaN(num) || num <= 0) {
  840. const errorMsg: string = ITextTranslation.translateText(
  841. "ReaderErrorMessages/StaffError", "Invalid number of staves."
  842. );
  843. throw new MusicSheetReadingException(errorMsg);
  844. }
  845. return num;
  846. }
  847. /**
  848. * Read from XML for a single [[Instrument]] the first xmlMeasure in order to find out the Instrument's number of Staves.
  849. * @param partNode
  850. * @returns {number}
  851. */
  852. private getInstrumentNumberOfStavesFromXml(partNode: IXmlElement): number {
  853. let num: number = 0;
  854. const xmlMeasure: IXmlElement = partNode.element("measure");
  855. if (xmlMeasure) {
  856. const attributes: IXmlElement = xmlMeasure.element("attributes");
  857. let staves: IXmlElement = undefined;
  858. if (attributes) {
  859. staves = attributes.element("staves");
  860. }
  861. if (!attributes || !staves) {
  862. num = 1;
  863. } else {
  864. num = parseInt(staves.value, 10);
  865. }
  866. }
  867. if (isNaN(num) || num <= 0) {
  868. const errorMsg: string = ITextTranslation.translateText(
  869. "ReaderErrorMessages/StaffError", "Invalid number of Staves."
  870. );
  871. throw new MusicSheetReadingException(errorMsg);
  872. }
  873. return num;
  874. }
  875. }