PlaybackManager.ts 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. const instrumentVolume: number = notePlaybackInstrument?.volume ?? 1;
  638. // TODO notePlaybackInstrument can be undefined, e.g. issue 42
  639. volume = instrumentVolume * staff.Volume * voiceEntry.ParentVoice.Volume;
  640. // attenuate if in Solo mode an this voice is not soloed:
  641. if (soloAttenuate) {
  642. volume *= this.SoloAttenuationValue;
  643. }
  644. if (entryIsAccent) {
  645. volume *= 1.3;
  646. volume = Math.min(1, volume);
  647. }
  648. }
  649. // calculate stop time and remember it
  650. let noteLength: Fraction = Fraction.createFromFraction(note.Length);
  651. let stopAt: Fraction;
  652. // ToDo MU: move this to PlaybackEntry
  653. const entryIsStaccato: boolean = voiceEntry.DurationModifier !== undefined;
  654. if (entryIsStaccato) {
  655. // Reduce length and stopAt time:
  656. noteLength = new Fraction(noteLength.Numerator * 2, noteLength.Denominator * 3);
  657. stopAt = Fraction.plus(entry.enrolledTimestamp, noteLength);
  658. } else {
  659. stopAt = Fraction.plus(entry.enrolledTimestamp, noteLength);
  660. }
  661. try {
  662. if (this.audioPlayer !== undefined) {
  663. this.audioPlayer.playSound( channel,
  664. key,
  665. volume,
  666. this.timingSource.getDurationInMs(noteLength));
  667. }
  668. } catch (ex) {
  669. log.info("PlaybackManager.handlePlaybackEvent. Failed playing sound: ", ex);
  670. }
  671. if (!this.notesToStop.containsKey(stopAt)) {
  672. // this.notesToStop.Add(stopAt, new List<ChannelNote>());
  673. this.notesToStop.setValue(stopAt, []);
  674. }
  675. this.notesToStop.getValue(stopAt).push(new ChannelNote(key, channel, note));
  676. if (this.highlightPlayedNotes) {
  677. note.ParentNote.state = NoteState.Selected;
  678. }
  679. playbackedNotes.push(note);
  680. }
  681. }
  682. /*** Inform about which notes are now played ***
  683. * e.g. for updating graphics
  684. */
  685. // TODO: Replace with generic event system
  686. // if (this.highlightPlayedNotes && this.NotesPlaybackEventOccurred !== undefined) {
  687. this.NotesPlaybackEventOccurred(playbackedNotes);
  688. }
  689. }
  690. if (newCursorTimestampReached) {
  691. // store current iterator parameters:
  692. this.currentIteratorSourceTimeStamp = this.cursorIterator.CurrentSourceTimestamp;
  693. this.currentMeasureIndex = this.cursorIterator.CurrentMeasureIndex;
  694. // this.currentRepetition = this.cursorIterator.CurrentRepetition;
  695. /************ Move to next sheet position ************/
  696. // move iterator already to next position, to find out how long to wait or if the End has been reached:
  697. this.cursorIterator.moveToNext();
  698. this.nextIteratorTimestamp = this.cursorIterator.CurrentEnrolledTimestamp;
  699. updateCursorPosition = true;
  700. }
  701. // Stop the sound of the last played metronome
  702. this.stopMetronomeSound();
  703. // Check for "end has been reached"
  704. if (endHasBeenReached && this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)) {
  705. // notify possible listeners:
  706. for (const listener of this.listeners) {
  707. listener.selectionEndReached(undefined);
  708. }
  709. this.handleEndReached();
  710. } else {
  711. /******
  712. * Play Metronome if needed
  713. */
  714. if (this.currentTimestamp.gte(this.playNextMetronomeAt)) {
  715. updateCursorPosition = true;
  716. const playFirstBeatSample: boolean = this.beatCounter % this.startRhythmBeats === 0;
  717. this.playMetronomeSound(playFirstBeatSample);
  718. this.beatCounter++;
  719. }
  720. // calculate the next metronome beat timestamp
  721. if (this.currentMetronomeBaseTimestamp !== undefined) {
  722. this.playNextMetronomeAt = Fraction.plus(
  723. this.currentMetronomeBaseTimestamp,
  724. new Fraction(this.beatCounter, this.startRhythmDenominator)
  725. );
  726. }
  727. /*************************************/
  728. this.calculateClosestNextTimestamp();
  729. }
  730. } else {
  731. // needed when a reset was requested: reset parameters, fire score position changed and finally stop again
  732. this.isPlaying = false;
  733. }
  734. // Check for "updating the display"
  735. if (updateCursorPosition ||
  736. endHasBeenReached && !this.loopTriggeredReset) {
  737. // set the play cursor in the display
  738. this.updateScoreCursorPosition(resetOccurred);
  739. }
  740. // }
  741. }
  742. private NotesPlaybackEventOccurred(notes: PlaybackNote[]): void {
  743. for (const listener of this.listeners) {
  744. listener.notesPlaybackEventOccurred(notes);
  745. }
  746. }
  747. public calculateFinalVolume(volume: number): number {
  748. return ((volume - this.defaultVolume) * this.dynamicImpactFactor + this.defaultVolume);
  749. }
  750. /** Main playback loop. Not a sheet music loop, but checks for new notes to be played. */
  751. private loop(): void {
  752. // start playing:
  753. try {
  754. this.isRunning = true;
  755. // @ts-ignore
  756. const reset: boolean = false;
  757. if (this.isPlaying) {
  758. try {
  759. if (this.isRunning && this.isInitialized) {
  760. //console.log(`handlePlayback, timing deviation: ${Math.round(this.timingSource.getCurrentTimeInMs()) - Math.round(this.wantedNextIteratorTimestampMs)}`);
  761. this.handlePlaybackEvent();
  762. if (this.closestNextTimestamp !== undefined) {
  763. const wantedNextElapsedMs: number = this.timingSource.getWaitingTimeForTimestampInMs(this.closestNextTimestamp);
  764. //this.wantedNextIteratorTimestampMs = this.timingSource.getCurrentTimeInMs() + wantedNextElapsedMs;
  765. window.setTimeout(() => { this.loop(); }, Math.max(0, wantedNextElapsedMs));
  766. //this.interruptWaiting.WaitOne(Math.max(0, wantedNextElapsedMs));
  767. }
  768. }
  769. } catch (ex) {
  770. this.pause();
  771. this.reset();
  772. const errorMsg: string = TextTranslation.translateText(
  773. "MidiPlaybackError",
  774. "An error occurred at the Midi Playback."
  775. );
  776. log.info("PlaybackManager.loop: " + errorMsg + " ", ex);
  777. if (this.messageViewer !== undefined && this.messageViewer.MessageOccurred !== undefined) {
  778. this.messageViewer.MessageOccurred(MessageBoxType.Error, errorMsg);
  779. }
  780. }
  781. }
  782. } catch (ex) {
  783. const errorMsg: string = TextTranslation.translateText(
  784. "MidiPlaybackLoopError",
  785. "An error occurred at the Midi Playback. Please restart the program in order for the Playback to be availiable again."
  786. );
  787. log.info("PlaybackManager.loop: " + errorMsg + " ", ex);
  788. if (this.messageViewer !== undefined && this.messageViewer.MessageOccurred !== undefined) {
  789. this.messageViewer.MessageOccurred(MessageBoxType.Error, errorMsg);
  790. }
  791. }
  792. this.isRunning = false;
  793. }
  794. private stopAllCurrentlyPlayingNotes(): void {
  795. try {
  796. // lock(this.playbackThreadSyncObject) {
  797. if (this.audioPlayer !== undefined) {
  798. // stop active metronome sound
  799. this.audioPlayer.stopSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key);
  800. this.audioPlayer.stopSound(this.metronomeNote.channel, this.metronomeNote.key);
  801. // stop active notes
  802. // TODO MB: check if port of following for..of is correct
  803. // check same in for..of below
  804. // for (const entry of this.notesToStop) {
  805. // for (const note of entry.Value) {
  806. // this.audioPlayer.stopSound(note.channel, note.key);
  807. // }
  808. // }
  809. for (const entry of this.notesToStop.values()) {
  810. for (const note of entry) {
  811. this.audioPlayer.stopSound(note.channel, note.key);
  812. }
  813. }
  814. }
  815. /*** Inform about which notes are now stopped ***
  816. * e.g. for updating graphics
  817. */
  818. const notes: Note[] = [];
  819. for (const entry of this.notesToStop.values()) {
  820. for (const note of entry) {
  821. note.note.ParentNote.state = NoteState.Normal;
  822. notes.push(note.note.ParentNote);
  823. }
  824. }
  825. if (this.highlightPlayedNotes) {
  826. // TODO: Replace with generic even system
  827. // if (this.NotesPlaybackEventOccurred !== undefined) {
  828. // this.NotesPlaybackEventOccurred(notes);
  829. // }
  830. }
  831. this.notesToStop.clear();
  832. // }
  833. } catch (ex) {
  834. log.info("PlaybackManager.stoppAllCurrentlyPlayingNotes: ", ex);
  835. }
  836. }
  837. protected doReset(shallPrecount: boolean, preCountMeasures: number = 1): void {
  838. this.nextIteratorTimestamp = undefined;
  839. this.playNextMetronomeAt = undefined;
  840. this.closestNextTimestamp = undefined;
  841. this.currentMeasure = undefined;
  842. this.beatCounter = 0;
  843. this.fermataActive = false;
  844. this.stopAllCurrentlyPlayingNotes();
  845. if (this.musicPartManager !== undefined) {
  846. this.cursorIterator = this.musicPartManager.getIterator();
  847. }
  848. if (this.cursorIterator === undefined) {
  849. return;
  850. }
  851. this.playbackIterator.Reset();
  852. this.currentIteratorSourceTimeStamp = this.cursorIterator.CurrentSourceTimestamp;
  853. this.nextIteratorTimestamp = this.cursorIterator.CurrentEnrolledTimestamp;
  854. this.currentMeasure = this.cursorIterator.CurrentMeasure;
  855. this.currentMeasureIndex = this.cursorIterator.CurrentMeasureIndex;
  856. // this.currentRepetition = this.cursorIterator.CurrentRepetition;
  857. this.startRhythmBeats = this.cursorIterator.currentPlaybackSettings().Rhythm.Numerator;
  858. this.startRhythmDenominator = this.cursorIterator.currentPlaybackSettings().Rhythm.Denominator;
  859. let preCountDuration: Fraction = new Fraction();
  860. if (shallPrecount) {
  861. this.isPreCounting = true;
  862. const rhythmDuration: Fraction = new Fraction(this.startRhythmBeats * preCountMeasures, this.startRhythmDenominator);
  863. const sourceMeasureDuration: Fraction = this.musicPartManager.MusicSheet.SourceMeasures[this.currentMeasureIndex].Duration;
  864. const measureDuration: Fraction = new Fraction(sourceMeasureDuration.Numerator * preCountMeasures, sourceMeasureDuration.Denominator);
  865. const duration: Fraction =
  866. Fraction.plus(this.musicPartManager.MusicSheet.SourceMeasures[this.currentMeasureIndex].AbsoluteTimestamp,
  867. measureDuration).Sub(this.currentIteratorSourceTimeStamp);
  868. preCountDuration = rhythmDuration;
  869. if (rhythmDuration.gte(duration)) { // make sure that missing duration can't get negative (e.g. if measure is longer that given rhythm.
  870. const missingDuration: Fraction = Fraction.minus(rhythmDuration, duration);
  871. if (missingDuration.RealValue / rhythmDuration.RealValue < 0.5) {
  872. preCountDuration.Add(missingDuration);
  873. } else {
  874. preCountDuration = missingDuration;
  875. }
  876. }
  877. }
  878. this.currentMetronomeBaseTimestamp = this.playNextMetronomeAt = Fraction.minus(this.cursorIterator.CurrentEnrolledTimestamp, preCountDuration);
  879. //this.timingSource.reset();
  880. this.timingSource.setTimeAndBpm(this.currentMetronomeBaseTimestamp,
  881. this.cursorIterator.currentPlaybackSettings().BeatsPerMinute);
  882. this.calculateClosestNextTimestamp();
  883. }
  884. /// <summary>
  885. /// Calculate the closest next timestamp at which the next instruction has to be processed
  886. /// </summary>
  887. private calculateClosestNextTimestamp(): void {
  888. const timestamps: Fraction[] = [];
  889. // add next timestamp for stopping notes
  890. if (this.notesToStop.size() > 0) {
  891. // timestamps.push(this.notesToStop.keys().Min());
  892. // TODO MB: Check if line below does what line above is supposed to do
  893. timestamps.push(this.notesToStop.keys().reduce( (a, b) => a.lt(b) ? a : b));
  894. }
  895. // add next timestamp for next notes or other sheet instruction
  896. if (this.playbackIterator.NextEntryTimestamp !== undefined) {
  897. timestamps.push(this.playbackIterator.NextEntryTimestamp);
  898. }
  899. if (this.nextIteratorTimestamp !== undefined) {
  900. timestamps.push(this.nextIteratorTimestamp);
  901. }
  902. // add next timestamp for metronome tick
  903. if (this.playNextMetronomeAt !== undefined) {
  904. timestamps.push(this.playNextMetronomeAt);
  905. }
  906. // get the closest next timestamp
  907. if (timestamps.length > 0) {
  908. // this.closestNextTimestamp = timestamps.Min();
  909. // TODO MB: Check if line below does what line above is supposed to do
  910. this.closestNextTimestamp = timestamps.reduce( (a, b) => a.lt(b) ? a : b);
  911. } else {
  912. this.closestNextTimestamp = undefined;
  913. }
  914. }
  915. /// <summary>
  916. /// Called when the end of the sheet or the selection has been reached
  917. /// </summary>
  918. protected handleEndReached(): void {
  919. this.pause();
  920. }
  921. /// <summary>
  922. /// Fire a delegate to inform the display, that the cursor position has changed
  923. /// </summary>
  924. /// <param name="resetOccurred"></param>
  925. private updateScoreCursorPosition(resetOccurred: boolean): void {
  926. if (this.isPreCounting && !this.MoveCursorDuringPrecount) {
  927. return;
  928. }
  929. this.scorePositionChangedData.CurrentMeasureIndex = this.currentMeasureIndex;
  930. this.scorePositionChangedData.CurrentRepetition = this.currentRepetition;
  931. this.scorePositionChangedData.PredictedPosition = this.currentTimestamp;
  932. this.scorePositionChangedData.CurrentBpm = this.musicPartManager.MusicSheet.SheetPlaybackSetting.BeatsPerMinute;
  933. this.scorePositionChangedData.ResetOccurred = resetOccurred;
  934. for (const listener of this.listeners) {
  935. listener.cursorPositionChanged(this.currentIteratorSourceTimeStamp, this.scorePositionChangedData);
  936. }
  937. }
  938. private stopMetronomeSound(): void {
  939. if (this.metronomeSoundPlayed) {
  940. if (this.audioPlayer !== undefined) {
  941. this.audioPlayer.stopSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key);
  942. this.audioPlayer.stopSound(this.metronomeNote.channel, this.metronomeNote.key);
  943. }
  944. this.metronomeSoundPlayed = false;
  945. }
  946. }
  947. private playMetronomeSound(playFirstBeatSample: boolean): void {
  948. // play the metronome if needed:
  949. if (this.metronome.Audible ||
  950. this.metronome.Solo ||
  951. this.isPreCounting) {
  952. let volume: number = this.isPreCounting ? this.metronome.PreCountVolume : this.metronome.Volume;
  953. if (!this.isPreCounting && this.SoloActive && !this.metronome.Solo) {
  954. volume *= this.SoloAttenuationValue;
  955. }
  956. if (volume > 0) {
  957. if (playFirstBeatSample) {
  958. try {
  959. if (this.audioPlayer !== undefined) {
  960. this.audioPlayer.playSound(this.metronomeNoteFirstBeat.channel, this.metronomeNoteFirstBeat.key, volume, 1000);
  961. }
  962. if (this.audioMetronomePlayer !== undefined) {
  963. this.audioMetronomePlayer.playFirstBeatSample(volume);
  964. }
  965. } catch (ex) {
  966. log.info("PlaybackManager.playMetronomeSound: ", ex);
  967. }
  968. } else {
  969. try {
  970. if (this.audioPlayer !== undefined) {
  971. this.audioPlayer.playSound(this.metronomeNote.channel, this.metronomeNote.key, volume, 1000);
  972. }
  973. if (this.audioMetronomePlayer !== undefined) {
  974. this.audioMetronomePlayer.playBeatSample(volume);
  975. }
  976. } catch (ex) {
  977. log.info("PlaybackManager.playMetronomeSound: ", ex);
  978. }
  979. }
  980. this.metronomeSoundPlayed = true;
  981. }
  982. }
  983. }
  984. private stopFinishedNotes(): void {
  985. // do the pending note stops:
  986. let expiredKeys: Fraction[];
  987. if (this.currentTimestamp !== undefined) {
  988. expiredKeys = this.notesToStop.keys().filter(ts => ts.lte(this.currentTimestamp));
  989. } else {
  990. expiredKeys = this.notesToStop.keys();
  991. }
  992. for (const timestamp of expiredKeys) {
  993. const notesToStop: ChannelNote[] = this.notesToStop.getValue(timestamp);
  994. if (this.audioPlayer !== undefined) {
  995. for (const note of notesToStop) {
  996. this.audioPlayer.stopSound(note.channel, note.key);
  997. }
  998. }
  999. /*** Inform about which notes are now stopped ***
  1000. * e.g. for updating graphics
  1001. */
  1002. const notes: Note[] = [];
  1003. for (const note of notesToStop) {
  1004. note.note.ParentNote.state = NoteState.Normal;
  1005. notes.push(note.note.ParentNote);
  1006. }
  1007. if (this.highlightPlayedNotes) {
  1008. // TODO: Replace with generic event system
  1009. // if (this.NotesPlaybackEventOccurred !== undefined) {
  1010. // this.NotesPlaybackEventOccurred(notes);
  1011. // }
  1012. }
  1013. this.notesToStop.remove(timestamp);
  1014. }
  1015. }
  1016. private processTempoInstructions(): void {
  1017. // 1. check if the current bpm of the iterator have changed (significantly):
  1018. if (Math.abs(this.currentReferenceBPM - this.cursorIterator.CurrentBpm) > 0.001) {
  1019. this.changeTempo(this.cursorIterator.CurrentBpm);
  1020. }
  1021. // 2. check for possible fermatas and slow down for that entry:
  1022. this.handleFermata();
  1023. }
  1024. private handleFermata(): void {
  1025. // check for fermatas:
  1026. let fermataFound: boolean = false;
  1027. if (!this.cursorIterator.EndReached) {
  1028. if (this.currentTimestamp.gte(this.cursorIterator.CurrentEnrolledTimestamp)) {
  1029. for (const ve of this.cursorIterator.CurrentVoiceEntries) {
  1030. fermataFound = ve.Fermata !== undefined;
  1031. }
  1032. }
  1033. }
  1034. if (fermataFound) {
  1035. if (!this.fermataActive) {
  1036. this.fermataActive = true;
  1037. this.changeTempo(this.cursorIterator.CurrentBpm / 3);
  1038. }
  1039. } else {
  1040. if (this.fermataActive) {
  1041. this.fermataActive = false;
  1042. this.changeTempo(this.cursorIterator.CurrentBpm);
  1043. }
  1044. }
  1045. }
  1046. public bpmChanged(newBpm: number): void {
  1047. this.currentBPM = newBpm;
  1048. this.timingSource.setBpm(newBpm);
  1049. }
  1050. public volumeChanged(instrument: number, newVolume: number): void {
  1051. this.currentVolume = newVolume / 100;
  1052. if (instrument === -1) {
  1053. this.metronome.Volume = this.currentVolume;
  1054. } else {
  1055. this.instrumentIdMapping.getValue(instrument).Volume = this.currentVolume;
  1056. }
  1057. }
  1058. public volumeMute(instrument: number): void {
  1059. if (instrument === -1) {
  1060. this.metronome.Mute = true;
  1061. } else {
  1062. this.instrumentIdMapping.getValue(instrument).Audible = false;
  1063. }
  1064. }
  1065. public volumeUnmute(instrument: number): void {
  1066. if (instrument === -1) {
  1067. this.metronome.Mute = false;
  1068. } else {
  1069. this.instrumentIdMapping.getValue(instrument).Audible = true;
  1070. }
  1071. }
  1072. private changeTempo(newTempoInBPM: number): void {
  1073. log.debug("PlaybackManager.changeTempo", `current tempo in BPM: ${newTempoInBPM}`);
  1074. //Console.WriteLine(currTempoInBPM.ToString());
  1075. if (newTempoInBPM > 0) {
  1076. this.currentReferenceBPM = newTempoInBPM;
  1077. this.setTempo();
  1078. }
  1079. }
  1080. protected setTempo(): void {
  1081. this.currentBPM = this.tempoUserFactor * this.getCurrentReferenceBPM();
  1082. this.timingSource.setBpm(this.currentBPM);
  1083. }
  1084. protected getCurrentReferenceBPM(): number {
  1085. return ((this.currentReferenceBPM - this.sheetStartBPM) * this.tempoImpactFactor + this.sheetStartBPM);
  1086. }
  1087. public checkForSoloDeactivated(): void {
  1088. if (this.musicPartManager.MusicSheet === undefined) {
  1089. this.SoloActive = false;
  1090. return;
  1091. }
  1092. let state: boolean = false;
  1093. for (const instrument of this.musicPartManager.MusicSheet.Instruments) {
  1094. for (const staff of instrument.Staves) {
  1095. state = state || staff.Solo;
  1096. }
  1097. for (const voice of instrument.Voices) {
  1098. state = state || voice.Solo;
  1099. }
  1100. }
  1101. state = state || this.Metronome.Solo;
  1102. if (!state) {
  1103. this.SoloActive = false;
  1104. }
  1105. }
  1106. /** Returns the duration of the piece in ms. Including repeats. */
  1107. public getSheetDurationInMs(): number {
  1108. return this.timingSource.getDurationInMs(this.musicPartManager.MusicSheet.SheetEndTimestamp);
  1109. }
  1110. //private class MidiChannelInfo
  1111. //{
  1112. // public List<IInstrument> subscribers = new List<IInstrument>();
  1113. // public int channel;
  1114. //}
  1115. }