MusicSheetReader.ts 45 KB

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