-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathMidiFileGenerator.ts
1378 lines (1276 loc) · 58.8 KB
/
MidiFileGenerator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ControllerType } from '@src/midi/ControllerType';
import { IMidiFileHandler } from '@src/midi/IMidiFileHandler';
import { MidiPlaybackController } from '@src/midi/MidiPlaybackController';
import { MasterBarTickLookup } from '@src/midi/MasterBarTickLookup';
import { MidiTickLookup } from '@src/midi/MidiTickLookup';
import { MidiUtils } from '@src/midi/MidiUtils';
import { AccentuationType } from '@src/model/AccentuationType';
import { Automation, AutomationType } from '@src/model/Automation';
import { Bar } from '@src/model/Bar';
import { Beat } from '@src/model/Beat';
import { BendPoint } from '@src/model/BendPoint';
import { BendStyle } from '@src/model/BendStyle';
import { BendType } from '@src/model/BendType';
import { BrushType } from '@src/model/BrushType';
import { Duration } from '@src/model/Duration';
import { GraceType } from '@src/model/GraceType';
import { MasterBar } from '@src/model/MasterBar';
import { Note } from '@src/model/Note';
import { PlaybackInformation } from '@src/model/PlaybackInformation';
import { Score } from '@src/model/Score';
import { SimileMark } from '@src/model/SimileMark';
import { SlideInType } from '@src/model/SlideInType';
import { SlideOutType } from '@src/model/SlideOutType';
import { Staff } from '@src/model/Staff';
import { Track } from '@src/model/Track';
import { TripletFeel } from '@src/model/TripletFeel';
import { VibratoType } from '@src/model/VibratoType';
import { Voice } from '@src/model/Voice';
import { WhammyType } from '@src/model/WhammyType';
import { NotationMode } from '@src/NotationSettings';
import { Settings } from '@src/Settings';
import { Logger } from '@src/Logger';
import { SynthConstants } from '@src/synth/SynthConstants';
import { PercussionMapper } from '@src/model/PercussionMapper';
export class MidiNoteDuration {
public noteOnly: number = 0;
public untilTieOrSlideEnd: number = 0;
public letRingEnd: number = 0;
}
class TripletFeelDurations {
public firstBeatDuration: number = 0;
public secondBeatStartOffset: number = 0;
public secondBeatDuration: number = 0;
}
/**
* This generator creates a midi file using a score.
*/
export class MidiFileGenerator {
private static readonly DefaultDurationDead: number = 30;
private static readonly DefaultDurationPalmMute: number = 80;
private readonly _score: Score;
private _settings: Settings;
private _handler: IMidiFileHandler;
private _currentTempo: number = 0;
private _programsPerChannel: Map<number, number> = new Map<number, number>();
/**
* Gets a lookup object which can be used to quickly find beats and bars
* at a given midi tick position.
*/
public readonly tickLookup: MidiTickLookup = new MidiTickLookup();
/**
* Gets or sets whether transposition pitches should be applied to the individual midi events or not.
*/
public applyTranspositionPitches: boolean = true;
/**
* Gets the transposition pitches for the individual midi channels.
*/
public readonly transpositionPitches: Map<number, number> = new Map<number, number>();
/**
* Initializes a new instance of the {@link MidiFileGenerator} class.
* @param score The score for which the midi file should be generated.
* @param settings The settings ot use for generation.
* @param handler The handler that should be used for generating midi events.
*/
public constructor(score: Score, settings: Settings | null, handler: IMidiFileHandler) {
this._score = score;
this._settings = !settings ? new Settings() : settings;
this._currentTempo = this._score.tempo;
this._handler = handler;
}
/**
* Starts the generation of the midi file.
*/
public generate(): void {
this.transpositionPitches.clear();
// initialize tracks
for (const track of this._score.tracks) {
this.generateTrack(track);
}
Logger.debug('Midi', 'Begin midi generation');
const controller: MidiPlaybackController = new MidiPlaybackController(this._score);
let previousMasterBar: MasterBar | null = null;
// store the previous played bar for repeats
while (!controller.finished) {
const index: number = controller.index;
const bar: MasterBar = this._score.masterBars[index];
const currentTick: number = controller.currentTick;
controller.processCurrent();
if (controller.shouldPlay) {
this.generateMasterBar(bar, previousMasterBar, currentTick);
for (const track of this._score.tracks) {
for (const staff of track.staves) {
if (index < staff.bars.length) {
this.generateBar(staff.bars[index], currentTick);
}
}
}
}
controller.moveNext();
previousMasterBar = bar;
}
for (const track of this._score.tracks) {
this._handler.finishTrack(track.index, controller.currentTick);
}
Logger.debug('Midi', 'Midi generation done');
}
private generateTrack(track: Track): void {
// channel
this.generateChannel(track, track.playbackInfo.primaryChannel, track.playbackInfo);
if (track.playbackInfo.primaryChannel !== track.playbackInfo.secondaryChannel) {
this.generateChannel(track, track.playbackInfo.secondaryChannel, track.playbackInfo);
}
}
private addProgramChange(track: Track, tick: number, channel: number, program: number) {
if (!this._programsPerChannel.has(channel) || this._programsPerChannel.get(channel) !== program) {
this._handler.addProgramChange(track.index, tick, channel, program);
this._programsPerChannel.set(channel, program);
}
}
public static buildTranspositionPitches(score: Score, settings: Settings): Map<number, number> {
const transpositionPitches = new Map<number, number>();
for (const track of score.tracks) {
const transpositionPitch = track.index < settings.notation.transpositionPitches.length
? settings.notation.transpositionPitches[track.index]
: 0;
transpositionPitches.set(track.playbackInfo.primaryChannel, transpositionPitch);
transpositionPitches.set(track.playbackInfo.secondaryChannel, transpositionPitch);
}
return transpositionPitches;
}
private generateChannel(track: Track, channel: number, playbackInfo: PlaybackInformation): void {
const transpositionPitch = track.index < this._settings.notation.transpositionPitches.length
? this._settings.notation.transpositionPitches[track.index]
: 0;
this.transpositionPitches.set(channel, transpositionPitch);
let volume: number = MidiFileGenerator.toChannelShort(playbackInfo.volume);
let balance: number = MidiFileGenerator.toChannelShort(playbackInfo.balance);
this._handler.addControlChange(track.index, 0, channel, ControllerType.VolumeCoarse, volume);
this._handler.addControlChange(track.index, 0, channel, ControllerType.PanCoarse, balance);
this._handler.addControlChange(track.index, 0, channel, ControllerType.ExpressionControllerCoarse, 127);
// set parameter that is being updated (0) -> PitchBendRangeCoarse
this._handler.addControlChange(track.index, 0, channel, ControllerType.RegisteredParameterFine, 0);
this._handler.addControlChange(track.index, 0, channel, ControllerType.RegisteredParameterCourse, 0);
// Set PitchBendRangeCoarse to 12
this._handler.addControlChange(track.index, 0, channel, ControllerType.DataEntryFine, 0);
this._handler.addControlChange(
track.index,
0,
channel,
ControllerType.DataEntryCoarse,
MidiFileGenerator.PitchBendRangeInSemitones
);
this.addProgramChange(track, 0, channel, playbackInfo.program);
}
private static toChannelShort(data: number): number {
const value: number = Math.max(-32768, Math.min(32767, data * 8 - 1));
return Math.max(value, -1) + 1;
}
private generateMasterBar(masterBar: MasterBar, previousMasterBar: MasterBar | null, currentTick: number): void {
// time signature
if (
!previousMasterBar ||
previousMasterBar.timeSignatureDenominator !== masterBar.timeSignatureDenominator ||
previousMasterBar.timeSignatureNumerator !== masterBar.timeSignatureNumerator
) {
this._handler.addTimeSignature(
currentTick,
masterBar.timeSignatureNumerator,
masterBar.timeSignatureDenominator
);
}
// tempo
if (masterBar.tempoAutomation) {
this._handler.addTempo(currentTick, masterBar.tempoAutomation.value);
this._currentTempo = masterBar.tempoAutomation.value;
} else if (!previousMasterBar) {
this._handler.addTempo(currentTick, masterBar.score.tempo);
this._currentTempo = masterBar.score.tempo;
}
const masterBarLookup: MasterBarTickLookup = new MasterBarTickLookup();
masterBarLookup.masterBar = masterBar;
masterBarLookup.start = currentTick;
masterBarLookup.tempo = this._currentTempo;
masterBarLookup.end = masterBarLookup.start + masterBar.calculateDuration();
this.tickLookup.addMasterBar(masterBarLookup);
}
private generateBar(bar: Bar, barStartTick: number): void {
let playbackBar: Bar = this.getPlaybackBar(bar);
for (const v of playbackBar.voices) {
this.generateVoice(v, barStartTick, bar);
}
}
private getPlaybackBar(bar: Bar): Bar {
switch (bar.simileMark) {
case SimileMark.Simple:
if (bar.previousBar) {
bar = this.getPlaybackBar(bar.previousBar);
}
break;
case SimileMark.FirstOfDouble:
if (bar.previousBar && bar.previousBar.previousBar) {
bar = this.getPlaybackBar(bar.previousBar.previousBar);
}
break;
case SimileMark.SecondOfDouble:
if (bar.previousBar && bar.previousBar.previousBar) {
bar = this.getPlaybackBar(bar.previousBar.previousBar);
}
break;
}
return bar;
}
private generateVoice(voice: Voice, barStartTick: number, realBar: Bar): void {
if (voice.isEmpty && (!voice.bar.isEmpty || voice.index !== 0)) {
return;
}
for (const b of voice.beats) {
this.generateBeat(b, barStartTick, realBar);
}
}
private _currentTripletFeel: TripletFeelDurations | null = null;
private generateBeat(beat: Beat, barStartTick: number, realBar: Bar): void {
let beatStart: number = beat.playbackStart;
let audioDuration: number = beat.playbackDuration;
if (beat.voice.bar.isEmpty) {
audioDuration = beat.voice.bar.masterBar.calculateDuration();
} else if (
beat.voice.bar.masterBar.tripletFeel !== TripletFeel.NoTripletFeel &&
this._settings.player.playTripletFeel
) {
if (this._currentTripletFeel) {
beatStart -= this._currentTripletFeel.secondBeatStartOffset;
audioDuration = this._currentTripletFeel.secondBeatDuration;
this._currentTripletFeel = null;
} else {
this._currentTripletFeel = MidiFileGenerator.calculateTripletFeelInfo(beatStart, audioDuration, beat);
if (this._currentTripletFeel) {
audioDuration = this._currentTripletFeel.firstBeatDuration;
}
}
}
// in case of normal playback register playback
if (realBar === beat.voice.bar) {
this.tickLookup.addBeat(beat, beatStart, audioDuration);
} else {
// in case of simile marks where we repeat we also register
this.tickLookup.addBeat(beat, 0, audioDuration);
}
const track: Track = beat.voice.bar.staff.track;
for (const automation of beat.automations) {
this.generateAutomation(beat, automation, barStartTick);
}
if (beat.isRest) {
this._handler.addRest(track.index, barStartTick + beatStart, track.playbackInfo.primaryChannel);
} else {
let brushInfo = this.getBrushInfo(beat);
for (const n of beat.notes) {
this.generateNote(n, barStartTick + beatStart, audioDuration, brushInfo);
}
}
if (beat.vibrato !== VibratoType.None) {
let phaseLength: number = 240;
let bendAmplitude: number = 3;
switch (beat.vibrato) {
case VibratoType.Slight:
phaseLength = this._settings.player.vibrato.beatSlightLength;
bendAmplitude = this._settings.player.vibrato.beatSlightAmplitude;
break;
case VibratoType.Wide:
phaseLength = this._settings.player.vibrato.beatWideLength;
bendAmplitude = this._settings.player.vibrato.beatWideAmplitude;
break;
}
this.generateVibratorWithParams(
barStartTick + beatStart,
beat.playbackDuration,
phaseLength,
bendAmplitude,
(tick, value) => {
this._handler.addBend(
beat.voice.bar.staff.track.index,
tick,
track.playbackInfo.secondaryChannel,
value
);
}
);
}
}
private static calculateTripletFeelInfo(
beatStart: number,
audioDuration: number,
beat: Beat
): TripletFeelDurations | null {
let initialDuration: Duration;
switch (beat.voice.bar.masterBar.tripletFeel) {
case TripletFeel.Triplet8th:
case TripletFeel.Dotted8th:
case TripletFeel.Scottish8th:
initialDuration = Duration.Eighth;
break;
case TripletFeel.Triplet16th:
case TripletFeel.Dotted16th:
case TripletFeel.Scottish16th:
initialDuration = Duration.Sixteenth;
break;
default:
// not possible
return null;
}
const interval: number = MidiUtils.toTicks(initialDuration);
// it must be a plain note with the expected duration
// without dots, triplets, grace notes etc.
if (audioDuration !== interval) {
return null;
}
// check if the beat is aligned in respect to the duration
// e.g. the eighth notes on a 4/4 time signature must start exactly on the following
// times to get a triplet feel applied
// 0 480 960 1440 1920 2400 2880 3360
if (beatStart % interval !== 0) {
return null;
}
// ensure next beat matches spec
if (!beat.nextBeat || beat.nextBeat.voice !== beat.voice || beat.playbackDuration !== interval) {
return null;
}
// looks like we have a triplet feel combination start here!
const durations: TripletFeelDurations = new TripletFeelDurations();
switch (beat.voice.bar.masterBar.tripletFeel) {
case TripletFeel.Triplet8th:
durations.firstBeatDuration = MidiUtils.applyTuplet(MidiUtils.toTicks(Duration.Quarter), 3, 2);
durations.secondBeatDuration = MidiUtils.applyTuplet(MidiUtils.toTicks(Duration.Eighth), 3, 2);
break;
case TripletFeel.Dotted8th:
durations.firstBeatDuration = MidiUtils.applyDot(MidiUtils.toTicks(Duration.Eighth), false);
durations.secondBeatDuration = MidiUtils.toTicks(Duration.Sixteenth);
break;
case TripletFeel.Scottish8th:
durations.firstBeatDuration = MidiUtils.toTicks(Duration.Sixteenth);
durations.secondBeatDuration = MidiUtils.applyDot(MidiUtils.toTicks(Duration.Eighth), false);
break;
case TripletFeel.Triplet16th:
durations.firstBeatDuration = MidiUtils.applyTuplet(MidiUtils.toTicks(Duration.Eighth), 3, 2);
durations.secondBeatDuration = MidiUtils.applyTuplet(MidiUtils.toTicks(Duration.Sixteenth), 3, 2);
break;
case TripletFeel.Dotted16th:
durations.firstBeatDuration = MidiUtils.applyDot(MidiUtils.toTicks(Duration.Sixteenth), false);
durations.secondBeatDuration = MidiUtils.toTicks(Duration.ThirtySecond);
break;
case TripletFeel.Scottish16th:
durations.firstBeatDuration = MidiUtils.toTicks(Duration.ThirtySecond);
durations.secondBeatDuration = MidiUtils.applyDot(MidiUtils.toTicks(Duration.Sixteenth), false);
break;
}
// calculate the number of ticks the second beat can start earlier
durations.secondBeatStartOffset = audioDuration - durations.firstBeatDuration;
return durations;
}
private generateNote(note: Note, beatStart: number, beatDuration: number, brushInfo: Int32Array): void {
const track: Track = note.beat.voice.bar.staff.track;
const staff: Staff = note.beat.voice.bar.staff;
let noteKey: number = note.calculateRealValue(this.applyTranspositionPitches, true);
if (note.isPercussion) {
const articulation = PercussionMapper.getArticulation(note);
if (articulation) {
noteKey = articulation.outputMidiNumber;
}
}
const brushOffset: number = note.isStringed && note.string <= brushInfo.length ? brushInfo[note.string - 1] : 0;
const noteStart: number = beatStart + brushOffset;
const noteDuration: MidiNoteDuration = this.getNoteDuration(note, beatDuration);
noteDuration.untilTieOrSlideEnd -= brushOffset;
noteDuration.noteOnly -= brushOffset;
noteDuration.letRingEnd -= brushOffset;
const velocity: number = MidiFileGenerator.getNoteVelocity(note);
const channel: number =
note.hasBend || note.beat.hasWhammyBar || note.beat.vibrato !== VibratoType.None
? track.playbackInfo.secondaryChannel
: track.playbackInfo.primaryChannel;
let initialBend: number = 0;
if (note.hasBend) {
initialBend = MidiFileGenerator.getPitchWheel(note.bendPoints![0].value);
} else if (note.beat.hasWhammyBar) {
initialBend = MidiFileGenerator.getPitchWheel(note.beat.whammyBarPoints![0].value);
} else if (
note.isTieDestination ||
(note.slideOrigin && note.slideOrigin.slideOutType === SlideOutType.Legato)
) {
initialBend = -1;
} else {
initialBend = MidiFileGenerator.getPitchWheel(0);
}
if (initialBend >= 0) {
this._handler.addNoteBend(track.index, noteStart, channel, noteKey, initialBend);
}
//
// Fade in
if (note.beat.fadeIn) {
this.generateFadeIn(note, noteStart, noteDuration);
}
//
// Trill
if (note.isTrill && !staff.isPercussion) {
this.generateTrill(note, noteStart, noteDuration, noteKey, velocity, channel);
// no further generation needed
return;
}
//
// Tremolo Picking
if (note.beat.isTremolo) {
this.generateTremoloPicking(note, noteStart, noteDuration, noteKey, velocity, channel);
// no further generation needed
return;
}
//
// All String Bending/Variation effects
if (note.hasBend) {
this.generateBend(note, noteStart, noteDuration, noteKey, channel);
} else if (note.beat.hasWhammyBar && note.index === 0) {
this.generateWhammy(note.beat, noteStart, noteDuration, channel);
} else if (note.slideInType !== SlideInType.None || note.slideOutType !== SlideOutType.None) {
this.generateSlide(note, noteStart, noteDuration, noteKey, channel);
} else if (note.vibrato !== VibratoType.None || (note.isTieDestination && note.tieOrigin!.vibrato !== VibratoType.None)) {
this.generateVibrato(note, noteStart, noteDuration, noteKey, channel);
}
// for tied notes, and target notes of legato slides we do not pick the note
// the previous one is extended
if (!note.isTieDestination && (!note.slideOrigin || note.slideOrigin.slideOutType !== SlideOutType.Legato)) {
let noteSoundDuration: number = Math.max(noteDuration.untilTieOrSlideEnd, noteDuration.letRingEnd);
this._handler.addNote(track.index, noteStart, noteSoundDuration, noteKey, velocity, channel);
}
}
private getNoteDuration(note: Note, duration: number): MidiNoteDuration {
const durationWithEffects: MidiNoteDuration = new MidiNoteDuration();
durationWithEffects.noteOnly = duration;
durationWithEffects.untilTieOrSlideEnd = duration;
durationWithEffects.letRingEnd = duration;
if (note.isDead) {
durationWithEffects.noteOnly = this.applyStaticDuration(MidiFileGenerator.DefaultDurationDead, duration);
durationWithEffects.untilTieOrSlideEnd = durationWithEffects.noteOnly;
durationWithEffects.letRingEnd = durationWithEffects.noteOnly;
return durationWithEffects;
}
if (note.isPalmMute) {
durationWithEffects.noteOnly = this.applyStaticDuration(
MidiFileGenerator.DefaultDurationPalmMute,
duration
);
durationWithEffects.untilTieOrSlideEnd = durationWithEffects.noteOnly;
durationWithEffects.letRingEnd = durationWithEffects.noteOnly;
return durationWithEffects;
}
if (note.isStaccato) {
durationWithEffects.noteOnly = (duration / 2) | 0;
durationWithEffects.untilTieOrSlideEnd = durationWithEffects.noteOnly;
durationWithEffects.letRingEnd = durationWithEffects.noteOnly;
return durationWithEffects;
}
if (note.isTieOrigin) {
const endNote: Note = note.tieDestination!;
// for the initial start of the tie calculate absolute duration from start to end note
if (endNote) {
if (!note.isTieDestination) {
const startTick: number = note.beat.absolutePlaybackStart;
const tieDestinationDuration: MidiNoteDuration = this.getNoteDuration(
endNote,
endNote.beat.playbackDuration
);
const endTick: number =
endNote.beat.absolutePlaybackStart + tieDestinationDuration.untilTieOrSlideEnd;
durationWithEffects.untilTieOrSlideEnd = endTick - startTick;
} else {
// for continuing ties, take the current duration + the one from the destination
// this branch will be entered as part of the recusion of the if branch
const tieDestinationDuration: MidiNoteDuration = this.getNoteDuration(
endNote,
endNote.beat.playbackDuration
);
durationWithEffects.untilTieOrSlideEnd = duration + tieDestinationDuration.untilTieOrSlideEnd;
}
}
} else if (note.slideOutType === SlideOutType.Legato) {
const endNote: Note = note.slideTarget!;
if (endNote) {
const startTick: number = note.beat.absolutePlaybackStart;
const slideTargetDuration: MidiNoteDuration = this.getNoteDuration(
endNote,
endNote.beat.playbackDuration
);
const endTick: number = endNote.beat.absolutePlaybackStart + slideTargetDuration.untilTieOrSlideEnd;
durationWithEffects.untilTieOrSlideEnd = endTick - startTick;
}
}
if (note.isLetRing && this._settings.notation.notationMode === NotationMode.GuitarPro) {
// LetRing ends when:
// - rest
let lastLetRingBeat: Beat = note.beat;
let letRingEnd: number = 0;
const maxDuration: number = note.beat.voice.bar.masterBar.calculateDuration();
while (lastLetRingBeat.nextBeat) {
let next: Beat = lastLetRingBeat.nextBeat;
if (next.isRest) {
break;
}
// note on the same string
if (note.isStringed && next.hasNoteOnString(note.string)) {
break;
}
lastLetRingBeat = lastLetRingBeat.nextBeat;
letRingEnd =
lastLetRingBeat.absolutePlaybackStart -
note.beat.absolutePlaybackStart +
lastLetRingBeat.playbackDuration;
if (letRingEnd > maxDuration) {
letRingEnd = maxDuration;
break;
}
}
if (lastLetRingBeat === note.beat) {
durationWithEffects.letRingEnd = duration;
} else {
durationWithEffects.letRingEnd = letRingEnd;
}
} else {
durationWithEffects.letRingEnd = durationWithEffects.untilTieOrSlideEnd;
}
return durationWithEffects;
}
private applyStaticDuration(duration: number, maximum: number): number {
const value: number = ((this._currentTempo * duration) / BendPoint.MaxPosition) | 0;
return Math.min(value, maximum);
}
private static getNoteVelocity(note: Note): number {
let dynamicValue: number = note.dynamics as number;
// more silent on hammer destination
if (!note.beat.voice.bar.staff.isPercussion && note.hammerPullOrigin) {
dynamicValue--;
}
// more silent on ghost notes
if (note.isGhost) {
dynamicValue--;
}
// louder on accent
switch (note.accentuated) {
case AccentuationType.Normal:
dynamicValue++;
break;
case AccentuationType.Heavy:
dynamicValue += 2;
break;
}
return MidiUtils.dynamicToVelocity(dynamicValue);
}
private generateFadeIn(note: Note, noteStart: number, noteDuration: MidiNoteDuration): void {
const track: Track = note.beat.voice.bar.staff.track;
const endVolume: number = MidiFileGenerator.toChannelShort(track.playbackInfo.volume);
const volumeFactor: number = endVolume / noteDuration.noteOnly;
const tickStep: number = 120;
const steps: number = (noteDuration.noteOnly / tickStep) | 0;
const endTick: number = noteStart + noteDuration.noteOnly;
for (let i: number = steps - 1; i >= 0; i--) {
const tick: number = endTick - i * tickStep;
const volume: number = (tick - noteStart) * volumeFactor;
if (i === steps - 1) {
this._handler.addControlChange(
track.index,
noteStart,
track.playbackInfo.primaryChannel,
ControllerType.VolumeCoarse,
volume
);
this._handler.addControlChange(
track.index,
noteStart,
track.playbackInfo.secondaryChannel,
ControllerType.VolumeCoarse,
volume
);
}
this._handler.addControlChange(
track.index,
tick,
track.playbackInfo.primaryChannel,
ControllerType.VolumeCoarse,
volume
);
this._handler.addControlChange(
track.index,
tick,
track.playbackInfo.secondaryChannel,
ControllerType.VolumeCoarse,
volume
);
}
}
private generateVibrato(
note: Note,
noteStart: number,
noteDuration: MidiNoteDuration,
noteKey: number,
channel: number
): void {
let phaseLength: number = 0;
let bendAmplitude: number = 0;
const vibratoType = note.vibrato !== VibratoType.None ? note.vibrato : (
note.isTieDestination ? note.tieOrigin!.vibrato :
VibratoType.Slight /* should never happen unless called wrongly */
);
switch (vibratoType) {
case VibratoType.Slight:
phaseLength = this._settings.player.vibrato.noteSlightLength;
bendAmplitude = this._settings.player.vibrato.noteSlightAmplitude;
break;
case VibratoType.Wide:
phaseLength = this._settings.player.vibrato.noteWideLength;
bendAmplitude = this._settings.player.vibrato.noteWideAmplitude;
break;
default:
return;
}
const track: Track = note.beat.voice.bar.staff.track;
this.generateVibratorWithParams(noteStart, noteDuration.noteOnly, phaseLength, bendAmplitude, (tick, value) => {
this._handler.addNoteBend(track.index, tick, channel, noteKey, value);
});
}
public vibratoResolution: number = 16;
private generateVibratorWithParams(
noteStart: number,
noteDuration: number,
phaseLength: number,
bendAmplitude: number,
addBend: (tick: number, value: number) => void
): void {
const resolution: number = this.vibratoResolution;
const phaseHalf: number = (phaseLength / 2) | 0;
// 1st Phase stays at bend 0,
// then we have a sine wave with the given amplitude and phase length
noteStart += phaseLength;
const noteEnd: number = noteStart + noteDuration;
while (noteStart < noteEnd) {
let phase: number = 0;
const phaseDuration: number = noteStart + phaseLength < noteEnd ? phaseLength : noteEnd - noteStart;
while (phase < phaseDuration) {
let bend: number = bendAmplitude * Math.sin((phase * Math.PI) / phaseHalf);
addBend((noteStart + phase) | 0, MidiFileGenerator.getPitchWheel(bend));
phase += resolution;
}
noteStart += phaseLength;
}
}
/**
* Maximum semitones that are supported in bends in one direction (up or down)
* GP has 8 full tones on whammys.
*/
private static readonly PitchBendRangeInSemitones = 8 * 2;
/**
* The value on how many pitch-values are used for one semitone
*/
private static readonly PitchValuePerSemitone: number =
SynthConstants.DefaultPitchWheel / MidiFileGenerator.PitchBendRangeInSemitones;
/**
* The minimum number of breakpoints generated per semitone bend.
*/
private static readonly MinBreakpointsPerSemitone = 6;
/**
* How long until a new breakpoint is generated for a bend.
*/
private static readonly MillisecondsPerBreakpoint = 150;
/**
* Calculates the midi pitch wheel value for the give bend value.
*/
public static getPitchWheel(bendValue: number) {
// bend values are 1/4 notes therefore we only take half a semitone value per bend value
return SynthConstants.DefaultPitchWheel + (bendValue / 2) * MidiFileGenerator.PitchValuePerSemitone;
}
private generateSlide(
note: Note,
noteStart: number,
noteDuration: MidiNoteDuration,
noteKey: number,
channel: number
) {
let duration: number =
note.slideOutType === SlideOutType.Legato ? noteDuration.noteOnly : noteDuration.untilTieOrSlideEnd;
let playedBendPoints: BendPoint[] = [];
let track: Track = note.beat.voice.bar.staff.track;
const simpleSlidePitchOffset = this._settings.player.slide.simpleSlidePitchOffset;
const simpleSlideDurationOffset = Math.floor(
BendPoint.MaxPosition * this._settings.player.slide.simpleSlideDurationRatio
);
const shiftSlideDurationOffset = Math.floor(
BendPoint.MaxPosition * this._settings.player.slide.shiftSlideDurationRatio
);
// Shift Slide: Play note, move up to target note, play end note
// Legato Slide: Play note, move up to target note, no pick on end note, just keep it ringing
// 2 bend points: one on 0/0, dy/MaxPos.
// Slide into from above/below: Play note on lower pitch, slide into it quickly at start
// Slide out above/blow: Play note on normal pitch, slide out quickly at end
switch (note.slideInType) {
case SlideInType.IntoFromAbove:
playedBendPoints.push(new BendPoint(0, simpleSlidePitchOffset));
playedBendPoints.push(new BendPoint(simpleSlideDurationOffset, 0));
break;
case SlideInType.IntoFromBelow:
playedBendPoints.push(new BendPoint(0, -simpleSlidePitchOffset));
playedBendPoints.push(new BendPoint(simpleSlideDurationOffset, 0));
break;
}
switch (note.slideOutType) {
case SlideOutType.Legato:
case SlideOutType.Shift:
playedBendPoints.push(new BendPoint(shiftSlideDurationOffset, 0));
// normal note values are in 1/2 tones, bends are in 1/4 tones
const dy = (note.slideTarget!.calculateRealValue(this.applyTranspositionPitches, true) - note.calculateRealValue(this.applyTranspositionPitches, true)) * 2;
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition, dy));
break;
case SlideOutType.OutDown:
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition - simpleSlideDurationOffset, 0));
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition, -simpleSlidePitchOffset));
break;
case SlideOutType.OutUp:
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition - simpleSlideDurationOffset, 0));
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition, simpleSlidePitchOffset));
break;
}
this.generateWhammyOrBend(noteStart, duration, playedBendPoints, (tick, value) => {
this._handler.addNoteBend(track.index, tick, channel, noteKey, value);
});
}
private generateBend(
note: Note,
noteStart: number,
noteDuration: MidiNoteDuration,
noteKey: number,
channel: number
): void {
let bendPoints: BendPoint[] = note.bendPoints!;
let track: Track = note.beat.voice.bar.staff.track;
const addBend: (tick: number, value: number) => void = (tick, value) => {
this._handler.addNoteBend(track.index, tick, channel, noteKey, value);
};
// if bend is extended on next tied note, we directly bend to the final bend value
let finalBendValue: number | null = null;
// Bends are spread across all tied notes unless they have a bend on their own.
let duration: number;
if (note.isTieOrigin && this._settings.notation.extendBendArrowsOnTiedNotes) {
let endNote: Note = note;
while (endNote.isTieOrigin && !endNote.tieDestination!.hasBend) {
endNote = endNote.tieDestination!;
}
duration =
endNote.beat.absolutePlaybackStart -
note.beat.absolutePlaybackStart +
this.getNoteDuration(endNote, endNote.beat.playbackDuration).noteOnly;
} else if (note.isTieOrigin && note.beat.graceType !== GraceType.None) {
switch (note.tieDestination!.bendType) {
case BendType.Bend:
case BendType.BendRelease:
case BendType.PrebendBend:
finalBendValue = note.tieDestination!.bendPoints![1].value;
break;
case BendType.Prebend:
case BendType.PrebendRelease:
finalBendValue = note.tieDestination!.bendPoints![0].value;
break;
}
duration = Math.max(
noteDuration.noteOnly,
MidiUtils.millisToTicks(this._settings.player.songBookBendDuration, this._currentTempo)
);
} else {
duration = noteDuration.noteOnly;
}
// ensure prebends are slightly before the actual note.
if (bendPoints[0].value > 0 && !note.isContinuedBend && noteStart > 0) {
noteStart--;
}
const bendDuration: number = Math.min(
duration,
MidiUtils.millisToTicks(this._settings.player.songBookBendDuration, this._currentTempo)
);
let playedBendPoints: BendPoint[] = [];
switch (note.bendType) {
case BendType.Custom:
playedBendPoints = bendPoints;
break;
case BendType.Bend:
case BendType.Release:
switch (note.bendStyle) {
case BendStyle.Default:
playedBendPoints = bendPoints;
break;
case BendStyle.Gradual:
playedBendPoints.push(new BendPoint(0, note.bendPoints![0].value));
if (!finalBendValue || finalBendValue < note.bendPoints![1].value) {
finalBendValue = note.bendPoints![1].value;
}
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition, finalBendValue));
break;
case BendStyle.Fast:
if (!finalBendValue || finalBendValue < note.bendPoints![1].value) {
finalBendValue = note.bendPoints![1].value;
}
if (note.beat.graceType === GraceType.BendGrace) {
this.generateSongBookWhammyOrBend(
noteStart,
duration,
true,
[note.bendPoints![0].value, finalBendValue],
bendDuration,
addBend
);
} else {
this.generateSongBookWhammyOrBend(
noteStart,
duration,
false,
[note.bendPoints![0].value, finalBendValue],
bendDuration,
addBend
);
}
return;
}
break;
case BendType.BendRelease:
switch (note.bendStyle) {
case BendStyle.Default:
playedBendPoints = bendPoints;
break;
case BendStyle.Gradual:
playedBendPoints.push(new BendPoint(0, note.bendPoints![0].value));
playedBendPoints.push(new BendPoint((BendPoint.MaxPosition / 2) | 0, note.bendPoints![1].value));
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition, note.bendPoints![2].value));
break;
case BendStyle.Fast:
this.generateSongBookWhammyOrBend(
noteStart,
duration,
false,
[note.bendPoints![0].value, note.bendPoints![1].value, note.bendPoints![2].value],
bendDuration,
addBend
);
return;
}
break;
case BendType.Hold:
playedBendPoints = bendPoints;
break;
case BendType.Prebend:
playedBendPoints = bendPoints;
break;
case BendType.PrebendBend:
switch (note.bendStyle) {
case BendStyle.Default:
playedBendPoints = bendPoints;
break;
case BendStyle.Gradual:
playedBendPoints.push(new BendPoint(0, note.bendPoints![0].value));
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition, note.bendPoints![1].value));
break;
case BendStyle.Fast:
const preBendValue: number = MidiFileGenerator.getPitchWheel(note.bendPoints![0].value);
addBend(noteStart, preBendValue | 0);
if (!finalBendValue || finalBendValue < note.bendPoints![1].value) {
finalBendValue = note.bendPoints![1].value;
}
this.generateSongBookWhammyOrBend(
noteStart,
duration,
false,
[note.bendPoints![0].value, finalBendValue],
bendDuration,
addBend
);
return;
}
break;
case BendType.PrebendRelease:
switch (note.bendStyle) {
case BendStyle.Default:
playedBendPoints = bendPoints;
break;
case BendStyle.Gradual:
playedBendPoints.push(new BendPoint(0, note.bendPoints![0].value));
playedBendPoints.push(new BendPoint(BendPoint.MaxPosition, note.bendPoints![1].value));
break;
case BendStyle.Fast:
const preBendValue: number = MidiFileGenerator.getPitchWheel(note.bendPoints![0].value);
addBend(noteStart, preBendValue | 0);
this.generateSongBookWhammyOrBend(
noteStart,
duration,
false,
[note.bendPoints![0].value, note.bendPoints![1].value],
bendDuration,
addBend
);
return;
}
break;
}
this.generateWhammyOrBend(noteStart, duration, playedBendPoints, addBend);
}
private generateSongBookWhammyOrBend(
noteStart: number,
duration: number,