-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
rendermidi.cpp
2682 lines (2396 loc) · 118 KB
/
rendermidi.cpp
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
//=============================================================================
// MuseScore
// Music Composition & Notation
//
// Copyright (C) 2002-2012 Werner Schweer
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2
// as published by the Free Software Foundation and appearing in
// the file LICENCE.GPL
//=============================================================================
/**
\file
render score into event list
*/
#include <set>
#include "rendermidi.h"
#include "score.h"
#include "volta.h"
#include "note.h"
#include "glissando.h"
#include "instrument.h"
#include "part.h"
#include "chord.h"
#include "trill.h"
#include "vibrato.h"
#include "style.h"
#include "slur.h"
#include "tie.h"
#include "stafftext.h"
#include "repeat.h"
#include "articulation.h"
#include "arpeggio.h"
#include "durationtype.h"
#include "measure.h"
#include "tempo.h"
#include "repeatlist.h"
#include "velo.h"
#include "dynamic.h"
#include "navigate.h"
#include "pedal.h"
#include "staff.h"
#include "hairpin.h"
#include "bend.h"
#include "tremolo.h"
#include "noteevent.h"
#include "synthesizer/event.h"
#include "segment.h"
#include "undo.h"
#include "utils.h"
#include "sym.h"
#include "synthesizerstate.h"
namespace Ms {
//int printNoteEventLists(NoteEventList el, int prefix, int j){
// int k=0;
// for (NoteEvent event : el) {
// qDebug("%d: %d: %d pitch=%d ontime=%d duration=%d",prefix, j, k, event.pitch(), event.ontime(), event.len());
// k++;
// }
// return 0;
//}
//int printNoteEventLists(QList<NoteEventList> ell, int prefix){
// int j=0;
// for (NoteEventList el : ell) {
// printNoteEventLists(el,prefix,j);
// j++;
// }
// return 0;
//}
struct StaffRenderData {
Fraction lastHairpinStart = Fraction(-1, 1);
Fraction lastDynamicEnd = Fraction(-1, 1);
std::map<int, NPlayEvent> tempPlayEvents;
};
bool graceNotesMerged(Chord *chord);
//---------------------------------------------------------
// updateSwing
//---------------------------------------------------------
void Score::updateSwing()
{
for (Staff* s : _staves) {
s->clearSwingList();
}
Measure* fm = firstMeasure();
if (!fm)
return;
for (Segment* s = fm->first(SegmentType::ChordRest); s; s = s->next1(SegmentType::ChordRest)) {
for (const Element* e : s->annotations()) {
if (!e->isStaffTextBase())
continue;
const StaffTextBase* st = toStaffTextBase(e);
if (st->xmlText().isEmpty())
continue;
Staff* staff = st->staff();
if (!st->swing())
continue;
SwingParameters sp;
sp.swingRatio = st->swingParameters()->swingRatio;
sp.swingUnit = st->swingParameters()->swingUnit;
if (st->systemFlag()) {
for (Staff* sta : _staves) {
sta->insertIntoSwingList(s->tick(),sp);
}
}
else
staff->insertIntoSwingList(s->tick(),sp);
}
}
}
//---------------------------------------------------------
// updateCapo
//---------------------------------------------------------
void Score::updateCapo()
{
for (Staff* s : _staves) {
s->clearCapoList();
}
Measure* fm = firstMeasure();
if (!fm)
return;
for (Segment* s = fm->first(SegmentType::ChordRest); s; s = s->next1(SegmentType::ChordRest)) {
for (const Element* e : s->annotations()) {
if (!e->isStaffTextBase())
continue;
const StaffTextBase* st = toStaffTextBase(e);
if (st->xmlText().isEmpty())
continue;
Staff* staff = st->staff();
if (st->capo() == 0)
continue;
staff->insertIntoCapoList(s->tick(),st->capo());
}
}
}
//---------------------------------------------------------
// updateChannel
//---------------------------------------------------------
void MasterScore::updateChannel()
{
for (Staff* s : staves()) {
for (int i = 0; i < VOICES; ++i)
s->clearChannelList(i);
}
Measure* fm = firstMeasure();
if (!fm)
return;
for (Segment* s = fm->first(SegmentType::ChordRest); s; s = s->next1(SegmentType::ChordRest)) {
for (const Element* e : s->annotations()) {
if (e->isInstrumentChange()) {
Staff* staff = Score::staff(e->staffIdx());
for (int voice = 0; voice < VOICES; ++voice)
staff->insertIntoChannelList(voice, s->tick(), 0);
continue;
}
if (!e->isStaffTextBase())
continue;
const StaffTextBase* st = toStaffTextBase(e);
for (int voice = 0; voice < VOICES; ++voice) {
QString an(st->channelName(voice));
if (an.isEmpty())
continue;
Staff* staff = Score::staff(st->staffIdx());
int a = staff->part()->instrument(s->tick())->channelIdx(an);
if (a != -1)
staff->insertIntoChannelList(voice, s->tick(), a);
}
}
}
for (auto it = spanner().cbegin(); it != spanner().cend(); ++it) {
Spanner* spanner = (*it).second;
if (!spanner->isVolta())
continue;
Volta* volta = toVolta(spanner);
volta->setChannel();
}
for (Segment* s = fm->first(SegmentType::ChordRest); s; s = s->next1(SegmentType::ChordRest)) {
for (Staff* st : staves()) {
int strack = st->idx() * VOICES;
int etrack = strack + VOICES;
for (int track = strack; track < etrack; ++track) {
if (!s->element(track))
continue;
Element* e = s->element(track);
if (e->type() != ElementType::CHORD)
continue;
Chord* c = toChord(e);
int channel = st->channel(c->tick(), c->voice());
Instrument* instr = c->part()->instrument(c->tick());
if (channel >= instr->channel().size()) {
qDebug() << "Channel " << channel << " too high. Max " << instr->channel().size();
channel = 0;
}
for (Note* note : c->notes()) {
if (note->hidden())
continue;
if (note->tieBack())
continue;
note->setSubchannel(channel);
}
}
}
}
}
//---------------------------------------------------------
// playNote
//---------------------------------------------------------
static void playNote(EventMap* events, const Note* note, int channel, int pitch,
int velo, int onTime, int offTime, int staffIdx)
{
if (!note->play())
return;
velo = note->customizeVelocity(velo);
NPlayEvent ev(ME_NOTEON, channel, pitch, velo);
ev.setOriginatingStaff(staffIdx);
ev.setTuning(note->tuning());
ev.setNote(note);
if (offTime < onTime)
offTime = onTime;
events->insert(std::pair<int, NPlayEvent>(onTime, ev));
ev.setVelo(0);
events->insert(std::pair<int, NPlayEvent>(offTime, ev));
}
//---------------------------------------------------------
// collectNote
//---------------------------------------------------------
static void collectNote(EventMap* events, int channel, const Note* note, int velo, int tickOffset, int staffIdx)
{
if (!note->play() || note->hidden()) // do not play overlapping notes
return;
Chord* chord = note->chord();
int ticks;
int tieLen = 0;
if (chord->isGrace()) {
Q_ASSERT( !graceNotesMerged(chord)); // this function should not be called on a grace note if grace notes are merged
chord = toChord(chord->parent());
ticks = chord->actualTicks().ticks(); // ticks of the parent note
tieLen = 0;
}
else {
ticks = chord->actualTicks().ticks(); // ticks of the actual note
// calculate additional length due to ties forward
// taking NoteEvent length adjustments into account
// but stopping at any note with multiple NoteEvents
// and processing those notes recursively
if (note->tieFor()) {
Note* n = note->tieFor()->endNote();
while (n) {
NoteEventList nel = n->playEvents();
if (nel.size() == 1) {
// add value of this note to main note
// if we wish to suppress first note of ornament,
// then do this regardless of number of NoteEvents
tieLen += (n->chord()->actualTicks().ticks() * (nel[0].len())) / 1000;
}
else {
// recurse
collectNote(events, channel, n, velo, tickOffset, staffIdx);
break;
}
if (n->tieFor() && n != n->tieFor()->endNote())
n = n->tieFor()->endNote();
else
break;
}
}
}
int tick1 = chord->tick().ticks() + tickOffset;
bool tieFor = note->tieFor();
bool tieBack = note->tieBack();
NoteEventList nel = note->playEvents();
int nels = nel.size();
for (int i = 0, pitch = note->ppitch(); i < nels; ++i) {
const NoteEvent& e = nel[i]; // we make an explicit const ref, not a const copy. no need to copy as we won't change the original object.
// skip if note has a tie into it and only one NoteEvent
// its length was already added to previous note
// if we wish to suppress first note of ornament
// then change "nels == 1" to "i == 0", and change "break" to "continue"
if (tieBack && nels == 1)
break;
int p = pitch + e.pitch();
if (p < 0)
p = 0;
else if (p > 127)
p = 127;
int on = tick1 + (ticks * e.ontime())/1000;
int off = on + (ticks * e.len())/1000 - 1;
if (tieFor && i == nels - 1)
off += tieLen;
playNote(events, note, channel, p, velo, on, off, staffIdx);
}
// Bends
for (Element* e : note->el()) {
if (e == 0 || e->type() != ElementType::BEND)
continue;
Bend* bend = toBend(e);
if (!bend->playBend())
break;
const QList<PitchValue>& points = bend->points();
int pitchSize = points.size();
double noteLen = note->playTicks();
int lastPointTick = tick1;
for (int pitchIndex = 0; pitchIndex < pitchSize-1; pitchIndex++) {
PitchValue pitchValue = points[pitchIndex];
PitchValue nextPitch = points[pitchIndex+1];
int nextPointTick = tick1 + nextPitch.time / 60.0 * noteLen;
int pitch = pitchValue.pitch;
if (pitchIndex == 0 && (pitch == nextPitch.pitch)) {
int midiPitch = (pitch * 16384) / 1200 + 8192;
int msb = midiPitch / 128;
int lsb = midiPitch % 128;
NPlayEvent ev(ME_PITCHBEND, channel, lsb, msb);
ev.setOriginatingStaff(staffIdx);
events->insert(std::pair<int, NPlayEvent>(lastPointTick, ev));
lastPointTick = nextPointTick;
continue;
}
if (pitch == nextPitch.pitch && !(pitchIndex == 0 && pitch != 0)) {
lastPointTick = nextPointTick;
continue;
}
double pitchDelta = nextPitch.pitch - pitch;
double tickDelta = nextPitch.time - pitchValue.time;
/* B
/. pitch is 1/100 semitones
bend / . pitchDelta time is in noteDuration/60
/ . midi pitch is 12/16384 semitones
A....
tickDelta */
for (int i = lastPointTick; i <= nextPointTick; i += 16) {
double dx = ((i-lastPointTick) * 60) / noteLen;
int p = pitch + dx * pitchDelta / tickDelta;
// We don't support negative pitch, but Midi does. Let's center by adding 8192.
int midiPitch = (p * 16384) / 1200 + 8192;
// Representing pitch as two bytes
int msb = midiPitch / 128;
int lsb = midiPitch % 128;
NPlayEvent ev(ME_PITCHBEND, channel, lsb, msb);
ev.setOriginatingStaff(staffIdx);
events->insert(std::pair<int, NPlayEvent>(i, ev));
}
lastPointTick = nextPointTick;
}
NPlayEvent ev(ME_PITCHBEND, channel, 0, 64); // 0:64 is 8192 - no pitch bend
ev.setOriginatingStaff(staffIdx);
events->insert(std::pair<int, NPlayEvent>(tick1+int(noteLen), ev));
}
}
//---------------------------------------------------------
// aeolusSetStop
//---------------------------------------------------------
static void aeolusSetStop(int tick, int channel, int i, int k, bool val, EventMap* events)
{
NPlayEvent event;
event.setType(ME_CONTROLLER);
event.setController(98);
if (val)
event.setValue(0x40 + 0x20 + i);
else
event.setValue(0x40 + 0x10 + i);
event.setChannel(channel);
events->insert(std::pair<int,NPlayEvent>(tick, event));
event.setValue(k);
events->insert(std::pair<int,NPlayEvent>(tick, event));
// event.setValue(0x40 + i);
// events->insert(std::pair<int,NPlayEvent>(tick, event));
}
//---------------------------------------------------------
// collectProgramChanges
//---------------------------------------------------------
static void collectProgramChanges(EventMap* events, Measure* m, Staff* staff, int tickOffset)
{
int firstStaffIdx = staff->idx();
int nextStaffIdx = firstStaffIdx + 1;
//
// collect program changes and controller
//
for (Segment* s = m->first(SegmentType::ChordRest); s; s = s->next(SegmentType::ChordRest)) {
for (Element* e : s->annotations()) {
if (!e->isStaffTextBase() || e->staffIdx() < firstStaffIdx || e->staffIdx() >= nextStaffIdx)
continue;
const StaffTextBase* st1 = toStaffTextBase(e);
Fraction tick = s->tick() + Fraction::fromTicks(tickOffset);
Instrument* instr = e->part()->instrument(tick);
for (const ChannelActions& ca : *st1->channelActions()) {
int channel = instr->channel().at(ca.channel)->channel();
for (const QString& ma : ca.midiActionNames) {
NamedEventList* nel = instr->midiAction(ma, ca.channel);
if (!nel)
continue;
for (MidiCoreEvent event : nel->events) {
event.setChannel(channel);
NPlayEvent e1(event);
e1.setOriginatingStaff(firstStaffIdx);
if (e1.dataA() == CTRL_PROGRAM)
events->insert(std::pair<int, NPlayEvent>(tick.ticks()-1, e1));
else
events->insert(std::pair<int, NPlayEvent>(tick.ticks(), e1));
}
}
}
if (st1->setAeolusStops()) {
Staff* s1 = st1->staff();
int voice = 0;
int channel = s1->channel(tick, voice);
for (int i = 0; i < 4; ++i) {
static int num[4] = { 12, 13, 16, 16 };
for (int k = 0; k < num[i]; ++k)
aeolusSetStop(tick.ticks(), channel, i, k, st1->getAeolusStop(i, k), events);
}
}
}
}
}
//---------------------------------------------------------
// getControllerFromCC
//---------------------------------------------------------
static int getControllerFromCC(int cc)
{
int controller = -1;
switch (cc) {
case 1:
controller = CTRL_MODULATION;
break;
case 2:
controller = CTRL_BREATH;
break;
case 4:
controller = CTRL_FOOT;
break;
case 11:
controller = CTRL_EXPRESSION;
break;
default:
break;
}
return controller;
}
//---------------------------------------------------------
// collectMeasureEventsSimple
// the original, velocity-only method of collecting events.
//---------------------------------------------------------
static void collectMeasureEventsSimple(EventMap* events, Measure* m, Staff* staff, int tickOffset)
{
int firstStaffIdx = staff->idx();
int nextStaffIdx = firstStaffIdx + 1;
SegmentType st = SegmentType::ChordRest;
int strack = firstStaffIdx * VOICES;
int etrack = nextStaffIdx * VOICES;
for (Segment* seg = m->first(st); seg; seg = seg->next(st)) {
int tick = seg->tick().ticks();
for (int track = strack; track < etrack; ++track) {
// skip linked staves, except primary
if (!m->score()->staff(track / VOICES)->primaryStaff()) {
track += VOICES-1;
continue;
}
Element* cr = seg->element(track);
if (cr == 0 || cr->type() != ElementType::CHORD)
continue;
Chord* chord = toChord(cr);
Staff* st1 = chord->staff();
int staffIdx = st1->idx();
int velocity = st1->velocities().velo(seg->tick().ticks());
Instrument* instr = chord->part()->instrument(Fraction::fromTicks(tick));
int channel = instr->channel(chord->upNote()->subchannel())->channel();
events->registerChannel(channel);
for (Articulation* a : chord->articulations())
instr->updateVelocity(&velocity,channel, a->articulationName());
if ( !graceNotesMerged(chord))
for (Chord* c : chord->graceNotesBefore())
for (const Note* note : c->notes())
collectNote(events, channel, note, velocity, tickOffset, staffIdx);
for (const Note* note : chord->notes())
collectNote(events, channel, note, velocity, tickOffset, staffIdx);
if ( !graceNotesMerged(chord))
for (Chord* c : chord->graceNotesAfter())
for (const Note* note : c->notes())
collectNote(events, channel, note, velocity, tickOffset, staffIdx);
}
}
}
//---------------------------------------------------------
// changeCCBetween
// since we're adding events, pass ticks as ints rather than fractions
//---------------------------------------------------------
static void changeCCBetween(std::map<int, NPlayEvent>& tempEvents, int stick, int etick, int startExpr, int endExpr, int channel, int controller, VeloChangeMethod changeMethod, int tickOffset, int originatingStaff)
{
// Prevent zero-division error, but add single event
if (startExpr == endExpr || stick == etick) {
int tickToUse = stick + tickOffset;
if (tempEvents.find(tickToUse) != tempEvents.end()) {
// Don't add a play event if it would be quieter than the current one at
// this tick
if (tempEvents[tickToUse].velo() >= abs(startExpr))
return;
}
tempEvents[tickToUse] = NPlayEvent(ME_CONTROLLER, channel, controller, abs(startExpr));
return;
}
// Ticks to change expression over
int exprTicks = etick - stick;
int exprDiff = endExpr - startExpr;
// The lambdas are in the format:
// func(precalculated values, current tick)
// The precalculated values are for values that stay constant, involving
// total ticks or total expression. Although it seems messy,
// it saves some 13% processing time.
// NOTE:JT - hardcoded, todo change?
int tickInc = 1;
// See these functions graphically at: https://www.desmos.com/calculator/kk89ficmjk
std::function<int(std::vector<double>&, int)> valueFunction;
std::vector<double> preCalculated;
switch (changeMethod) {
case VeloChangeMethod::EXPONENTIAL:
// Due to the nth-root, exponential functions do not flip with negative values, and cause errors,
// so treat it as a piecewise function.
if (exprDiff > 0) {
preCalculated.push_back(
pow((exprDiff + 1), 1.0 / double(exprTicks)) // the exprTicks root of d+1
);
valueFunction = [](std::vector<double>& pc, int ct) { return int(
pow(
pc[0],
double(ct) // to the power of the current tick (exponential)
) - 1
); };
}
else {
preCalculated.push_back(
pow((-exprDiff + 1), 1.0 / double(exprTicks)) // the exprTicks root of 1-d
);
valueFunction = [](std::vector<double>& pc, int ct) { return -int(
pow(
pc[0],
double(ct) // again to the power of ct
) + 1
); };
}
break;
// Uses sin x transformed, which _does_ flip with negative numbers
case VeloChangeMethod::EASE_IN_OUT:
preCalculated.push_back(double(exprDiff) / 2.0);
preCalculated.push_back(double(M_PI / double(exprTicks)));
preCalculated.push_back(double(M_PI / 2.0));
valueFunction = [](std::vector<double>& pc, int ct) { return int(
pc[0] * (
sin(
double(ct) * (
pc[1]
) - pc[2]
) + 1
)
); };
break;
case VeloChangeMethod::EASE_IN:
preCalculated.push_back(double(exprDiff));
preCalculated.push_back(double(exprTicks));
preCalculated.push_back(double(M_PI / double(2 * exprTicks)));
valueFunction = [](std::vector<double>& pc, int ct) { return int(
pc[0] * (
sin(
double(ct - pc[1]) * (
pc[2]
)
) + 1
)
); };
break;
case VeloChangeMethod::EASE_OUT:
preCalculated.push_back(double(exprDiff));
preCalculated.push_back(double(M_PI / double(2 * exprTicks)));
valueFunction = [](std::vector<double>& pc, int ct) { return int(
pc[0] * sin(
double(ct) * (
pc[1]
)
)
); };
break;
case VeloChangeMethod::NORMAL:
default:
// We can calculate how to increase the ticks, since it is linear
tickInc = exprTicks / abs(exprDiff);
preCalculated.push_back(double(exprDiff));
preCalculated.push_back(double(exprTicks));
valueFunction = [](std::vector<double>& pc, int ct) { return int(pc[0] * (double(ct) / pc[1])); };
break;
}
// prevent possible infinite loop
if (tickInc < 1)
tickInc = 1;
int lastVal = -1;
for (int i = stick; i < etick; i += tickInc) {
int valueToAdd = valueFunction(preCalculated, i - stick);
if (lastVal == valueToAdd)
continue;
int exprVal = startExpr + valueToAdd;
if (tempEvents.find(i + tickOffset) != tempEvents.end()) {
// Don't add a play event if it would be quieter than the current one at this tick
if (tempEvents[i + tickOffset].velo() >= abs(exprVal))
continue;
}
lastVal = valueToAdd;
NPlayEvent event = NPlayEvent(ME_CONTROLLER, channel, controller, abs(exprVal));
event.setOriginatingStaff(originatingStaff);
tempEvents[i + tickOffset] = event;
}
}
//---------------------------------------------------------
// collectMeasureEventsDefault
// this uses only CC events to control note velocity, and sets the
// note-on velocity to always be 127 (max). This is the method that allows
// single note dynamics, but only works if the soundfont supports it.
// Method is one of:
// FIXED_MAX - default: velocity is fixed at 127
// SEG_START - note-on velocity is the same as the start velocity of the seg
//---------------------------------------------------------
static void collectMeasureEventsDefault(EventMap* events, Measure* m, Staff* staff, StaffRenderData& renderData, int tickOffset, DynamicsRenderMethod method, int cc)
{
int controller = getControllerFromCC(cc);
if (controller == -1) {
qWarning("controller for CC %d not valid", cc);
return;
}
int firstStaffIdx = staff->idx();
int nextStaffIdx = firstStaffIdx + 1;
SegmentType st = SegmentType::ChordRest;
int strack = firstStaffIdx * VOICES;
int etrack = nextStaffIdx * VOICES;
static const VeloChangeMethod defaultChangeMethod = VeloChangeMethod::NORMAL;
int lastSubchannel = -1;
for (Segment* seg = m->first(st); seg; seg = seg->next(st)) {
Fraction tick = seg->tick();
Fraction tick2 = tick + seg->ticks();
for (int track = strack; track < etrack; ++track) {
// Skip linked staves, except primary
Staff* st1 = m->score()->staff(track / VOICES);
if (!st1->primaryStaff()) {
track += VOICES - 1;
continue;
}
Chord* chord = nullptr;
Element* cr = seg->element(track);
if (cr != 0) {
if (cr->isChord())
chord = toChord(cr);
}
// We need to be able to add CC events even if there isn't a note,
// since in multi-stave scores, some segments will have no notes in
// them for a stave, despite a note being held. So, if there isn't
// a chord, at least try to add CC events.
if (!chord && !seg->isChordRestType())
continue;
int staffIdx = st1->idx();
int velocity = st1->velocities().velo(tick.ticks());
Instrument* instr = st1->part()->instrument(tick);
int channel;
if (chord != 0)
lastSubchannel = chord->upNote()->subchannel();
// This is a slightly hacky way of always getting a channel, no matter
// if there are notes or not.
if (lastSubchannel != -1)
channel = instr->channel(lastSubchannel)->channel();
else
continue;
events->registerChannel(channel);
//
// Decide whether to add CC events or not
//
if (instr->singleNoteDynamics()) {
Fraction hairpinStartTick;
Fraction hairpinStopTick;
bool hasHairpin = false;
bool singleNoteDynamics = false;
Hairpin* h = nullptr;
VeloChangeMethod changeMethod = VeloChangeMethod::NORMAL;
// This flag is used to decide whether to add a static velocity event or none at all,
// depending on whether we're in a hairpin/changing dynamic or not.
bool doAddStaticVel = true;
// Check for hairpin crossing segment
for (auto it : staff->score()->spannerMap().findOverlapping(tick.ticks(), tick2.ticks()-1)) {
Spanner* s = it.value;
if (it.stop == tick.ticks())
continue;
// Don't playback dynamic if this hairpin started before or at the same time as the last one
// processed (i.e. if it is the same hairpin)
if (it.start + tickOffset <= renderData.lastHairpinStart.ticks()) {
doAddStaticVel = false;
continue;
}
if (s->isHairpin()) {
h = toHairpin(s);
switch (h->dynRange()) {
case Dynamic::Range::STAFF:
if (h->staff() != st1)
continue;
break;
case Dynamic::Range::PART:
if (h->part() != st1->part())
continue;
break;
case Dynamic::Range::SYSTEM:
default:
break;
}
singleNoteDynamics = h->singleNoteDynamics() || singleNoteDynamics;
if (singleNoteDynamics) {
hairpinStartTick = Fraction::fromTicks(it.start);
hairpinStopTick = Fraction::fromTicks(it.stop);
hasHairpin = true;
changeMethod = h->veloChangeMethod();
break;
}
}
}
// From this, work out a start and end tick to apply CC events for
Fraction stick;
Fraction etick;
Fraction fracTickOffset = Fraction::fromTicks(tickOffset);
if (hasHairpin) {
stick = hairpinStartTick;
etick = hairpinStopTick;
// Correct for a changing dynamic that may still be finishing
if (renderData.lastDynamicEnd >= etick + fracTickOffset) {
singleNoteDynamics = false;
}
else if (renderData.lastDynamicEnd > stick + fracTickOffset) {
stick = renderData.lastDynamicEnd;
}
}
else {
stick = Fraction(0, 1);
etick = seg->tick() + seg->ticks();
}
if (stick < seg->tick())
stick = seg->tick();
// Make sure we don't add a static dynamic event in the middle of a changing dynamic
if (renderData.lastDynamicEnd >= stick + fracTickOffset)
doAddStaticVel = false;
// Check if there is a fortepiano / similar dynamic
bool hasChangingDynamic = false;
Dynamic* changingDyn = nullptr;
if (chord != 0) {
for (Element* e : seg->annotations()) {
if (!e)
continue;
if (!e->isDynamic())
continue;
Dynamic* d = toDynamic(e);
if (d->changeInVelocity() == 0)
continue;
switch (d->dynRange()) {
case Dynamic::Range::STAFF:
if (d->staff()->idx() != staffIdx)
continue;
break;
case Dynamic::Range::PART:
if (d->part() != chord->part())
continue;
break;
case Dynamic::Range::SYSTEM:
default:
break;
}
hasChangingDynamic = true;
changingDyn = d;
}
}
// We have a start and end tick, so get the velocities at these points
int velocityStart = staff->velocities().velo(stick.ticks());
int velocityMiddle = hasChangingDynamic ? velocityStart + changingDyn->changeInVelocity() : -1;
int velocityEnd = staff->velocities().velo(etick.ticks() - 1);
// Attempt to fix invalid hairpin
if (hasHairpin) {
int hairpinStartVel = (velocityMiddle == -1) ? velocityStart : velocityMiddle;
if (h->isCrescendo() && hairpinStartVel > velocityEnd)
singleNoteDynamics = false;
else if (h->isDecrescendo() && hairpinStartVel < velocityEnd)
singleNoteDynamics = false;
}
// Check for articulations
bool hasArticulations = false;
if (chord)
hasArticulations = chord->articulations().count() > 0;
//
// Add CC events
//
if (singleNoteDynamics || hasArticulations || hasChangingDynamic) {
if (chord != 0 && hasArticulations) {
for (Articulation* a : chord->articulations()) {
if (velocityMiddle == -1)
velocityMiddle = velocityStart;
instr->updateVelocity(&velocityStart, channel, a->articulationName());
}
}
if (hasHairpin && singleNoteDynamics)
renderData.lastHairpinStart = hairpinStartTick + Fraction::fromTicks(tickOffset);
if (hasArticulations || hasChangingDynamic) {
int startExpr = velocityStart;
int endExpr = velocityMiddle;
Fraction accentTicks = Fraction(1, 16);
if (hasChangingDynamic) {
accentTicks = changingDyn->velocityChangeLength();
renderData.lastDynamicEnd = stick + accentTicks + fracTickOffset;
}
// Determine how long to 'hold' the initial velocity
// This is shorter with a dynamic than an articulation
// Also, since we're about to add CC events, we can use int ticks instead of fractions
int stickToUse = stick.ticks() + accentTicks.ticks() / (hasChangingDynamic ? 4 : 2);
int etickToUse = stick.ticks() + accentTicks.ticks();
// First, add an initial accent velocity
// stick is the seg start tick, stickToUse is where we should dim to the rest velocity
changeCCBetween(renderData.tempPlayEvents, stick.ticks(), stickToUse, startExpr, startExpr, channel, controller, defaultChangeMethod, tickOffset, staffIdx);
// Then dimenuendo back down to normal
// eticktouse is the end of the dim back to normal for an accent,
// but etick is the segment end tick.
changeCCBetween(renderData.tempPlayEvents, stickToUse, etickToUse, startExpr, endExpr, channel, controller, defaultChangeMethod, tickOffset, staffIdx);
// if there's a cresc or dim after the dynamic, apply it
if (singleNoteDynamics && hasHairpin) {
startExpr = velocityMiddle;
endExpr = velocityEnd;
stickToUse = qMin(stick.ticks() + accentTicks.ticks() + 1, etick.ticks());
changeCCBetween(renderData.tempPlayEvents, stickToUse, etick.ticks(), startExpr, endExpr, channel, controller, changeMethod, tickOffset, staffIdx);
}
}
else {
int startExpr = velocityStart;
int endExpr = velocityEnd;
changeCCBetween(renderData.tempPlayEvents, stick.ticks(), etick.ticks(), startExpr, endExpr, channel, controller, changeMethod, tickOffset, staffIdx);
}
}
else if (doAddStaticVel) {
// Add a single expression value to match the velocity, since there is no hairpin
int exprVal = velocityStart;
int staticTick = seg->tick().ticks();
changeCCBetween(renderData.tempPlayEvents, staticTick, staticTick, exprVal, exprVal, channel, controller, defaultChangeMethod, tickOffset, staffIdx);
}
} // if instr->singleNoteDynamics()
else {
if (chord != 0) {
for (Articulation* a : chord->articulations())
instr->updateVelocity(&velocity, channel, a->articulationName());
}
// Add a single expression value to match the velocity, since this instrument should
// not use single note dynamics.
int staticTick = seg->tick().ticks();
changeCCBetween(renderData.tempPlayEvents, staticTick, staticTick, velocity, velocity, channel, controller, defaultChangeMethod, tickOffset, staffIdx);
}
//
// Add normal note events
//
if (chord != 0) {
int velocityToUse = 0;
switch (method) {
case DynamicsRenderMethod::FIXED_MAX:
velocityToUse = 127;
break;
case DynamicsRenderMethod::SEG_START:
default:
velocityToUse = velocity;
break;
}
if (!graceNotesMerged(chord))
for (Chord* c : chord->graceNotesBefore())
for (const Note* note : c->notes())
collectNote(events, channel, note, velocityToUse, tickOffset, staffIdx);
for (const Note* note : chord->notes())
collectNote(events, channel, note, velocityToUse, tickOffset, staffIdx);
if (!graceNotesMerged(chord))
for (Chord* c : chord->graceNotesAfter())
for (const Note* note : c->notes())
collectNote(events, channel, note, velocityToUse, tickOffset, staffIdx);
}
}
}
}
//---------------------------------------------------------
// collectMeasureEvents
// redirects to the correct function based on the passed method
//---------------------------------------------------------
static void collectMeasureEvents(EventMap* events, Measure* m, Staff* staff, StaffRenderData& renderData, int tickOffset, DynamicsRenderMethod method, int cc)
{
switch (method) {
case DynamicsRenderMethod::SIMPLE:
collectMeasureEventsSimple(events, m, staff, tickOffset);
break;
case DynamicsRenderMethod::SEG_START:
case DynamicsRenderMethod::FIXED_MAX:
collectMeasureEventsDefault(events, m, staff, renderData, tickOffset, method, cc);