MusicSheetReader.ts 37 KB

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