MusicSheetReader.ts 42 KB

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