PlaybackManager.ts 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. import { ITimingSource } from "../Common/Interfaces/ITimingSource";
  2. import { IMessageViewer } from "../Common/Interfaces/IMessageViewer";
  3. import { IAudioPlayer } from "../Common/Interfaces/IAudioPlayer";
  4. import { MusicPartManager, MusicPartManagerIterator } from "../MusicalScore/MusicParts";
  5. import { PlaybackIterator } from "../MusicalScore/Playback/PlaybackIterator";
  6. import { Dictionary } from "typescript-collections";
  7. import { Staff, SourceMeasure, VoiceEntry, Note, MidiInstrument } from "../MusicalScore/VoiceData";
  8. import { Fraction } from "../Common/DataObjects";
  9. import { MetronomeInstrument } from "./MetronomeInstrument";
  10. import { CursorPosChangedData } from "../Common/DataObjects/CursorPosChangedData";
  11. import { Repetition } from "../MusicalScore/MusicSource";
  12. import { TextTranslation } from "../Common/Strings/TextTranslation";
  13. import { NoteState, Instrument, SubInstrument, MusicSheet } from "../MusicalScore";
  14. import { DynamicsContainer } from "../MusicalScore/VoiceData/HelperObjects";
  15. import { PlaybackEntry } from "../MusicalScore/Playback/PlaybackEntry";
  16. import { ContinuousDynamicExpression } from "../MusicalScore/VoiceData/Expressions/ContinuousExpressions";
  17. import { PlaybackNote } from "../MusicalScore/Playback/PlaybackNote";
  18. import log from "loglevel";
  19. import { IAudioMetronomePlayer } from "../Common/Interfaces/IAudioMetronomePlayer";
  20. import { ISettableInstrument } from "../Common/Interfaces/ISettableInstrument";
  21. import { PlaybackState, MessageBoxType } from "../Common/Enums/PsEnums";
  22. import { IPlaybackListener } from "../Common/Interfaces/IPlaybackListener";
  23. import { IPlaybackParametersListener } from "../Common/Interfaces/IPlaybackParametersListener";
  24. import { AbstractExpression } from "../MusicalScore/VoiceData/Expressions";
  25. export class ChannelNote {
  26. public note: PlaybackNote;
  27. public key: number;
  28. public channel: number;
  29. constructor(k: number, c: number, n: PlaybackNote = undefined) {
  30. this.note = n;
  31. this.key = k;
  32. this.channel = c;
  33. }
  34. }
  35. export class PlaybackManager implements IPlaybackParametersListener {
  36. protected timingSource: ITimingSource;
  37. protected resetRequested: boolean;
  38. protected loopTriggeredReset: boolean;
  39. protected tempoUserFactor: number;
  40. protected currentBPM: number;
  41. protected listeners: IPlaybackListener[] = [];
  42. public addListener(listener: IPlaybackListener): void {
  43. this.listeners.push(listener);
  44. }
  45. private readonly percussionChannel: number = 9; // this is a definition of the midi interface (cannot be changed)
  46. private messageViewer: IMessageViewer;
  47. private audioMetronomePlayer: IAudioMetronomePlayer;
  48. private audioPlayer: IAudioPlayer<any>;
  49. private musicPartManager: MusicPartManager;
  50. private cursorIterator: MusicPartManagerIterator;
  51. get CursorIterator(): MusicPartManagerIterator {
  52. return this.cursorIterator;
  53. }
  54. private playbackIterator: PlaybackIterator;
  55. //private Dictionary<int, MidiChannelInfo> instrumentsPerMidiSoundDict = new Dictionary<int, MidiChannelInfo>();
  56. //private Dictionary<int, int> midiSoundToChannelMappingDict = new Dictionary<int, int>();
  57. //private int[] midiChannelToSoundArray = new int[16];
  58. //Staff is not considered Unique for key purposes here. Had to use something unique - staff ID
  59. private instrumentToStaffToMidiChannelDict: Dictionary<Staff, number> = new Dictionary<Staff, number>();
  60. //store this data just in case
  61. private instrumentIdMapping: Dictionary<number, Instrument> = new Dictionary<number, Instrument>();
  62. public get InstrumentIdMapping(): Dictionary<number, Instrument> {
  63. return this.instrumentIdMapping;
  64. }
  65. //private List<int> staffIndexToMidiChannelMapping = new List<int>();
  66. private freeMidiChannels: number[] = [];
  67. private notesToStop: Dictionary<Fraction, ChannelNote[]> = new Dictionary<Fraction, ChannelNote[]>();
  68. private metronomeNote: ChannelNote = new ChannelNote(88, this.percussionChannel);
  69. private metronomeNoteFirstBeat: ChannelNote = new ChannelNote(64, this.percussionChannel);
  70. private currentMeasure: SourceMeasure = undefined;
  71. private currentTimestamp: Fraction = undefined;
  72. private closestNextTimestamp: Fraction = undefined;
  73. private currentMetronomeBaseTimestamp: Fraction = undefined;
  74. private currentBeatDuration: Fraction = undefined;
  75. private currentIteratorSourceTimeStamp: Fraction = undefined;
  76. private beatCounter: number = 0;
  77. protected runningState: PlaybackState = PlaybackState.Stopped;
  78. private isRunning: boolean = false;
  79. private isInitialized: boolean = false; // make sure midi device gets opened only once
  80. private nextIteratorTimestamp: Fraction;
  81. private playNextMetronomeAt: Fraction;
  82. // private masterTranspose: number = 0;
  83. private isPlaying: boolean = false;
  84. private metronome: MetronomeInstrument;
  85. private metronomeSoundPlayed: boolean = false;
  86. private tempoImpactFactor: number = 1.0;
  87. private sheetStartBPM: number;
  88. private currentReferenceBPM: number;
  89. private readonly defaultVolume: number = 0.8;
  90. private currentVolume: number = this.defaultVolume;
  91. private dynamicImpactFactor: number = 0.6;
  92. private scorePositionChangedData: CursorPosChangedData = new CursorPosChangedData();
  93. private tooManyInstruments: boolean = false;
  94. private currentRepetition: Repetition;
  95. private currentMeasureIndex: number;
  96. private metronomeOnlyBPM: number = 100;
  97. // private playbackThreadSyncObject = new object(); // TODO MB: Handle this.
  98. private readonly highlightPlayedNotes: boolean = false;
  99. private startRhythmBeats: number;
  100. private startRhythmDenominator: number;
  101. private isPreCounting: boolean;
  102. public MoveCursorDuringPrecount: boolean = true;
  103. private fermataActive: boolean;
  104. private doPreCount: boolean = true;
  105. constructor (timingSource: ITimingSource, audioMetronomePlayer: IAudioMetronomePlayer, audioPlayer: IAudioPlayer<any>, messageViewer: IMessageViewer) {
  106. const metronomeLabel: string = TextTranslation.translateText("Playback/LabelMetronome", "Metronome");
  107. this.metronome = new MetronomeInstrument(-1, metronomeLabel, false, true, 0.0, MidiInstrument.Percussion);
  108. this.timingSource = timingSource;
  109. this.audioMetronomePlayer = audioMetronomePlayer;
  110. this.audioPlayer = audioPlayer;
  111. this.messageViewer = messageViewer;
  112. }
  113. public get RunningState(): PlaybackState {
  114. return this.runningState;
  115. }
  116. public set RunningState(value: PlaybackState) {
  117. this.runningState = value;
  118. }
  119. public DoPlayback: boolean;
  120. /** Do the initial pre-count */
  121. public get DoPreCount(): boolean {
  122. return this.doPreCount;
  123. }
  124. public set DoPreCount(value: boolean) {
  125. if (this.doPreCount !== value) {
  126. this.doPreCount = value;
  127. }
  128. }
  129. public PreCountMeasures: number;
  130. public PreCountBeats: number;
  131. public get Metronome(): ISettableInstrument {
  132. return this.metronome;
  133. }
  134. public get MetronomeOnlyBPM(): number {
  135. return this.metronomeOnlyBPM;
  136. }
  137. public set MetronomeOnlyBPM(value: number) {
  138. this.metronomeOnlyBPM = value;
  139. }
  140. // public get Transpose(): number {
  141. // return this.masterTranspose;
  142. // }
  143. // public set Transpose(value: number) {
  144. // this.masterTranspose = value;
  145. // }
  146. public get OriginalBpm(): number {
  147. return this.currentReferenceBPM;
  148. }
  149. /** will be activated when any solo flag of an Instrument, Voice or Staff is set to true. */
  150. public SoloActive: boolean;
  151. public SoloAttenuationValue: number = 0;
  152. // Only used for debug and scheduling precision measurements
  153. //private wantedNextIteratorTimestampMs: number = 0;
  154. public playVoiceEntry(voiceEntry: VoiceEntry): void {
  155. const ve: VoiceEntry = voiceEntry;
  156. if (ve !== undefined) {
  157. // lock(this.playbackThreadSyncObject) {
  158. this.stopAllCurrentlyPlayingNotes();
  159. if (this.highlightPlayedNotes) {
  160. const notes: Note[] = [];
  161. for (const note of ve.Notes) {
  162. note.state = NoteState.Selected;
  163. notes.push(note);
  164. }
  165. //this.NotesPlaybackEventOccurred(notes);
  166. }
  167. //int staffIndex = this.musicPartManager.MusicSheet.getIndexFromStaff(ve.Notes[0].ParentStaff);
  168. const channel: number = this.instrumentToStaffToMidiChannelDict.getValue(ve.Notes[0].ParentStaff);
  169. const instrument: Instrument = ve.ParentVoice.Parent;
  170. const isPercussion: boolean = instrument.MidiInstrumentId === MidiInstrument.Percussion;
  171. const volume: number = 0.8;
  172. const notesToPlay: ChannelNote[] = [];
  173. const transpose: number = this.musicPartManager.MusicSheet.Transpose;
  174. const instrumentPlaybackTranspose: number = ve.ParentVoice.Parent.PlaybackTranspose;
  175. for (const note of ve.MainPlaybackEntry.Notes.filter(n => n.MidiKey !== 0)) {
  176. // play the note
  177. let key: number = note.MidiKey;
  178. if (!isPercussion) {
  179. key += instrumentPlaybackTranspose + transpose;
  180. }
  181. if (note.ParentNote.PlaybackInstrumentId !== undefined) {
  182. const notePlaybackInstrument: SubInstrument =
  183. instrument.getSubInstrument(note.ParentNote.PlaybackInstrumentId);
  184. if (notePlaybackInstrument !== undefined) {
  185. if (notePlaybackInstrument.fixedKey >= 0) {
  186. key = notePlaybackInstrument.fixedKey;
  187. }
  188. }
  189. }
  190. // calculate stop time and remember it
  191. // const stopAt: Fraction = Fraction.plus(this.cursorIterator.CurrentEnrolledTimestamp, note.Length);
  192. try {
  193. if (this.audioPlayer !== undefined) {
  194. //const noteLengthFraction: Fraction = Fraction.createFromFraction(note.Length);
  195. this.audioPlayer.playSound(channel, key, volume, 500);
  196. }
  197. } catch (ex) {
  198. log.info("PlaybackManager.playVoiceEntry: ", ex);
  199. }
  200. notesToPlay.push(new ChannelNote(key, channel, note));
  201. }
  202. // TODO MB: Handle this
  203. // Task stopper = new Task(() => {
  204. // EventWaitHandle waiter = new EventWaitHandle(false, EventResetMode.AutoReset);
  205. // waiter.WaitOne(200);
  206. // lock(this.playbackThreadSyncObject) {
  207. // if (this.audioPlayer !== undefined) {
  208. // foreach(var n in notesToPlay) {
  209. // this.audioPlayer.stopSound(n.channel, n.key);
  210. // }
  211. // }
  212. // }
  213. // // redraw to color notes normal if highlighted in playback
  214. // //this.phonicScoreInterface.RedrawGraphicalMusicSheet();
  215. // });
  216. // stopper.Start();
  217. // }
  218. }
  219. }
  220. public initialize(musicPartMng: MusicPartManager): void {
  221. // lock(this.playbackThreadSyncObject) {
  222. if (this.isInitialized) {
  223. this.stopAllCurrentlyPlayingNotes();
  224. if (this.audioPlayer !== undefined) {
  225. this.audioPlayer.close();
  226. }
  227. this.cursorIterator = undefined;
  228. this.playbackIterator = undefined;
  229. }
  230. this.isInitialized = false;
  231. this.musicPartManager = musicPartMng;
  232. if (this.musicPartManager !== undefined) {
  233. const musicSheet: MusicSheet = this.musicPartManager.MusicSheet;
  234. // TODO MB: Converted musicSheetParameterChanged to setBpm in this file. Handle following line.
  235. //musicSheet.MusicSheetParameterChanged += this.musicSheetParameterChanged;
  236. this.cursorIterator = this.musicPartManager.getIterator();
  237. this.playbackIterator = new PlaybackIterator(musicSheet);
  238. if (this.audioPlayer !== undefined) {
  239. // TODO MB: I rewrote following line in line below. Does it do what it's supposed to do? Array.from() not supported in IE
  240. // List < MidiInstrument > uniqueMidiInstruments = musicSheet.Instruments.Select(item => item.MidiInstrumentId).Distinct().ToList();
  241. const uniqueMidiInstruments: MidiInstrument[] = Array.from(new Set(musicSheet.Instruments.map(item => item.MidiInstrumentId)));
  242. this.audioPlayer.open(uniqueMidiInstruments, 16);
  243. // set drums:
  244. this.audioPlayer.setSound(this.percussionChannel, 115);
  245. }
  246. this.currentReferenceBPM = this.sheetStartBPM = musicSheet.getExpressionsStartTempoInBPM();
  247. this.tempoUserFactor = musicSheet.userStartTempoInBPM / this.sheetStartBPM;
  248. let instrumentId: number = 0;
  249. this.tooManyInstruments = false;
  250. // reset the dicts and channel mappings
  251. //this.staffIndexToMidiChannelMapping.Clear();
  252. this.instrumentToStaffToMidiChannelDict.clear();
  253. this.instrumentIdMapping.clear();
  254. for (let i: number = 0; i < this.percussionChannel; i++) {
  255. this.freeMidiChannels.push(i);
  256. }
  257. for (let i: number = this.percussionChannel + 1; i < 16; i++) {
  258. this.freeMidiChannels.push(i);
  259. }
  260. for (const instrument of musicSheet.Instruments) {
  261. this.instrumentIdMapping.setValue(instrumentId, instrument);
  262. for (const staff of instrument.Staves) {
  263. // just add a list element - calcMidiChannel() will provide the right value.
  264. //this.staffIndexToMidiChannelMapping.Add(-1);
  265. this.instrumentToStaffToMidiChannelDict.setValue(staff, -1);
  266. }
  267. this.setSound(instrumentId, instrument.MidiInstrumentId);
  268. instrumentId++;
  269. }
  270. if (this.audioPlayer !== undefined && this.tooManyInstruments) {
  271. const errorMsg: string = TextTranslation.translateText(
  272. "MidiNumberError",
  273. "This music sheet has more parts than are supported for midi playback. " +
  274. "Some parts will not be played with the desired instrument sounds."
  275. );
  276. if (this.messageViewer !== undefined && this.messageViewer.MessageOccurred !== undefined) {
  277. this.messageViewer.MessageOccurred(MessageBoxType.Warning, errorMsg);
  278. }
  279. }
  280. this.checkForSoloDeactivated();
  281. }
  282. this.isInitialized = true;
  283. // }
  284. this.reset();
  285. }
  286. public async play(): Promise<void> {
  287. if (this.cursorIterator !== undefined && this.cursorIterator.EndReached && this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)) {
  288. console.log("End reached, resetting");
  289. this.reset();
  290. }
  291. this.isPlaying = true;
  292. this.RunningState = PlaybackState.Running;
  293. await this.timingSource.start();
  294. this.loop();
  295. }
  296. public async pause(): Promise<void> {
  297. // lock(this.playbackThreadSyncObject) {
  298. this.isPlaying = false;
  299. // stop all active midi notes:
  300. this.stopAllCurrentlyPlayingNotes();
  301. // inform sample player to e.g. dispose used samples:
  302. if (this.audioPlayer !== undefined) {
  303. this.audioPlayer.playbackHasStopped();
  304. }
  305. // notify delegates (coreContainer) that the playing has finished:
  306. this.RunningState = PlaybackState.Stopped;
  307. await this.timingSource.pause();
  308. try {
  309. //bool endReached = this.iterator !== undefined && this.iterator.EndReached;
  310. for (const listener of this.listeners) {
  311. listener.pauseOccurred(undefined);
  312. }
  313. } catch (ex) {
  314. log.debug("PlaybackManager.pause: ", ex);
  315. }
  316. // }
  317. }
  318. /** Effectively resets the playback to osmd.Sheet.SelectionStart.
  319. * If you want to reset to the start of the sheet,
  320. * call osmd.Sheet.SelectionStart = osmd.Sheet.sourceMeasures[0].AbsoluteTimestamp beforehand.
  321. */
  322. public reset(): void {
  323. // lock(this.playbackThreadSyncObject) {
  324. //this.resetRequested = true;
  325. this.doReset(this.DoPreCount, this.PreCountMeasures);
  326. if (this.musicPartManager === undefined) {
  327. return;
  328. }
  329. if (this.RunningState === PlaybackState.Stopped) {
  330. //this.isPlaying = true;
  331. }
  332. for (const listener of this.listeners) {
  333. listener.resetOccurred(undefined);
  334. }
  335. // }
  336. }
  337. /** Starts play() from a time in milliseconds.*/
  338. public async playFromMs(timeInMs: number): Promise<void> {
  339. await this.pause();
  340. const timestamp: Fraction = this.getTimestampFromMs(timeInMs);
  341. const previousSelectionStart: Fraction = this.musicPartManager.MusicSheet.SelectionStart.clone();
  342. this.musicPartManager.MusicSheet.SelectionStart = timestamp;
  343. this.reset();
  344. this.play();
  345. this.musicPartManager.MusicSheet.SelectionStart = previousSelectionStart; // restore previous start point
  346. }
  347. public getTimestampFromMs(timeInMs: number): Fraction {
  348. return this.timingSource.Settings.getDurationAsNoteDuration(timeInMs);
  349. }
  350. /** Sets the cursor and MusicSheet.SelectionStart to the target timestamp (fraction),
  351. * but does not start playback if it was not started already.
  352. * To get the timestamp from milliseconds, use getTimestampFromMs().
  353. * To reset the playback start to the beginning of the sheet, call the function without arguments.
  354. */
  355. public setPlaybackStart(timestamp?: Fraction): void {
  356. if (!timestamp) {
  357. timestamp = this.musicPartManager.MusicSheet.SourceMeasures[0].AbsoluteTimestamp; // start of sheet
  358. }
  359. this.musicPartManager.MusicSheet.SelectionStart = timestamp;
  360. this.reset();
  361. }
  362. public Dispose(): void {
  363. // lock(this.playbackThreadSyncObject) {
  364. this.listeners = [];
  365. this.isRunning = false;
  366. // stop all active midi notes:
  367. if (this.isInitialized) {
  368. this.stopAllCurrentlyPlayingNotes();
  369. if (this.audioPlayer !== undefined) {
  370. this.audioPlayer.close();
  371. }
  372. }
  373. // this.musicPartManager = undefined;
  374. // // }
  375. }
  376. public setSound(instrumentId: number, newSoundId: MidiInstrument): boolean {
  377. if (newSoundId <= MidiInstrument.None || newSoundId > MidiInstrument.Percussion) {
  378. return false;
  379. }
  380. // lock(this.playbackThreadSyncObject) {
  381. try {
  382. const isPercussionNow: boolean = newSoundId === MidiInstrument.Percussion;
  383. if (instrumentId === -1) { // Metronome
  384. if (this.audioPlayer !== undefined && !isPercussionNow) {
  385. this.audioPlayer.setSound(0, newSoundId);
  386. }
  387. } else {
  388. let neededLastChannel: boolean = false;
  389. const musicSheet: MusicSheet = this.musicPartManager.MusicSheet;
  390. let instrument: Instrument;
  391. if (instrumentId === -2) {
  392. instrument = musicSheet.Instruments.find(x => x.Id === instrumentId);
  393. } else {
  394. instrument = musicSheet.Instruments[instrumentId];
  395. }
  396. this.instrumentIdMapping.setValue(instrument.Id, instrument);
  397. for (const staff of instrument.Staves) {
  398. //int staffIndex = musicSheet.getIndexFromStaff(staff);
  399. //int channel = this.staffIndexToMidiChannelMapping[staffIndex];
  400. let channel: number = this.instrumentToStaffToMidiChannelDict.getValue(staff);
  401. const wasPercussion: boolean = channel === this.percussionChannel;
  402. if (isPercussionNow) { // if is now a percussion
  403. const oldChannel: number = channel;
  404. channel = this.percussionChannel;
  405. // check if this instrument has been initialized and was no percussion instrument:
  406. if (oldChannel > 0 && !wasPercussion) {
  407. this.freeMidiChannels.push(oldChannel);
  408. this.freeMidiChannels.sort((a, b) => a - b); //TODO MB: Does this .sort do the same thing as C# .Sort()?
  409. }
  410. } else {
  411. if (channel < 0 || wasPercussion) { // if is not initialized or was a percussion:
  412. if (this.freeMidiChannels.length > 0) { // if still a free channel exists
  413. // get the channel and remove in from the free channels list
  414. channel = this.freeMidiChannels[0];
  415. this.freeMidiChannels.shift();
  416. } else { // if no channel is free any more:
  417. this.tooManyInstruments = true;
  418. // use last channel
  419. channel = 15;
  420. this.instrumentToStaffToMidiChannelDict.setValue(staff, channel);
  421. //// use piano sound
  422. //newSoundId = 0;
  423. neededLastChannel = true;
  424. }
  425. }
  426. }
  427. this.instrumentToStaffToMidiChannelDict.setValue(staff, channel);
  428. if (this.audioPlayer !== undefined && !isPercussionNow) {
  429. // TODO: Uncomment when panaroma is supported in audio player
  430. // this.audioPlayer.setPanorama(channel, instrument.SubInstruments[0].pan);
  431. // TODO: Commented because AvailableComponents not defined
  432. // if (AvailableComponents.PLAYBACK_INSTRUMENTS_AVAILABLE) {
  433. // // only set instrument sounds in pro version:
  434. this.audioPlayer.setSound(channel, newSoundId);
  435. // } else {
  436. // play all as piano in free version:
  437. // this.audioPlayer.setSound(channel, 0);
  438. // }
  439. }
  440. }
  441. if (neededLastChannel) {
  442. return false;
  443. }
  444. }
  445. return true;
  446. } catch (ex) {
  447. log.info("PlaybackManager.setSound: ", ex);
  448. return false;
  449. }
  450. // }
  451. }
  452. // public mainParameterChanged(client: IPhonicScoreClient, settingType: ProgramParameters, currentValue, previousValue): void {
  453. // switch (settingType) {
  454. // case ProgramParameters.DynamicInstructionsImpact:
  455. // this.dynamicImpactFactor = Convert.ToSingle(currentValue);
  456. // break;
  457. // case ProgramParameters.TempoInstructionsImpact: {
  458. // this.tempoImpactFactor = Convert.ToSingle(currentValue);
  459. // this.setTempo();
  460. // break;
  461. // }
  462. // }
  463. // }
  464. // TODO MB: Check if function setBpm() is sufficient for doing what commented function below does.
  465. // protected musicSheetParameterChanged(client: IPhonicScoreClient, parameter: MusicSheetParameters, currentValue, previousValue): void {
  466. // switch (parameter) {
  467. // case MusicSheetParameters.StartTempoInBPM: {
  468. // this.tempoUserFactor = Convert.ToSingle(currentValue) / this.sheetStartBPM;
  469. // this.setTempo();
  470. // break;
  471. // }
  472. // }
  473. // }
  474. protected setBpm(bpm: number): void {
  475. this.tempoUserFactor = bpm / this.sheetStartBPM;
  476. this.setTempo();
  477. }
  478. public handlePlaybackEvent(): void {
  479. // lock(this.playbackThreadSyncObject) {
  480. // initialize flags:
  481. const resetOccurred: boolean = this.resetRequested;
  482. this.resetRequested = false;
  483. // const resetMetronomeBeatCounter: boolean = resetOccurred;
  484. // @ts-ignore
  485. const resetMetronomeBeatCounter: boolean = resetOccurred;
  486. let updateCursorPosition: boolean = resetOccurred;
  487. let endHasBeenReached: boolean = false;
  488. if (resetOccurred) {
  489. const shallPrecount: boolean = this.DoPreCount;
  490. this.doReset(shallPrecount);
  491. }
  492. if (this.musicPartManager === undefined) {
  493. return;
  494. }
  495. /**********************************************/
  496. // set the current values:
  497. this.currentTimestamp = this.timingSource.getCurrentTimestamp();
  498. // console.log("TS ms: " + this.timingSource.getCurrentTimeInMs());
  499. // console.log("TS ts: " + this.currentTimestamp);
  500. endHasBeenReached = this.cursorIterator.EndReached;
  501. /**********************************************/
  502. // handle the currently pending instructions:
  503. // stop the notes that are already over now:
  504. this.stopFinishedNotes();
  505. this.processTempoInstructions();
  506. if (this.RunningState === PlaybackState.Running) { // needed when resetting when in pause
  507. const newCursorTimestampReached: boolean = this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)
  508. && !endHasBeenReached;
  509. if (newCursorTimestampReached) {
  510. this.isPreCounting = false;
  511. /***** Metronome Beat Calculations *****/
  512. // check if the measure has changed:
  513. if (this.currentMeasure !== this.cursorIterator.CurrentMeasure &&
  514. this.cursorIterator.CurrentMeasure !== undefined) {
  515. // set current measure to the new measure
  516. this.currentMeasure = this.cursorIterator.CurrentMeasure;
  517. this.startRhythmBeats = this.cursorIterator.currentPlaybackSettings().Rhythm.Numerator;
  518. this.startRhythmDenominator = this.cursorIterator.currentPlaybackSettings().Rhythm.Denominator;
  519. // get the enrolled timestamp of this measure start:
  520. const relativeToMeasureTimestamp: Fraction = this.cursorIterator.CurrentRelativeInMeasureTimestamp;
  521. this.currentMetronomeBaseTimestamp = Fraction.minus(this.cursorIterator.CurrentEnrolledTimestamp, relativeToMeasureTimestamp);
  522. // calculate the new beat duration
  523. this.currentBeatDuration = new Fraction(1, this.currentMeasure.Duration.Denominator);
  524. // calculate which beat is next:
  525. const relativeNextMetronomeBeatTimestamp: Fraction = new Fraction();
  526. this.beatCounter = 0;
  527. while (relativeNextMetronomeBeatTimestamp.lt(relativeToMeasureTimestamp)) {
  528. relativeNextMetronomeBeatTimestamp.Add(this.currentBeatDuration);
  529. this.beatCounter++;
  530. }
  531. this.playNextMetronomeAt = Fraction.plus(
  532. this.currentMetronomeBaseTimestamp,
  533. new Fraction(this.beatCounter, this.currentMeasure.Duration.Denominator)
  534. );
  535. }
  536. /***** process dynamic instructions: *****/
  537. const dynamicEntries: DynamicsContainer[] = this.cursorIterator.getCurrentDynamicChangingExpressions();
  538. for (const dynamicEntry of dynamicEntries) {
  539. const staff: Staff = this.musicPartManager.MusicSheet.getStaffFromIndex(dynamicEntry.staffNumber);
  540. const channel: number =
  541. this.instrumentToStaffToMidiChannelDict.getValue(staff);
  542. //int channel = this.staffIndexToMidiChannelMapping[dynamicEntry.StaffNumber];
  543. let volume: number = this.currentVolume;
  544. if (dynamicEntry.parMultiExpression().StartingContinuousDynamic !== undefined) {
  545. // dynamic expression is continuous:
  546. const currentDynamicValue: number =
  547. dynamicEntry.parMultiExpression().StartingContinuousDynamic.getInterpolatedDynamic(
  548. this.cursorIterator.CurrentSourceTimestamp);
  549. if (currentDynamicValue >= 0) {
  550. volume = this.calculateFinalVolume(currentDynamicValue);
  551. }
  552. } else { // dynamic Expression is instantanious - immediately set the volume:
  553. volume = this.calculateFinalVolume(dynamicEntry.parMultiExpression().InstantaneousDynamic.Volume);
  554. }
  555. try {
  556. if (this.audioPlayer !== undefined) {
  557. this.audioPlayer.setVolume(channel, volume);
  558. }
  559. } catch (ex) {
  560. log.info("PlaybackManager.handlePlaybackEvent: ", ex);
  561. }
  562. }
  563. dynamicEntries.clear();
  564. }
  565. // check if the time has come to process the pending instructions:
  566. const dueEntries: { enrolledTimestamp: Fraction, playbackEntry: PlaybackEntry }[] = this.playbackIterator.Update(this.currentTimestamp);
  567. if (dueEntries.length > 0) {
  568. // play new notes
  569. if (this.DoPlayback) {
  570. const playbackedNotes: PlaybackNote[] = [];
  571. for (const entry of dueEntries) {
  572. const playbackEntry: PlaybackEntry = entry.playbackEntry;
  573. const voiceEntry: VoiceEntry = playbackEntry.ParentVoiceEntry;
  574. if (playbackEntry.Notes.length === 0) {
  575. continue;
  576. }
  577. const instrument: Instrument = voiceEntry.ParentVoice.Parent;
  578. const staff: Staff = voiceEntry.Notes[0].ParentStaff;
  579. const staffIndex: number =
  580. MusicSheet.getIndexFromStaff(staff);
  581. let channel: number = this.instrumentToStaffToMidiChannelDict.getValue(staff);
  582. const isPercussion: boolean = instrument.MidiInstrumentId === MidiInstrument.Percussion;
  583. // choose percussion channel if Selected
  584. if (isPercussion) {
  585. channel = this.percussionChannel;
  586. }
  587. const currentlyActiveExpression: AbstractExpression = this.cursorIterator.ActiveDynamicExpressions[staffIndex];
  588. // adapt volume level for continuous expressions
  589. if (currentlyActiveExpression instanceof ContinuousDynamicExpression) {
  590. const currentDynamicValue: number =
  591. currentlyActiveExpression.getInterpolatedDynamic(
  592. this.cursorIterator.CurrentSourceTimestamp);
  593. if (currentDynamicValue >= 0) {
  594. const channelVolume: number = this.calculateFinalVolume(currentDynamicValue);
  595. try {
  596. if (this.audioPlayer !== undefined) {
  597. this.audioPlayer.setVolume(channel, channelVolume);
  598. }
  599. } catch (ex) {
  600. log.info("PlaybackManager.handlePlaybackEvent: ", ex);
  601. }
  602. }
  603. }
  604. // calculate volume from instrument volume, staff volume and voice volume:
  605. let volume: number = instrument.Volume * staff.Volume * voiceEntry.ParentVoice.Volume;
  606. // attenuate if in Solo mode an this voice is not soloed:
  607. const soloAttenuate: boolean = this.SoloActive &&
  608. !(instrument.Solo || voiceEntry.ParentVoice.Solo || staff.Solo);
  609. if (soloAttenuate) {
  610. volume *= this.SoloAttenuationValue;
  611. }
  612. // increase volume if this is an accent:
  613. const entryIsAccent: boolean = voiceEntry.VolumeModifier !== undefined;
  614. if (entryIsAccent) {
  615. volume *= 1.3;
  616. volume = Math.min(1, volume);
  617. }
  618. const transpose: number = this.musicPartManager.MusicSheet.Transpose;
  619. const instrumentPlaybackTranspose: number = instrument.PlaybackTranspose ?? 0;
  620. for (const note of playbackEntry.Notes.filter(n => n.MidiKey !== 0)) {
  621. // play the note
  622. let key: number = note.MidiKey;
  623. if (!isPercussion) {
  624. key += instrumentPlaybackTranspose + transpose;
  625. }
  626. // if note has another explicitly given playback instrument:
  627. if (note.ParentNote.PlaybackInstrumentId !== undefined) {
  628. // playback with other instrument:
  629. const notePlaybackInstrument: SubInstrument =
  630. instrument.getSubInstrument(note.ParentNote.PlaybackInstrumentId);
  631. if (notePlaybackInstrument !== undefined) {
  632. if (notePlaybackInstrument.fixedKey >= 0) {
  633. key = notePlaybackInstrument.fixedKey;
  634. }
  635. }
  636. // recalculate Volume for this instrument:
  637. volume = notePlaybackInstrument.volume * staff.Volume * voiceEntry.ParentVoice.Volume;
  638. // attenuate if in Solo mode an this voice is not soloed:
  639. if (soloAttenuate) {
  640. volume *= this.SoloAttenuationValue;
  641. }
  642. if (entryIsAccent) {
  643. volume *= 1.3;
  644. volume = Math.min(1, volume);
  645. }
  646. }
  647. // calculate stop time and remember it
  648. let noteLength: Fraction = Fraction.createFromFraction(note.Length);
  649. let stopAt: Fraction;
  650. // ToDo MU: move this to PlaybackEntry
  651. const entryIsStaccato: boolean = voiceEntry.DurationModifier !== undefined;
  652. if (entryIsStaccato) {
  653. // Reduce length and stopAt time:
  654. noteLength = new Fraction(noteLength.Numerator * 2, noteLength.Denominator * 3);
  655. stopAt = Fraction.plus(entry.enrolledTimestamp, noteLength);
  656. } else {
  657. stopAt = Fraction.plus(entry.enrolledTimestamp, noteLength);
  658. }
  659. try {
  660. if (this.audioPlayer !== undefined) {
  661. this.audioPlayer.playSound( channel,
  662. key,
  663. volume,
  664. this.timingSource.getDurationInMs(noteLength));
  665. }
  666. } catch (ex) {
  667. log.info("PlaybackManager.handlePlaybackEvent. Failed playing sound: ", ex);
  668. }
  669. if (!this.notesToStop.containsKey(stopAt)) {
  670. // this.notesToStop.Add(stopAt, new List<ChannelNote>());
  671. this.notesToStop.setValue(stopAt, []);
  672. }
  673. this.notesToStop.getValue(stopAt).push(new ChannelNote(key, channel, note));
  674. if (this.highlightPlayedNotes) {
  675. note.ParentNote.state = NoteState.Selected;
  676. }
  677. playbackedNotes.push(note);
  678. }
  679. }
  680. /*** Inform about which notes are now played ***
  681. * e.g. for updating graphics
  682. */
  683. // TODO: Replace with generic event system
  684. // if (this.highlightPlayedNotes && this.NotesPlaybackEventOccurred !== undefined) {
  685. this.NotesPlaybackEventOccurred(playbackedNotes);
  686. }
  687. }
  688. if (newCursorTimestampReached) {
  689. // store current iterator parameters:
  690. this.currentIteratorSourceTimeStamp = this.cursorIterator.CurrentSourceTimestamp;
  691. this.currentMeasureIndex = this.cursorIterator.CurrentMeasureIndex;
  692. // this.currentRepetition = this.cursorIterator.CurrentRepetition;
  693. /************ Move to next sheet position ************/
  694. // move iterator already to next position, to find out how long to wait or if the End has been reached:
  695. this.cursorIterator.moveToNext();
  696. this.nextIteratorTimestamp = this.cursorIterator.CurrentEnrolledTimestamp;
  697. updateCursorPosition = true;
  698. }
  699. // Stop the sound of the last played metronome
  700. this.stopMetronomeSound();
  701. // Check for "end has been reached"
  702. if (endHasBeenReached && this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)) {
  703. // notify possible listeners:
  704. for (const listener of this.listeners) {
  705. listener.selectionEndReached(undefined);
  706. }
  707. this.handleEndReached();
  708. } else {
  709. /******
  710. * Play Metronome if needed
  711. */
  712. if (this.currentTimestamp.gte(this.playNextMetronomeAt)) {
  713. updateCursorPosition = true;
  714. const playFirstBeatSample: boolean = this.beatCounter % this.startRhythmBeats === 0;
  715. this.playMetronomeSound(playFirstBeatSample);
  716. this.beatCounter++;
  717. }
  718. // calculate the next metronome beat timestamp
  719. if (this.currentMetronomeBaseTimestamp !== undefined) {
  720. this.playNextMetronomeAt = Fraction.plus(
  721. this.currentMetronomeBaseTimestamp,
  722. new Fraction(this.beatCounter, this.startRhythmDenominator)
  723. );
  724. }
  725. /*************************************/
  726. this.calculateClosestNextTimestamp();
  727. }
  728. } else {
  729. // needed when a reset was requested: reset parameters, fire score position changed and finally stop again
  730. this.isPlaying = false;
  731. }
  732. // Check for "updating the display"
  733. if (updateCursorPosition ||
  734. endHasBeenReached && !this.loopTriggeredReset) {
  735. // set the play cursor in the display
  736. this.updateScoreCursorPosition(resetOccurred);
  737. }
  738. // }
  739. }
  740. private NotesPlaybackEventOccurred(notes: PlaybackNote[]): void {
  741. for (const listener of this.listeners) {
  742. listener.notesPlaybackEventOccurred(notes);
  743. }
  744. }
  745. public calculateFinalVolume(volume: number): number {
  746. return ((volume - this.defaultVolume) * this.dynamicImpactFactor + this.defaultVolume);
  747. }
  748. /** Main playback loop. Not a sheet music loop, but checks for new notes to be played. */
  749. private loop(): void {
  750. // start playing:
  751. try {
  752. this.isRunning = true;
  753. // @ts-ignore
  754. const reset: boolean = false;
  755. if (this.isPlaying) {
  756. try {
  757. if (this.isRunning && this.isInitialized) {
  758. //console.log(`handlePlayback, timing deviation: ${Math.round(this.timingSource.getCurrentTimeInMs()) - Math.round(this.wantedNextIteratorTimestampMs)}`);
  759. this.handlePlaybackEvent();
  760. if (this.closestNextTimestamp !== undefined) {
  761. const wantedNextElapsedMs: number = this.timingSource.getWaitingTimeForTimestampInMs(this.closestNextTimestamp);
  762. //this.wantedNextIteratorTimestampMs = this.timingSource.getCurrentTimeInMs() + wantedNextElapsedMs;
  763. window.setTimeout(() => { this.loop(); }, Math.max(0, wantedNextElapsedMs));
  764. //this.interruptWaiting.WaitOne(Math.max(0, wantedNextElapsedMs));
  765. }
  766. }
  767. } catch (ex) {
  768. this.pause();
  769. this.reset();
  770. const errorMsg: string = TextTranslation.translateText(
  771. "MidiPlaybackError",
  772. "An error occurred at the Midi Playback."
  773. );
  774. log.info("PlaybackManager.loop: " + errorMsg + " ", ex);
  775. if (this.messageViewer !== undefined && this.messageViewer.MessageOccurred !== undefined) {
  776. this.messageViewer.MessageOccurred(MessageBoxType.Error, errorMsg);
  777. }
  778. }
  779. }
  780. } catch (ex) {
  781. const errorMsg: string = TextTranslation.translateText(
  782. "MidiPlaybackLoopError",
  783. "An error occurred at the Midi Playback. Please restart the program in order for the Playback to be availiable again."
  784. );
  785. log.info("PlaybackManager.loop: " + errorMsg + " ", ex);
  786. if (this.messageViewer !== undefined && this.messageViewer.MessageOccurred !== undefined) {
  787. this.messageViewer.MessageOccurred(MessageBoxType.Error, errorMsg);
  788. }
  789. }
  790. this.isRunning = false;
  791. }
  792. private stopAllCurrentlyPlayingNotes(): void {
  793. try {
  794. // lock(this.playbackThreadSyncObject) {
  795. if (this.audioPlayer !== undefined) {
  796. // stop active metronome sound
  797. this.audioPlayer.stopSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key);
  798. this.audioPlayer.stopSound(this.metronomeNote.channel, this.metronomeNote.key);
  799. // stop active notes
  800. // TODO MB: check if port of following for..of is correct
  801. // check same in for..of below
  802. // for (const entry of this.notesToStop) {
  803. // for (const note of entry.Value) {
  804. // this.audioPlayer.stopSound(note.channel, note.key);
  805. // }
  806. // }
  807. for (const entry of this.notesToStop.values()) {
  808. for (const note of entry) {
  809. this.audioPlayer.stopSound(note.channel, note.key);
  810. }
  811. }
  812. }
  813. /*** Inform about which notes are now stopped ***
  814. * e.g. for updating graphics
  815. */
  816. const notes: Note[] = [];
  817. for (const entry of this.notesToStop.values()) {
  818. for (const note of entry) {
  819. note.note.ParentNote.state = NoteState.Normal;
  820. notes.push(note.note.ParentNote);
  821. }
  822. }
  823. if (this.highlightPlayedNotes) {
  824. // TODO: Replace with generic even system
  825. // if (this.NotesPlaybackEventOccurred !== undefined) {
  826. // this.NotesPlaybackEventOccurred(notes);
  827. // }
  828. }
  829. this.notesToStop.clear();
  830. // }
  831. } catch (ex) {
  832. log.info("PlaybackManager.stoppAllCurrentlyPlayingNotes: ", ex);
  833. }
  834. }
  835. protected doReset(shallPrecount: boolean, preCountMeasures: number = 1): void {
  836. this.nextIteratorTimestamp = undefined;
  837. this.playNextMetronomeAt = undefined;
  838. this.closestNextTimestamp = undefined;
  839. this.currentMeasure = undefined;
  840. this.beatCounter = 0;
  841. this.fermataActive = false;
  842. this.stopAllCurrentlyPlayingNotes();
  843. if (this.musicPartManager !== undefined) {
  844. this.cursorIterator = this.musicPartManager.getIterator();
  845. }
  846. if (this.cursorIterator === undefined) {
  847. return;
  848. }
  849. this.playbackIterator.Reset();
  850. this.currentIteratorSourceTimeStamp = this.cursorIterator.CurrentSourceTimestamp;
  851. this.nextIteratorTimestamp = this.cursorIterator.CurrentEnrolledTimestamp;
  852. this.currentMeasure = this.cursorIterator.CurrentMeasure;
  853. this.currentMeasureIndex = this.cursorIterator.CurrentMeasureIndex;
  854. // this.currentRepetition = this.cursorIterator.CurrentRepetition;
  855. this.startRhythmBeats = this.cursorIterator.currentPlaybackSettings().Rhythm.Numerator;
  856. this.startRhythmDenominator = this.cursorIterator.currentPlaybackSettings().Rhythm.Denominator;
  857. let preCountDuration: Fraction = new Fraction();
  858. if (shallPrecount) {
  859. this.isPreCounting = true;
  860. const rhythmDuration: Fraction = new Fraction(this.startRhythmBeats * preCountMeasures, this.startRhythmDenominator);
  861. const sourceMeasureDuration: Fraction = this.musicPartManager.MusicSheet.SourceMeasures[this.currentMeasureIndex].Duration;
  862. const measureDuration: Fraction = new Fraction(sourceMeasureDuration.Numerator * preCountMeasures, sourceMeasureDuration.Denominator);
  863. const duration: Fraction =
  864. Fraction.plus(this.musicPartManager.MusicSheet.SourceMeasures[this.currentMeasureIndex].AbsoluteTimestamp,
  865. measureDuration).Sub(this.currentIteratorSourceTimeStamp);
  866. preCountDuration = rhythmDuration;
  867. if (rhythmDuration.gte(duration)) { // make sure that missing duration can't get negative (e.g. if measure is longer that given rhythm.
  868. const missingDuration: Fraction = Fraction.minus(rhythmDuration, duration);
  869. if (missingDuration.RealValue / rhythmDuration.RealValue < 0.5) {
  870. preCountDuration.Add(missingDuration);
  871. } else {
  872. preCountDuration = missingDuration;
  873. }
  874. }
  875. }
  876. this.currentMetronomeBaseTimestamp = this.playNextMetronomeAt = Fraction.minus(this.cursorIterator.CurrentEnrolledTimestamp, preCountDuration);
  877. //this.timingSource.reset();
  878. this.timingSource.setTimeAndBpm(this.currentMetronomeBaseTimestamp,
  879. this.cursorIterator.currentPlaybackSettings().BeatsPerMinute);
  880. this.calculateClosestNextTimestamp();
  881. }
  882. /// <summary>
  883. /// Calculate the closest next timestamp at which the next instruction has to be processed
  884. /// </summary>
  885. private calculateClosestNextTimestamp(): void {
  886. const timestamps: Fraction[] = [];
  887. // add next timestamp for stopping notes
  888. if (this.notesToStop.size() > 0) {
  889. // timestamps.push(this.notesToStop.keys().Min());
  890. // TODO MB: Check if line below does what line above is supposed to do
  891. timestamps.push(this.notesToStop.keys().reduce( (a, b) => a.lt(b) ? a : b));
  892. }
  893. // add next timestamp for next notes or other sheet instruction
  894. if (this.playbackIterator.NextEntryTimestamp !== undefined) {
  895. timestamps.push(this.playbackIterator.NextEntryTimestamp);
  896. }
  897. if (this.nextIteratorTimestamp !== undefined) {
  898. timestamps.push(this.nextIteratorTimestamp);
  899. }
  900. // add next timestamp for metronome tick
  901. if (this.playNextMetronomeAt !== undefined) {
  902. timestamps.push(this.playNextMetronomeAt);
  903. }
  904. // get the closest next timestamp
  905. if (timestamps.length > 0) {
  906. // this.closestNextTimestamp = timestamps.Min();
  907. // TODO MB: Check if line below does what line above is supposed to do
  908. this.closestNextTimestamp = timestamps.reduce( (a, b) => a.lt(b) ? a : b);
  909. } else {
  910. this.closestNextTimestamp = undefined;
  911. }
  912. }
  913. /// <summary>
  914. /// Called when the end of the sheet or the selection has been reached
  915. /// </summary>
  916. protected handleEndReached(): void {
  917. this.pause();
  918. }
  919. /// <summary>
  920. /// Fire a delegate to inform the display, that the cursor position has changed
  921. /// </summary>
  922. /// <param name="resetOccurred"></param>
  923. private updateScoreCursorPosition(resetOccurred: boolean): void {
  924. if (this.isPreCounting && !this.MoveCursorDuringPrecount) {
  925. return;
  926. }
  927. this.scorePositionChangedData.CurrentMeasureIndex = this.currentMeasureIndex;
  928. this.scorePositionChangedData.CurrentRepetition = this.currentRepetition;
  929. this.scorePositionChangedData.PredictedPosition = this.currentTimestamp;
  930. this.scorePositionChangedData.CurrentBpm = this.musicPartManager.MusicSheet.SheetPlaybackSetting.BeatsPerMinute;
  931. this.scorePositionChangedData.ResetOccurred = resetOccurred;
  932. for (const listener of this.listeners) {
  933. listener.cursorPositionChanged(this.currentIteratorSourceTimeStamp, this.scorePositionChangedData);
  934. }
  935. }
  936. private stopMetronomeSound(): void {
  937. if (this.metronomeSoundPlayed) {
  938. if (this.audioPlayer !== undefined) {
  939. this.audioPlayer.stopSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key);
  940. this.audioPlayer.stopSound(this.metronomeNote.channel, this.metronomeNote.key);
  941. }
  942. this.metronomeSoundPlayed = false;
  943. }
  944. }
  945. private playMetronomeSound(playFirstBeatSample: boolean): void {
  946. // play the metronome if needed:
  947. if (this.metronome.Audible ||
  948. this.metronome.Solo ||
  949. this.isPreCounting) {
  950. let volume: number = this.isPreCounting ? this.metronome.PreCountVolume : this.metronome.Volume;
  951. if (!this.isPreCounting && this.SoloActive && !this.metronome.Solo) {
  952. volume *= this.SoloAttenuationValue;
  953. }
  954. if (volume > 0) {
  955. if (playFirstBeatSample) {
  956. try {
  957. if (this.audioPlayer !== undefined) {
  958. this.audioPlayer.playSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key, volume, 1000);
  959. }
  960. if (this.audioMetronomePlayer !== undefined) {
  961. this.audioMetronomePlayer.playFirstBeatSample(volume);
  962. }
  963. } catch (ex) {
  964. log.info("PlaybackManager.playMetronomeSound: ", ex);
  965. }
  966. } else {
  967. try {
  968. if (this.audioPlayer !== undefined) {
  969. this.audioPlayer.playSound(this.metronomeNote.channel, this.metronomeNote.key, volume, 1000);
  970. }
  971. if (this.audioMetronomePlayer !== undefined) {
  972. this.audioMetronomePlayer.playBeatSample(volume);
  973. }
  974. } catch (ex) {
  975. log.info("PlaybackManager.playMetronomeSound: ", ex);
  976. }
  977. }
  978. this.metronomeSoundPlayed = true;
  979. }
  980. }
  981. }
  982. private stopFinishedNotes(): void {
  983. // do the pending note stops:
  984. let expiredKeys: Fraction[];
  985. if (this.currentTimestamp !== undefined) {
  986. expiredKeys = this.notesToStop.keys().filter(ts => ts.lte(this.currentTimestamp));
  987. } else {
  988. expiredKeys = this.notesToStop.keys();
  989. }
  990. for (const timestamp of expiredKeys) {
  991. const notesToStop: ChannelNote[] = this.notesToStop.getValue(timestamp);
  992. if (this.audioPlayer !== undefined) {
  993. for (const note of notesToStop) {
  994. this.audioPlayer.stopSound(note.channel, note.key);
  995. }
  996. }
  997. /*** Inform about which notes are now stopped ***
  998. * e.g. for updating graphics
  999. */
  1000. const notes: Note[] = [];
  1001. for (const note of notesToStop) {
  1002. note.note.ParentNote.state = NoteState.Normal;
  1003. notes.push(note.note.ParentNote);
  1004. }
  1005. if (this.highlightPlayedNotes) {
  1006. // TODO: Replace with generic event system
  1007. // if (this.NotesPlaybackEventOccurred !== undefined) {
  1008. // this.NotesPlaybackEventOccurred(notes);
  1009. // }
  1010. }
  1011. this.notesToStop.remove(timestamp);
  1012. }
  1013. }
  1014. private processTempoInstructions(): void {
  1015. // 1. check if the current bpm of the iterator have changed (significantly):
  1016. if (Math.abs(this.currentReferenceBPM - this.cursorIterator.CurrentBpm) > 0.001) {
  1017. this.changeTempo(this.cursorIterator.CurrentBpm);
  1018. }
  1019. // 2. check for possible fermatas and slow down for that entry:
  1020. this.handleFermata();
  1021. }
  1022. private handleFermata(): void {
  1023. // check for fermatas:
  1024. let fermataFound: boolean = false;
  1025. if (!this.cursorIterator.EndReached) {
  1026. if (this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)) {
  1027. for (const ve of this.cursorIterator.CurrentVoiceEntries) {
  1028. fermataFound = ve.Fermata !== undefined;
  1029. }
  1030. }
  1031. }
  1032. if (fermataFound) {
  1033. if (!this.fermataActive) {
  1034. this.fermataActive = true;
  1035. this.changeTempo(this.cursorIterator.CurrentBpm / 3);
  1036. }
  1037. } else {
  1038. if (this.fermataActive) {
  1039. this.fermataActive = false;
  1040. this.changeTempo(this.cursorIterator.CurrentBpm);
  1041. }
  1042. }
  1043. }
  1044. public bpmChanged(newBpm: number): void {
  1045. this.currentBPM = newBpm;
  1046. this.timingSource.setBpm(newBpm);
  1047. }
  1048. public volumeChanged(instrument: number, newVolume: number): void {
  1049. this.currentVolume = newVolume / 100;
  1050. if (instrument === -1) {
  1051. this.metronome.Volume = this.currentVolume;
  1052. } else {
  1053. this.instrumentIdMapping.getValue(instrument).Volume = this.currentVolume;
  1054. }
  1055. }
  1056. public volumeMute(instrument: number): void {
  1057. if (instrument === -1) {
  1058. this.metronome.Mute = true;
  1059. } else {
  1060. this.instrumentIdMapping.getValue(instrument).Audible = false;
  1061. }
  1062. }
  1063. public volumeUnmute(instrument: number): void {
  1064. if (instrument === -1) {
  1065. this.metronome.Mute = false;
  1066. } else {
  1067. this.instrumentIdMapping.getValue(instrument).Audible = true;
  1068. }
  1069. }
  1070. private changeTempo(newTempoInBPM: number): void {
  1071. log.debug("PlaybackManager.changeTempo", `current tempo in BPM: ${newTempoInBPM}`);
  1072. //Console.WriteLine(currTempoInBPM.ToString());
  1073. if (newTempoInBPM > 0) {
  1074. this.currentReferenceBPM = newTempoInBPM;
  1075. this.setTempo();
  1076. }
  1077. }
  1078. protected setTempo(): void {
  1079. this.currentBPM = this.tempoUserFactor * this.getCurrentReferenceBPM();
  1080. this.timingSource.setBpm(this.currentBPM);
  1081. }
  1082. protected getCurrentReferenceBPM(): number {
  1083. return ((this.currentReferenceBPM - this.sheetStartBPM) * this.tempoImpactFactor + this.sheetStartBPM);
  1084. }
  1085. public checkForSoloDeactivated(): void {
  1086. if (this.musicPartManager.MusicSheet === undefined) {
  1087. this.SoloActive = false;
  1088. return;
  1089. }
  1090. let state: boolean = false;
  1091. for (const instrument of this.musicPartManager.MusicSheet.Instruments) {
  1092. for (const staff of instrument.Staves) {
  1093. state = state || staff.Solo;
  1094. }
  1095. for (const voice of instrument.Voices) {
  1096. state = state || voice.Solo;
  1097. }
  1098. }
  1099. state = state || this.Metronome.Solo;
  1100. if (!state) {
  1101. this.SoloActive = false;
  1102. }
  1103. }
  1104. /** Returns the duration of the piece in ms. Including repeats. */
  1105. public getSheetDurationInMs(): number {
  1106. return this.timingSource.getDurationInMs(this.musicPartManager.MusicSheet.SheetEndTimestamp);
  1107. }
  1108. //private class MidiChannelInfo
  1109. //{
  1110. // public List<IInstrument> subscribers = new List<IInstrument>();
  1111. // public int channel;
  1112. //}
  1113. }