Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore-Studio-CLA-applies
4 : *
5 : * MuseScore Studio
6 : * Music Composition & Notation
7 : *
8 : * Copyright (C) 2021 MuseScore Limited and others
9 : *
10 : * This program is free software: you can redistribute it and/or modify
11 : * it under the terms of the GNU General Public License version 3 as
12 : * published by the Free Software Foundation.
13 : *
14 : * This program is distributed in the hope that it will be useful,
15 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : * GNU General Public License for more details.
18 : *
19 : * You should have received a copy of the GNU General Public License
20 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 : */
22 : #include "notationplayback.h"
23 :
24 : #include <cmath>
25 :
26 : #include "engraving/dom/chordrest.h"
27 : #include "engraving/dom/factory.h"
28 : #include "engraving/dom/instrument.h"
29 : #include "engraving/dom/linkedobjects.h"
30 : #include "engraving/dom/masterscore.h"
31 : #include "engraving/dom/measure.h"
32 : #include "engraving/dom/page.h"
33 : #include "engraving/dom/part.h"
34 : #include "engraving/dom/repeatlist.h"
35 : #include "engraving/dom/segment.h"
36 : #include "engraving/dom/soundflag.h"
37 : #include "engraving/dom/staff.h"
38 : #include "engraving/dom/stafftext.h"
39 : #include "engraving/dom/tempotimeline.h"
40 : #include "engraving/dom/utils.h"
41 :
42 : #include "notationerrors.h"
43 :
44 : #include "log.h"
45 : #include "translation.h"
46 :
47 : using namespace mu;
48 : using namespace mu::notation;
49 : using namespace mu::engraving;
50 : using namespace muse;
51 : using namespace muse::midi;
52 : using namespace muse::async;
53 :
54 : static constexpr double PLAYBACK_TAIL_SECS = 3;
55 :
56 0 : NotationPlayback::NotationPlayback(IGetScore* getScore,
57 : muse::async::Channel<muse::RectF> notationChanged,
58 0 : const modularity::ContextPtr& iocCtx)
59 0 : : muse::Contextable(iocCtx), m_getScore(getScore), m_notationChanged(notationChanged), m_playbackModel(iocCtx)
60 : {
61 0 : m_notationChanged.onReceive(this, [this](const muse::RectF&) {
62 0 : updateLoopBoundaries();
63 0 : });
64 0 : }
65 :
66 0 : mu::engraving::Score* NotationPlayback::score() const
67 : {
68 0 : return m_getScore->score();
69 : }
70 :
71 0 : void NotationPlayback::init()
72 : {
73 0 : IF_ASSERT_FAILED(score()) {
74 0 : return;
75 : }
76 :
77 0 : m_playbackModel.setPlayRepeats(configuration()->isPlayRepeatsEnabled());
78 0 : m_playbackModel.setPlayChordSymbols(configuration()->isPlayChordSymbolsEnabled());
79 0 : m_playbackModel.setUseScoreDynamicsForOffstreamPlayback(configuration()->playPreviewNotesWithScoreDynamics());
80 0 : m_playbackModel.setIsMetronomeEnabled(configuration()->isMetronomeEnabled());
81 :
82 0 : m_playbackModel.load(score());
83 :
84 0 : updateTotalPlayTime();
85 0 : m_playbackModel.tracksDataChanged().onReceive(this, [this](const InstrumentTrackIdSet&) {
86 0 : updateTotalPlayTime();
87 0 : });
88 :
89 0 : configuration()->isPlayRepeatsChanged().onNotify(this, [this]() {
90 0 : bool expandRepeats = configuration()->isPlayRepeatsEnabled();
91 0 : if (expandRepeats != m_playbackModel.isPlayRepeatsEnabled()) {
92 0 : m_playbackModel.setPlayRepeats(expandRepeats);
93 0 : m_playbackModel.reload();
94 : }
95 0 : });
96 :
97 0 : configuration()->isPlayChordSymbolsChanged().onNotify(this, [this]() {
98 0 : bool playChordSymbols = configuration()->isPlayChordSymbolsEnabled();
99 0 : if (playChordSymbols != m_playbackModel.isPlayChordSymbolsEnabled()) {
100 0 : m_playbackModel.setPlayChordSymbols(playChordSymbols);
101 0 : m_playbackModel.reload();
102 : }
103 0 : });
104 :
105 0 : configuration()->playPreviewNotesWithScoreDynamicsChanged().onNotify(this, [this]() {
106 0 : bool useScoreDynamics = configuration()->playPreviewNotesWithScoreDynamics();
107 0 : if (useScoreDynamics != m_playbackModel.useScoreDynamicsForOffstreamPlayback()) {
108 0 : m_playbackModel.setUseScoreDynamicsForOffstreamPlayback(useScoreDynamics);
109 : }
110 0 : });
111 :
112 0 : configuration()->isMetronomeEnabledChanged().onNotify(this, [this]() {
113 0 : bool metronomeEnabled = configuration()->isMetronomeEnabled();
114 0 : if (metronomeEnabled != m_playbackModel.isMetronomeEnabled()) {
115 0 : m_playbackModel.setIsMetronomeEnabled(metronomeEnabled);
116 : }
117 0 : });
118 :
119 0 : score()->loopBoundaryTickChanged().onReceive(this, [this](LoopBoundaryType, unsigned) {
120 0 : updateLoopBoundaries();
121 0 : });
122 : }
123 :
124 0 : void NotationPlayback::reload()
125 : {
126 0 : m_playbackModel.reload();
127 0 : }
128 :
129 0 : void NotationPlayback::setSendEventsOnScoreChange(const InstrumentTrackId& trackId, bool send)
130 : {
131 0 : m_playbackModel.setSendEventsOnScoreChange(trackId, send);
132 0 : }
133 :
134 0 : void NotationPlayback::sendEventsForChangedTracks()
135 : {
136 0 : m_playbackModel.sendEventsForChangedTracks();
137 0 : }
138 :
139 0 : muse::async::Channel<InstrumentTrackIdSet> NotationPlayback::tracksDataChanged() const
140 : {
141 0 : return m_playbackModel.tracksDataChanged();
142 : }
143 :
144 0 : const engraving::InstrumentTrackId& NotationPlayback::metronomeTrackId() const
145 : {
146 0 : return m_playbackModel.metronomeTrackId();
147 : }
148 :
149 0 : engraving::InstrumentTrackId NotationPlayback::chordSymbolsTrackId(const ID& partId) const
150 : {
151 0 : return m_playbackModel.chordSymbolsTrackId(partId);
152 : }
153 :
154 0 : bool NotationPlayback::isChordSymbolsTrack(const engraving::InstrumentTrackId& trackId) const
155 : {
156 0 : return m_playbackModel.isChordSymbolsTrack(trackId);
157 : }
158 :
159 0 : std::optional<std::string> NotationPlayback::trackName(const engraving::InstrumentTrackId& trackId) const
160 : {
161 0 : if (trackId == metronomeTrackId()) {
162 0 : return muse::trc("playback", "Metronome");
163 : }
164 :
165 0 : const Part* part = score() ? score()->partById(trackId.partId) : nullptr;
166 0 : if (!part) {
167 0 : return std::nullopt;
168 : }
169 :
170 0 : if (isChordSymbolsTrack(trackId)) {
171 0 : return muse::trc("playback", "Chords") + "." + part->partName().toStdString();
172 : }
173 :
174 0 : if (trackId.instrumentId == part->instrument()->id()) {
175 0 : return part->partName().toStdString();
176 : }
177 :
178 0 : if (const Instrument* instrument = part->instrumentById(trackId.instrumentId)) {
179 0 : return "(" + instrument->trackName().toStdString() + ")";
180 : }
181 :
182 0 : return std::nullopt;
183 : }
184 :
185 0 : const muse::mpe::PlaybackData& NotationPlayback::trackPlaybackData(const engraving::InstrumentTrackId& trackId) const
186 : {
187 0 : return m_playbackModel.resolveTrackPlaybackData(trackId);
188 : }
189 :
190 0 : void NotationPlayback::triggerEventsForItems(const std::vector<const EngravingItem*>& items, muse::mpe::duration_t duration,
191 : bool flushSound)
192 : {
193 0 : m_playbackModel.triggerEventsForItems(items, duration, flushSound);
194 0 : }
195 :
196 0 : void NotationPlayback::triggerMetronome(muse::midi::tick_t tick)
197 : {
198 0 : m_playbackModel.triggerMetronome(tick);
199 0 : }
200 :
201 0 : void NotationPlayback::triggerCountIn(muse::midi::tick_t tick, muse::secs_t& countInDuration)
202 : {
203 0 : muse::mpe::duration_t durationInMicrosecs = 0;
204 0 : m_playbackModel.triggerCountIn(tick, durationInMicrosecs);
205 0 : countInDuration = muse::usecs_to_secs(durationInMicrosecs);
206 0 : }
207 :
208 0 : void NotationPlayback::triggerControllers(const muse::mpe::ControllerChangeEventList& list, staff_idx_t staffIdx, int tick)
209 : {
210 0 : if (list.empty()) {
211 0 : return;
212 : }
213 :
214 0 : const Staff* staff = score()->staff(staffIdx);
215 0 : if (!staff) {
216 0 : return;
217 : }
218 :
219 0 : const Part* part = staff->part();
220 : const InstrumentTrackId trackId {
221 : part->id(),
222 0 : part->instrumentId(Fraction::fromTicks(tick))
223 0 : };
224 :
225 : const mpe::PlaybackEventsMap events {
226 0 : { 0, mpe::PlaybackEventList(list.begin(), list.end()) }
227 0 : };
228 :
229 0 : mpe::PlaybackData& data = m_playbackModel.resolveTrackPlaybackData(trackId);
230 0 : data.offStream.send(events, false /*flushOffstream*/);
231 0 : }
232 :
233 0 : InstrumentTrackIdSet NotationPlayback::existingTrackIdSet() const
234 : {
235 0 : return m_playbackModel.existingTrackIdSet();
236 : }
237 :
238 0 : muse::async::Channel<InstrumentTrackId> NotationPlayback::trackAdded() const
239 : {
240 0 : return m_playbackModel.trackAdded();
241 : }
242 :
243 0 : muse::async::Channel<InstrumentTrackId> NotationPlayback::trackRemoved() const
244 : {
245 0 : return m_playbackModel.trackRemoved();
246 : }
247 :
248 0 : void NotationPlayback::updateLoopBoundaries()
249 : {
250 0 : LoopBoundaries newBoundaries;
251 0 : newBoundaries.loopInTick = score()->loopInTick();
252 0 : newBoundaries.loopOutTick = score()->loopOutTick();
253 0 : newBoundaries.enabled = m_loopBoundaries.enabled;
254 :
255 0 : if (m_loopBoundaries != newBoundaries) {
256 0 : m_loopBoundaries = newBoundaries;
257 0 : m_loopBoundariesChanged.notify();
258 : }
259 0 : }
260 :
261 0 : void NotationPlayback::updateTotalPlayTime()
262 : {
263 0 : const mu::engraving::Score* score = m_getScore->score();
264 0 : if (!score) {
265 0 : return;
266 : }
267 :
268 0 : const bool expandRepeats = m_playbackModel.isPlayRepeatsEnabled();
269 0 : const int lastTick = score->repeatList(expandRepeats).ticks();
270 0 : const TempoTimeline& timeline = score->tempoTimeline(expandRepeats);
271 0 : audio::secs_t newPlayTime = timeline.utick2utime(lastTick);
272 0 : newPlayTime += PLAYBACK_TAIL_SECS;
273 :
274 0 : if (m_totalPlayTime == newPlayTime) {
275 0 : return;
276 : }
277 :
278 0 : m_totalPlayTime = newPlayTime;
279 0 : m_totalPlayTimeChanged.send(m_totalPlayTime);
280 : }
281 :
282 0 : muse::audio::secs_t NotationPlayback::totalPlayTime() const
283 : {
284 0 : return m_totalPlayTime;
285 : }
286 :
287 0 : muse::async::Channel<muse::audio::secs_t> NotationPlayback::totalPlayTimeChanged() const
288 : {
289 0 : return m_totalPlayTimeChanged;
290 : }
291 :
292 0 : muse::audio::secs_t NotationPlayback::playedTickToSec(tick_t tick) const
293 : {
294 0 : const mu::engraving::Score* sc = score();
295 0 : if (!sc) {
296 0 : return 0;
297 : }
298 :
299 0 : return sc->tempoTimeline(m_playbackModel.isPlayRepeatsEnabled()).utick2utime(tick);
300 : }
301 :
302 0 : tick_t NotationPlayback::secToPlayedTick(muse::audio::secs_t sec) const
303 : {
304 0 : const mu::engraving::Score* sc = score();
305 0 : if (!sc) {
306 0 : return 0;
307 : }
308 :
309 0 : return sc->tempoTimeline(m_playbackModel.isPlayRepeatsEnabled()).utime2utick(sec);
310 : }
311 :
312 0 : tick_t NotationPlayback::secToTick(muse::audio::secs_t sec) const
313 : {
314 0 : const mu::engraving::Score* sc = score();
315 0 : if (!sc) {
316 0 : return 0;
317 : }
318 :
319 0 : const bool expandRepeats = m_playbackModel.isPlayRepeatsEnabled();
320 0 : const tick_t utick = sc->tempoTimeline(expandRepeats).utime2utick(sec);
321 :
322 : // The flattened timeline's domain is already raw tick - only the expanded one needs converting back
323 0 : return expandRepeats ? sc->expandedRepeatList().utick2tick(utick) : utick;
324 : }
325 :
326 0 : RetVal<muse::midi::tick_t> NotationPlayback::playPositionTickByRawTick(muse::midi::tick_t tick) const
327 : {
328 0 : if (!score()) {
329 0 : return make_ret(Err::Undefined);
330 : }
331 :
332 0 : muse::midi::tick_t playbackTick = score()->repeatList(m_playbackModel.isPlayRepeatsEnabled()).tick2utick(tick);
333 :
334 0 : return RetVal<muse::midi::tick_t>::make_ok(std::move(playbackTick));
335 : }
336 :
337 0 : RetVal<muse::midi::tick_t> NotationPlayback::playPositionTickByElement(const EngravingItem* element) const
338 : {
339 0 : IF_ASSERT_FAILED(element) {
340 0 : return make_ret(Err::Undefined);
341 : }
342 :
343 0 : if (!score()) {
344 0 : return make_ret(Err::Undefined);
345 : }
346 :
347 0 : return playPositionTickByRawTick(element->tick().ticks());
348 : }
349 :
350 0 : void NotationPlayback::addLoopBoundary(LoopBoundaryType boundaryType, tick_t tick)
351 : {
352 0 : const Measure* first = score()->firstMeasure();
353 0 : const Measure* last = score()->lastMeasure();
354 0 : IF_ASSERT_FAILED(first && last) {
355 0 : return;
356 : }
357 :
358 0 : if (tick == BoundaryTick::FirstScoreTick) {
359 0 : tick = first->tick().ticks();
360 0 : } else if (tick == BoundaryTick::LastScoreTick) {
361 0 : tick = last->endTick().ticks();
362 : }
363 :
364 0 : switch (boundaryType) {
365 0 : case LoopBoundaryType::LoopIn:
366 0 : addLoopIn(tick);
367 0 : break;
368 0 : case LoopBoundaryType::LoopOut:
369 0 : addLoopOut(tick);
370 0 : break;
371 0 : case LoopBoundaryType::Unknown:
372 0 : break;
373 : }
374 : }
375 :
376 0 : void NotationPlayback::addLoopIn(int _tick)
377 : {
378 0 : Fraction tick = Fraction::fromTicks(_tick);
379 :
380 0 : if (_tick == BoundaryTick::SelectedNoteTick) {
381 0 : tick = score()->pos();
382 : }
383 :
384 0 : if (tick >= score()->loopOutTick()) { // If In pos >= Out pos, reset Out pos to end of score
385 0 : score()->setLoopOutTick(score()->lastMeasure()->endTick());
386 : }
387 :
388 0 : score()->setLoopInTick(tick);
389 0 : }
390 :
391 0 : void NotationPlayback::addLoopOut(int _tick)
392 : {
393 0 : Fraction tick = Fraction::fromTicks(_tick);
394 :
395 0 : if (_tick == BoundaryTick::SelectedNoteTick) {
396 0 : tick = score()->pos() + score()->inputState().ticks();
397 : }
398 :
399 0 : if (tick <= score()->loopInTick()) { // If Out pos <= In pos, reset In pos to beginning of score
400 0 : score()->setLoopInTick(Fraction(0, 1));
401 : } else {
402 0 : if (tick > score()->lastMeasure()->endTick()) {
403 0 : tick = score()->lastMeasure()->endTick();
404 : }
405 : }
406 :
407 0 : score()->setLoopOutTick(tick);
408 0 : }
409 :
410 0 : void NotationPlayback::setLoopBoundariesEnabled(bool enabled)
411 : {
412 0 : if (m_loopBoundaries.enabled == enabled) {
413 0 : return;
414 : }
415 :
416 0 : m_loopBoundaries.enabled = enabled;
417 0 : m_loopBoundariesChanged.notify();
418 0 : m_loopEnabledChanged.send(enabled);
419 : }
420 :
421 0 : bool NotationPlayback::isLoopEnabled() const
422 : {
423 0 : return !m_loopBoundaries.isNull() && m_loopBoundaries.enabled;
424 : }
425 :
426 0 : Channel<bool> NotationPlayback::loopEnabledChanged() const
427 : {
428 0 : return m_loopEnabledChanged;
429 : }
430 :
431 0 : const LoopBoundaries& NotationPlayback::loopBoundaries() const
432 : {
433 0 : return m_loopBoundaries;
434 : }
435 :
436 0 : Notification NotationPlayback::loopBoundariesChanged() const
437 : {
438 0 : return m_loopBoundariesChanged;
439 : }
440 :
441 0 : const Tempo& NotationPlayback::multipliedTempo(tick_t tick) const
442 : {
443 0 : if (!score()) {
444 : static Tempo empty;
445 0 : return empty;
446 : }
447 :
448 0 : m_currentTempo.valueBpm = static_cast<int>(std::round(score()->multipliedTempo(Fraction::fromTicks(tick)).toBPM().val));
449 :
450 0 : return m_currentTempo;
451 : }
452 :
453 0 : MeasureBeat NotationPlayback::beat(tick_t tick) const
454 : {
455 0 : return mu::engraving::findBeat(m_getScore->score(), tick);
456 : }
457 :
458 0 : tick_t NotationPlayback::beatToRawTick(int measureIndex, int beatIndex) const
459 : {
460 0 : return score() ? score()->sigmap()->bar2tick(measureIndex, beatIndex) : 0;
461 : }
462 :
463 0 : double NotationPlayback::tempoMultiplier() const
464 : {
465 0 : return score() ? score()->tempoTimeline().tempoMultiplier().val : 1.0;
466 : }
467 :
468 0 : void NotationPlayback::setTempoMultiplier(double multiplier)
469 : {
470 0 : Score* score = this->score();
471 0 : if (!score) {
472 0 : return;
473 : }
474 :
475 0 : if (!score->masterScore()->setTempoMultiplier(multiplier)) {
476 0 : return;
477 : }
478 :
479 0 : score->masterScore()->updateRepeatListTempo();
480 :
481 0 : m_playbackModel.reload();
482 : }
483 :
484 0 : void NotationPlayback::addSoundFlags(const std::vector<StaffText*>& staffTextList)
485 : {
486 0 : TRACEFUNC;
487 :
488 0 : if (staffTextList.empty()) {
489 0 : return;
490 : }
491 :
492 0 : bool added = false;
493 :
494 0 : for (StaffText* staffText : staffTextList) {
495 0 : added |= doAddSoundFlag(staffText);
496 : }
497 :
498 0 : if (added) {
499 0 : score()->update();
500 0 : m_notationChanged.send(muse::RectF());
501 : }
502 0 : }
503 :
504 0 : bool NotationPlayback::doAddSoundFlag(StaffText* staffText)
505 : {
506 0 : IF_ASSERT_FAILED(staffText) {
507 0 : return false;
508 : }
509 :
510 0 : if (staffText->hasSoundFlag()) {
511 0 : return false;
512 : }
513 :
514 0 : SoundFlag* soundFlag = Factory::createSoundFlag(staffText);
515 0 : staffText->add(soundFlag);
516 :
517 0 : const LinkedObjects* links = staffText->links();
518 0 : if (!links) {
519 0 : return true;
520 : }
521 :
522 0 : for (EngravingObject* obj : *links) {
523 0 : if (obj && obj->isStaffText() && obj != staffText) {
524 0 : toStaffText(obj)->add(soundFlag->linkedClone());
525 : }
526 : }
527 :
528 0 : return true;
529 : }
530 :
531 0 : void NotationPlayback::removeSoundFlags(const InstrumentTrackIdSet& trackIdSet)
532 : {
533 0 : TRACEFUNC;
534 :
535 0 : std::vector<StaffText*> staffTextList = collectStaffText(trackIdSet, true /*withSoundFlags*/);
536 0 : if (staffTextList.empty()) {
537 0 : return;
538 : }
539 :
540 0 : for (StaffText* staffText : staffTextList) {
541 0 : if (!staffText->hasSoundFlag()) {
542 0 : continue;
543 : }
544 :
545 0 : staffText->remove(staffText->soundFlag());
546 :
547 0 : const LinkedObjects* links = staffText->links();
548 0 : if (!links) {
549 0 : continue;
550 : }
551 :
552 0 : for (EngravingObject* obj : *links) {
553 0 : if (obj && obj->isStaffText() && obj != staffText) {
554 0 : StaffText* linkedStaffText = toStaffText(obj);
555 0 : if (!linkedStaffText->hasSoundFlag()) {
556 0 : continue;
557 : }
558 :
559 0 : linkedStaffText->remove(linkedStaffText->soundFlag());
560 : }
561 : }
562 : }
563 :
564 0 : score()->update();
565 :
566 0 : m_playbackModel.reload();
567 0 : m_notationChanged.send(muse::RectF());
568 0 : }
569 :
570 0 : bool NotationPlayback::hasSoundFlags(const engraving::InstrumentTrackIdSet& trackIdSet)
571 : {
572 0 : TRACEFUNC;
573 :
574 0 : for (const InstrumentTrackId& trackId : trackIdSet) {
575 0 : if (m_playbackModel.hasSoundFlags(trackId)) {
576 0 : return true;
577 : }
578 : }
579 :
580 0 : return false;
581 0 : }
582 :
583 0 : std::vector<StaffText*> NotationPlayback::collectStaffText(const InstrumentTrackIdSet& trackIdSet, bool withSoundFlags) const
584 : {
585 0 : TRACEFUNC;
586 :
587 0 : std::vector<StaffText*> result;
588 :
589 0 : if (trackIdSet.empty()) {
590 0 : return result;
591 : }
592 :
593 0 : const Score* score = this->score();
594 0 : IF_ASSERT_FAILED(score) {
595 0 : return result;
596 : }
597 :
598 0 : const Measure* fm = score->firstMeasure();
599 0 : if (!fm) {
600 0 : return result;
601 : }
602 :
603 0 : for (const Segment* seg = fm->first(SegmentType::ChordRest); seg; seg = seg->next1(SegmentType::ChordRest)) {
604 0 : for (EngravingItem* annotation : seg->annotations()) {
605 0 : if (!annotation || !annotation->isStaffText()) {
606 0 : continue;
607 : }
608 :
609 0 : StaffText* staffText = toStaffText(annotation);
610 0 : bool hasSoundFlag = staffText->hasSoundFlag();
611 :
612 0 : if (withSoundFlags && !hasSoundFlag) {
613 0 : continue;
614 : }
615 :
616 0 : if (!withSoundFlags && hasSoundFlag) {
617 0 : continue;
618 : }
619 :
620 0 : InstrumentTrackId trackId = mu::engraving::makeInstrumentTrackId(annotation);
621 0 : if (muse::contains(trackIdSet, trackId)) {
622 0 : result.push_back(staffText);
623 : }
624 0 : }
625 : }
626 :
627 0 : return result;
628 0 : }
|