MusicSheetReader.ts 37 KB

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