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) 2025 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 :
23 : #include "playbackcontroller.h"
24 :
25 : #include "async/notifylist.h"
26 : #include "containers.h"
27 : #include "modularity/ioc.h"
28 : #include "log.h"
29 : #include "types/ret.h"
30 :
31 : #include "audio/common/audioutils.h"
32 : #include "audio/devtools/inputlag.h"
33 :
34 : #include "engraving/dom/factory.h"
35 : #include "engraving/dom/masterscore.h"
36 : #include "engraving/dom/stafftext.h"
37 : #include "engraving/dom/utils.h"
38 :
39 : #include "notation/iexcerptnotation.h" // IWYU pragma: keep
40 : #include "notation/imasternotation.h"
41 : #include "notation/inotationautomation.h"
42 : #include "notation/inotationinteraction.h"
43 : #include "notation/inotationnoteinput.h" // IWYU pragma: keep
44 : #include "notation/inotationparts.h"
45 : #include "notation/inotationselection.h"
46 :
47 : #include "project/inotationproject.h"
48 :
49 : #include "../playbacktypes.h"
50 : #include "onlinesoundscontroller.h"
51 :
52 : using namespace muse;
53 : using namespace muse::async;
54 : using namespace muse::audio;
55 : using namespace muse::midi;
56 : using namespace mu::engraving;
57 : using namespace mu::notation;
58 : using namespace mu::playback;
59 : using namespace mu::project;
60 :
61 : static const muse::Uri NOTATION_REVIEW_PAGE_URI("musescore://notation/review");
62 :
63 10 : static AudioOutputParams makeReverbOutputParams()
64 : {
65 10 : AudioFxParams reverbParams;
66 10 : reverbParams.resourceMeta = makeReverbMeta();
67 10 : reverbParams.categories.insert(AudioFxCategory::FxReverb);
68 10 : reverbParams.chainOrder = 0;
69 10 : reverbParams.active = true;
70 :
71 10 : AudioOutputParams result;
72 10 : result.fxChain.emplace(reverbParams.chainOrder, std::move(reverbParams));
73 :
74 10 : return result;
75 10 : }
76 :
77 20 : static std::string resolveAuxTrackTitle(aux_channel_idx_t index, const AudioOutputParams& params, bool considerFx = true)
78 : {
79 20 : if (considerFx && params.fxChain.size() == 1) {
80 0 : const AudioResourceMeta& meta = params.fxChain.cbegin()->second.resourceMeta;
81 0 : if (meta.id == MUSE_REVERB_ID) {
82 0 : return muse::trc("playback", "Reverb");
83 : }
84 :
85 0 : return meta.id;
86 : }
87 :
88 20 : return muse::mtrc("playback", "Aux %1").arg(index + 1).toStdString();
89 : }
90 :
91 19 : PlaybackController::PlaybackController(const muse::modularity::ContextPtr& iocCtx)
92 171 : : muse::Contextable(iocCtx), m_onlineSoundsController(std::make_unique<OnlineSoundsController>(iocCtx))
93 : {
94 171 : }
95 :
96 19 : PlaybackController::~PlaybackController() = default;
97 :
98 19 : void PlaybackController::init()
99 : {
100 19 : m_onlineSoundsController->regActions();
101 :
102 19 : projectSession()->currentNotationChanged().onNotify(this, [this]() {
103 22 : onNotationChanged();
104 :
105 22 : setupPlaybackIfNeed();
106 22 : });
107 :
108 19 : projectSession()->projectChanged().onNotify(this, [this]() {
109 21 : if (m_isPlaybackInited) {
110 0 : resetPlayback();
111 : }
112 :
113 21 : m_needSetupPlayback = projectSession()->project() != nullptr;
114 :
115 21 : if (m_needSetupPlayback) {
116 18 : m_loadingProgress.start();
117 : }
118 21 : });
119 :
120 19 : playback()->init().onResolve(this, [this](const Ret& ret) {
121 19 : if (!ret) {
122 0 : LOGE() << "failed to init the audio context: " << ret.toString();
123 0 : return;
124 : }
125 :
126 19 : setupPlaybackIfNeed();
127 : });
128 :
129 19 : m_totalPlayTimeChanged.onNotify(this, [this]() {
130 10 : updateCurrentTempo();
131 :
132 10 : updateLoop();
133 :
134 : // Tempo/repeat/duration changes shift what secs_t a given tick maps to,
135 : // which invalidates any Volume/Pan automation envelope already sent to the engine
136 10 : resendAutomationEnvelopes();
137 10 : });
138 :
139 19 : m_measureInputLag = configuration()->shouldMeasureInputLag();
140 19 : }
141 :
142 41 : void PlaybackController::setupPlaybackIfNeed()
143 : {
144 41 : if (!m_needSetupPlayback || !playback()->isInited()) {
145 24 : return;
146 : }
147 :
148 17 : m_needSetupPlayback = false;
149 :
150 17 : setupPlayback();
151 : }
152 :
153 2 : void PlaybackController::deinit()
154 : {
155 2 : m_needSetupPlayback = false;
156 :
157 2 : if (m_isPlaybackInited) {
158 0 : resetPlayback();
159 : }
160 :
161 2 : if (playback()->isInited()) {
162 1 : playback()->deinit();
163 : }
164 2 : }
165 :
166 10 : void PlaybackController::updateCurrentTempo()
167 : {
168 10 : if (!notationPlayback()) {
169 0 : return;
170 : }
171 :
172 10 : const Tempo& newTempo = notationPlayback()->multipliedTempo(m_currentTick);
173 :
174 10 : if (newTempo == m_currentTempo) {
175 10 : return;
176 : }
177 :
178 0 : m_currentTempo = newTempo;
179 0 : m_currentTempoChanged.notify();
180 : }
181 :
182 30 : bool PlaybackController::isPlayAllowed() const
183 : {
184 30 : if (!m_isPlaybackInited) {
185 20 : return false;
186 : }
187 :
188 10 : if (!m_notation) {
189 0 : return false;
190 : }
191 :
192 10 : if (!m_masterNotation) {
193 0 : return false;
194 : }
195 :
196 10 : const MasterScore* masterScore = m_masterNotation->masterScore();
197 10 : if (!masterScore) {
198 10 : return false;
199 : }
200 :
201 0 : if (!masterScore->firstMeasure()) {
202 0 : return false;
203 : }
204 :
205 0 : if (!m_notation->hasVisibleParts()) {
206 0 : return false;
207 : }
208 :
209 0 : if (!isLoaded()) {
210 0 : return false;
211 : }
212 :
213 0 : return true;
214 : }
215 :
216 0 : Channel<bool> PlaybackController::isPlayAllowedChanged() const
217 : {
218 0 : return m_isPlayAllowedChanged;
219 : }
220 :
221 0 : bool PlaybackController::isPlaying() const
222 : {
223 0 : if (!currentPlayer()) {
224 0 : return false;
225 : }
226 0 : return currentPlayer()->playbackStatus() == PlaybackStatus::Running;
227 : }
228 :
229 0 : Channel<bool> PlaybackController::isPlayingChanged() const
230 : {
231 0 : return m_isPlayingChanged;
232 : }
233 :
234 0 : muse::audio::secs_t PlaybackController::playbackPosition() const
235 : {
236 0 : if (!currentPlayer()) {
237 0 : return 0;
238 : }
239 0 : return currentPlayer()->playbackPosition();
240 : }
241 :
242 0 : muse::async::Channel<muse::audio::secs_t> PlaybackController::playbackPositionChanged() const
243 : {
244 0 : return m_playbackPositionChanged;
245 : }
246 :
247 0 : bool PlaybackController::isPaused() const
248 : {
249 0 : if (!currentPlayer()) {
250 0 : return false;
251 : }
252 0 : return currentPlayer()->playbackStatus() == PlaybackStatus::Paused;
253 : }
254 :
255 0 : bool PlaybackController::isLoaded() const
256 : {
257 0 : return m_loadingTrackCount == 0;
258 : }
259 :
260 0 : bool PlaybackController::isLoopEnabled() const
261 : {
262 0 : return notationPlayback() && notationPlayback()->isLoopEnabled();
263 : }
264 :
265 0 : Channel<bool> PlaybackController::loopEnabledChanged() const
266 : {
267 0 : return m_loopEnabledChanged;
268 : }
269 :
270 0 : bool PlaybackController::loopBoundariesSet() const
271 : {
272 0 : return notationPlayback() && !notationPlayback()->loopBoundaries().isNull();
273 : }
274 :
275 0 : void PlaybackController::seekRawTick(const midi::tick_t tick, const bool flushSound)
276 : {
277 0 : if (m_currentTick == tick) {
278 0 : return;
279 : }
280 :
281 0 : RetVal<midi::tick_t> playedTick = notationPlayback()->playPositionTickByRawTick(tick);
282 0 : if (!playedTick.ret) {
283 0 : return;
284 : }
285 :
286 0 : seek(playedTickToSecs(playedTick.val), flushSound);
287 0 : }
288 :
289 0 : void PlaybackController::seek(const audio::secs_t secs, const bool flushSound)
290 : {
291 0 : IF_ASSERT_FAILED(currentPlayer()) {
292 0 : return;
293 : }
294 :
295 0 : currentPlayer()->seek(secs, flushSound);
296 : }
297 :
298 0 : bool PlaybackController::isPlaybackInited() const
299 : {
300 0 : return m_isPlaybackInited;
301 : }
302 :
303 0 : muse::async::Channel<bool> PlaybackController::playbackInitedChanged() const
304 : {
305 0 : return m_playbackInited;
306 : }
307 :
308 0 : const IPlaybackController::InstrumentTrackIdMap& PlaybackController::instrumentTrackIdMap() const
309 : {
310 0 : return m_instrumentTrackIdMap;
311 : }
312 :
313 0 : const IPlaybackController::AuxTrackIdMap& PlaybackController::auxTrackIdMap() const
314 : {
315 0 : return m_auxTrackIdMap;
316 : }
317 :
318 0 : Channel<TrackId> PlaybackController::trackAdded() const
319 : {
320 0 : return m_trackAdded;
321 : }
322 :
323 0 : Channel<TrackId> PlaybackController::trackRemoved() const
324 : {
325 0 : return m_trackRemoved;
326 : }
327 :
328 0 : std::string PlaybackController::auxChannelName(aux_channel_idx_t index) const
329 : {
330 0 : return resolveAuxTrackTitle(index, audioSettings()->auxOutputParams(index));
331 : }
332 :
333 0 : Channel<aux_channel_idx_t, std::string> PlaybackController::auxChannelNameChanged() const
334 : {
335 0 : return m_auxChannelNameChanged;
336 : }
337 :
338 0 : Promise<SoundPresetList> PlaybackController::availableSoundPresets(const InstrumentTrackId& instrumentTrackId) const
339 : {
340 0 : auto it = m_instrumentTrackIdMap.find(instrumentTrackId);
341 0 : if (it == m_instrumentTrackIdMap.end()) {
342 0 : return Promise<SoundPresetList>([](auto, auto reject) {
343 0 : return reject(static_cast<int>(Ret::Code::UnknownError), "invalid instrumentTrackId");
344 0 : });
345 : }
346 :
347 0 : const AudioInputParams& params = audioSettings()->trackInputParams(instrumentTrackId);
348 0 : return playback()->availableSoundPresets(params.resourceMeta);
349 : }
350 :
351 0 : const PlaybackController::SoloMuteState& PlaybackController::trackSoloMuteState(const InstrumentTrackId& trackId) const
352 : {
353 0 : return m_notation->soloMuteState()->trackSoloMuteState(trackId);
354 : }
355 :
356 1 : void PlaybackController::setTrackSoloMuteState(const InstrumentTrackId& trackId, const SoloMuteState& state)
357 : {
358 1 : if (trackId == notationPlayback()->metronomeTrackId()) {
359 0 : if (state.mute != notationConfiguration()->isMetronomeEnabled()) {
360 0 : return;
361 : }
362 :
363 0 : toggleMetronome();
364 0 : return;
365 : }
366 :
367 1 : m_notation->soloMuteState()->setTrackSoloMuteState(trackId, state);
368 : }
369 :
370 0 : ControlParams PlaybackController::currentTrackControlParams(const InstrumentTrackId& trackId) const
371 : {
372 0 : IF_ASSERT_FAILED(audioSettings()) {
373 0 : return {};
374 : }
375 :
376 0 : const AudioOutputParams& outParams = audioSettings()->trackOutputParams(trackId);
377 0 : ControlParams control = outParams.control();
378 0 : control.muted = resolveTrackMuted(trackId, outParams.muted);
379 :
380 0 : const auto it = m_automationEnvelopesCache.find(trackId);
381 0 : if (it != m_automationEnvelopesCache.end()) {
382 0 : applyEnvelopes(it->second, control);
383 : }
384 :
385 0 : return control;
386 0 : }
387 :
388 13 : ControlParams PlaybackController::currentMasterControlParams() const
389 : {
390 13 : IF_ASSERT_FAILED(audioSettings()) {
391 0 : return {};
392 : }
393 :
394 13 : ControlParams control = audioSettings()->masterAudioOutputParams().control();
395 13 : applyEnvelopes(m_masterAutomationEnvelopes, control);
396 13 : return control;
397 13 : }
398 :
399 0 : void PlaybackController::playElements(const std::vector<const notation::EngravingItem*>& elements, const PlayParams& params, bool isMidi)
400 : {
401 0 : IF_ASSERT_FAILED(notationPlayback()) {
402 0 : return;
403 : }
404 :
405 0 : if ((!configuration()->playNotesWhenEditing()) || (isMidi && !configuration()->playNotesOnMidiInput())) {
406 0 : return;
407 : }
408 :
409 0 : if (m_measureInputLag) {
410 0 : START_INPUT_LAG_TIMER;
411 : }
412 :
413 0 : std::vector<const notation::EngravingItem*> elementsForPlaying;
414 0 : elementsForPlaying.reserve(elements.size());
415 :
416 0 : bool playChordWhenEditing = configuration()->playChordWhenEditing();
417 0 : bool playHarmonyWhenEditing = configuration()->playHarmonyWhenEditing();
418 :
419 0 : for (const EngravingItem* element : elements) {
420 0 : IF_ASSERT_FAILED(element) {
421 0 : continue;
422 : }
423 :
424 0 : if (!element->isPlayable()) {
425 0 : continue;
426 : }
427 :
428 0 : if (element->isChord() && !playChordWhenEditing) {
429 0 : continue;
430 : }
431 :
432 0 : if (element->isHarmony() && !playHarmonyWhenEditing) {
433 0 : continue;
434 : }
435 :
436 0 : elementsForPlaying.push_back(element);
437 : }
438 :
439 0 : const mpe::duration_t duration = params.duration.has_value() ? params.duration.value()
440 0 : : notationConfiguration()->notePlayDurationMilliseconds() * 1000;
441 :
442 0 : notationPlayback()->triggerEventsForItems(elementsForPlaying, duration, params.flushSound);
443 0 : }
444 :
445 0 : void PlaybackController::playNotes(const NoteValList& notes, staff_idx_t staffIdx, const Segment* segment, const PlayParams& params)
446 : {
447 0 : Segment* seg = const_cast<Segment*>(segment);
448 0 : Chord* chord = engraving::Factory::createChord(seg);
449 :
450 0 : std::vector<const EngravingItem*> elements;
451 0 : elements.reserve(notes.size());
452 :
453 0 : for (const NoteVal& nval : notes) {
454 0 : Note* note = engraving::Factory::createNote(chord);
455 0 : note->setStaffIdx(staffIdx);
456 0 : note->setNval(nval);
457 0 : elements.push_back(note);
458 : }
459 :
460 0 : playElements(elements, params);
461 :
462 0 : delete chord;
463 0 : DeleteAll(elements);
464 0 : }
465 :
466 0 : void PlaybackController::playMetronome(int tick)
467 : {
468 0 : notationPlayback()->triggerMetronome(tick);
469 0 : }
470 :
471 0 : void PlaybackController::triggerControllers(const muse::mpe::ControllerChangeEventList& list, staff_idx_t staffIdx, int tick)
472 : {
473 0 : notationPlayback()->triggerControllers(list, staffIdx, tick);
474 0 : }
475 :
476 0 : void PlaybackController::seekElement(const notation::EngravingItem* element, bool flushSound)
477 : {
478 0 : IF_ASSERT_FAILED(notationPlayback()) {
479 0 : return;
480 : }
481 :
482 0 : if (!element) {
483 0 : return;
484 : }
485 :
486 0 : RetVal<midi::tick_t> tick = notationPlayback()->playPositionTickByElement(element);
487 0 : if (!tick.ret) {
488 0 : return;
489 : }
490 :
491 0 : seek(playedTickToSecs(tick.val), flushSound);
492 0 : }
493 :
494 0 : void PlaybackController::seekBeat(int measureIndex, int beatIndex, bool flushSound)
495 : {
496 0 : secs_t targetSecs = beatToSecs(measureIndex, beatIndex);
497 0 : seek(targetSecs, flushSound);
498 0 : }
499 :
500 0 : void PlaybackController::seekRangeSelection()
501 : {
502 0 : if (!selection()->isRange()) {
503 0 : return;
504 : }
505 :
506 0 : midi::tick_t startTick = selectionRange()->startTick().ticks();
507 :
508 0 : seekRawTick(startTick);
509 : }
510 :
511 0 : void PlaybackController::onAudioResourceChanged(const TrackId trackId, const InstrumentTrackId& instrumentTrackId,
512 : const AudioResourceMeta& oldMeta, const AudioResourceMeta& newMeta)
513 : {
514 0 : INotationPlaybackPtr notationPlayback = this->notationPlayback();
515 0 : if (!notationPlayback) {
516 0 : return;
517 : }
518 :
519 0 : if (oldMeta.type == newMeta.type && oldMeta.id == newMeta.id) {
520 0 : return;
521 : }
522 :
523 0 : if (shouldLoadDrumset(instrumentTrackId, oldMeta, newMeta)) {
524 0 : m_drumsetLoader.loadDrumset(m_notation, instrumentTrackId, newMeta);
525 : }
526 :
527 0 : notationPlayback->removeSoundFlags({ instrumentTrackId });
528 :
529 0 : if (audio::isOnlineAudioResource(newMeta)) {
530 0 : m_onlineSoundsController->addOnlineTrack(trackId, newMeta);
531 0 : tours()->onEvent(u"online_sounds_added");
532 0 : notationPlayback->setSendEventsOnScoreChange(instrumentTrackId, true);
533 0 : } else if (audio::isOnlineAudioResource(oldMeta)) {
534 0 : m_onlineSoundsController->removeOnlineTrack(trackId);
535 0 : notationPlayback->setSendEventsOnScoreChange(instrumentTrackId, false);
536 : }
537 0 : }
538 :
539 10 : bool PlaybackController::shouldLoadDrumset(const engraving::InstrumentTrackId& instrumentTrackId,
540 : const AudioResourceMeta& oldMeta, const AudioResourceMeta& newMeta) const
541 : {
542 10 : if (oldMeta.type == newMeta.type && oldMeta.id == newMeta.id) {
543 10 : return false;
544 : }
545 :
546 0 : const Part* part = masterNotationParts()->part(instrumentTrackId.partId);
547 0 : const Instrument* instrument = part ? part->instrumentById(instrumentTrackId.instrumentId) : nullptr;
548 0 : if (!instrument || !instrument->useDrumset()) {
549 0 : return false;
550 : }
551 :
552 0 : return isResourceType(oldMeta, AudioResourceType::MuseSamplerSoundPack)
553 0 : || isResourceType(newMeta, AudioResourceType::MuseSamplerSoundPack);
554 : }
555 :
556 0 : void PlaybackController::addSoundFlagsIfNeed(const std::vector<EngravingItem*>& selection)
557 : {
558 0 : if (selection.empty()) {
559 0 : return;
560 : }
561 :
562 0 : std::vector<StaffText*> staffTextList;
563 :
564 0 : for (EngravingItem* item : selection) {
565 0 : if (!item || !item->isStaffText()) {
566 0 : continue;
567 : }
568 :
569 0 : InstrumentTrackId trackId = mu::engraving::makeInstrumentTrackId(item);
570 0 : const AudioInputParams& params = audioSettings()->trackInputParams(trackId);
571 :
572 0 : bool supportsSoundFlags = params.type() == AudioSourceType::MuseSampler;
573 0 : if (supportsSoundFlags) {
574 0 : staffTextList.push_back(toStaffText(item));
575 : }
576 0 : }
577 :
578 0 : if (!staffTextList.empty()) {
579 0 : notationPlayback()->addSoundFlags(staffTextList);
580 : }
581 0 : }
582 :
583 40 : muse::audio::IPlayerPtr PlaybackController::currentPlayer() const
584 : {
585 40 : return m_player;
586 : }
587 :
588 356 : INotationPlaybackPtr PlaybackController::notationPlayback() const
589 : {
590 356 : return m_masterNotation ? m_masterNotation->playback() : nullptr;
591 : }
592 :
593 20 : INotationPartsPtr PlaybackController::masterNotationParts() const
594 : {
595 20 : return m_masterNotation ? m_masterNotation->parts() : nullptr;
596 : }
597 :
598 63 : INotationSelectionPtr PlaybackController::selection() const
599 : {
600 63 : return m_notation ? m_notation->interaction()->selection() : nullptr;
601 : }
602 :
603 42 : INotationSelectionRangePtr PlaybackController::selectionRange() const
604 : {
605 42 : INotationSelectionPtr selection = this->selection();
606 84 : return selection ? selection->range() : nullptr;
607 42 : }
608 :
609 0 : INotationInteractionPtr PlaybackController::interaction() const
610 : {
611 0 : return m_notation ? m_notation->interaction() : nullptr;
612 : }
613 :
614 40 : uint64_t PlaybackController::notationPlaybackKey() const
615 : {
616 40 : return reinterpret_cast<uint64_t>(notationPlayback().get());
617 : }
618 :
619 22 : void PlaybackController::onNotationChanged()
620 : {
621 22 : setNotation(projectSession()->currentNotation());
622 22 : }
623 :
624 0 : void PlaybackController::onPartChanged(const Part* part)
625 : {
626 0 : if (!m_notation->hasVisibleParts()) {
627 0 : doPause();
628 : }
629 0 : m_isPlayAllowedChanged.send(isPlayAllowed());
630 :
631 0 : if (!configuration()->muteHiddenInstruments()) {
632 0 : return;
633 : }
634 :
635 0 : for (const InstrumentTrackId& instrumentTrackId : part->instrumentTrackIdList()) {
636 0 : auto soloMuteState = trackSoloMuteState(instrumentTrackId);
637 0 : soloMuteState.mute = !part->show();
638 0 : setTrackSoloMuteState(instrumentTrackId, soloMuteState);
639 0 : }
640 :
641 0 : if (part->hasChordSymbol()) {
642 0 : InstrumentTrackId chordSymbolsTrackId = notationPlayback()->chordSymbolsTrackId(part->id());
643 0 : auto chordsSoloMuteState = trackSoloMuteState(chordSymbolsTrackId);
644 0 : chordsSoloMuteState.mute = !part->show();
645 0 : setTrackSoloMuteState(chordSymbolsTrackId, chordsSoloMuteState);
646 0 : }
647 : }
648 :
649 0 : void PlaybackController::onSelectionChanged()
650 : {
651 0 : const INotationSelectionPtr selection = this->selection();
652 0 : if (!selection || !m_player) {
653 0 : return;
654 : }
655 :
656 0 : bool selectionTypeChanged = m_isRangeSelection && !selection->isRange();
657 0 : m_isRangeSelection = selection->isRange();
658 :
659 0 : if (!m_isRangeSelection) {
660 0 : if (selectionTypeChanged) {
661 0 : updateLoop();
662 0 : updateSoloMuteStates();
663 : }
664 :
665 0 : addSoundFlagsIfNeed(selection->elements());
666 0 : return;
667 : }
668 :
669 0 : m_player->resetLoop();
670 :
671 0 : seekRangeSelection();
672 0 : updateSoloMuteStates();
673 0 : }
674 :
675 0 : muse::Ret PlaybackController::togglePlay()
676 : {
677 0 : if (isPlaying()) {
678 0 : return pause();
679 : }
680 :
681 0 : if (isPaused()) {
682 0 : doResume();
683 0 : return make_ok();
684 : }
685 :
686 0 : return play();
687 : }
688 :
689 0 : muse::Ret PlaybackController::play(bool showErrors)
690 : {
691 0 : if (!isPlayAllowed()) {
692 0 : LOGW() << "playback not allowed";
693 0 : return make_ret(Ret::Code::NotSupported);
694 : }
695 :
696 0 : IF_ASSERT_FAILED(currentPlayer()) {
697 0 : return make_ret(Ret::Code::InternalError);
698 : }
699 :
700 0 : if (showErrors && m_onlineSoundsController->shouldShowOnlineSoundsProcessingError(isPlaying())) {
701 0 : m_onlineSoundsController->showOnlineSoundsProcessingError([this]() { play(false /*showErrors*/); });
702 0 : return make_ret(Ret::Code::NotSupported);
703 : }
704 :
705 0 : interaction()->endEditElement();
706 0 : interaction()->noteInput()->endNoteInput();
707 :
708 0 : if (isPaused()) {
709 0 : notationPlayback()->sendEventsForChangedTracks();
710 :
711 0 : secs_t pos = currentPlayer()->playbackPosition();
712 0 : secs_t endSecs = totalPlayTime();
713 0 : if (pos == endSecs) {
714 0 : secs_t startSecs = playbackStartSecs();
715 0 : seek(startSecs);
716 : }
717 :
718 0 : doResume();
719 : } else {
720 0 : notationPlayback()->sendEventsForChangedTracks();
721 :
722 0 : doPlay();
723 : }
724 :
725 0 : return make_ok();
726 : }
727 :
728 0 : muse::Ret PlaybackController::pause(bool select)
729 : {
730 0 : if (isPlaying()) {
731 0 : doPause(select);
732 : }
733 :
734 0 : return make_ok();
735 : }
736 :
737 0 : muse::Ret PlaybackController::stop()
738 : {
739 0 : doStop();
740 0 : return make_ok();
741 : }
742 :
743 0 : muse::Ret PlaybackController::rewind(muse::secs_t secs)
744 : {
745 0 : if (!isPlayAllowed()) {
746 0 : LOGW() << "playback not allowed";
747 0 : return make_ret(Ret::Code::NotSupported);
748 : }
749 :
750 0 : doRewind(secs);
751 0 : return make_ok();
752 : }
753 :
754 0 : muse::Ret PlaybackController::playFromSelection(bool showErrors)
755 : {
756 0 : if (!isPlayAllowed()) {
757 0 : LOGW() << "playback not allowed";
758 0 : return make_ret(Ret::Code::NotSupported);
759 : }
760 :
761 0 : if (showErrors && m_onlineSoundsController->shouldShowOnlineSoundsProcessingError(isPlaying())) {
762 0 : m_onlineSoundsController->showOnlineSoundsProcessingError([this]() { playFromSelection(false /*showErrors*/); });
763 0 : return make_ret(Ret::Code::NotSupported);
764 : }
765 :
766 0 : int startTick = 0;
767 :
768 0 : if (!selection()->isNone()) {
769 0 : startTick = INT_MAX;
770 0 : for (const EngravingItem* item : selection()->elements()) {
771 0 : startTick = std::min(startTick, item->tick().ticks());
772 : }
773 : } else {
774 : // Selection is none - fall back to last element hit...
775 0 : if (const EngravingItem* lastElementHit = selection()->lastElementHit()) {
776 0 : startTick = lastElementHit->tick().ticks();
777 : }
778 : }
779 :
780 0 : const LoopBoundaries& loop = notationPlayback()->loopBoundaries();
781 0 : if (loop.enabled) {
782 0 : if (startTick < loop.loopInTick.ticks() || startTick > loop.loopOutTick.ticks()) {
783 0 : startTick = loop.loopInTick.ticks();
784 : }
785 : }
786 :
787 0 : const RetVal<midi::tick_t> retval = notationPlayback()->playPositionTickByRawTick(startTick);
788 0 : if (!retval.ret) {
789 0 : return retval.ret;
790 : }
791 :
792 0 : seek(playedTickToSecs(retval.val));
793 :
794 0 : if (isPaused()) {
795 0 : doResume();
796 0 : } else if (!isPlaying()) {
797 0 : doPlay();
798 : }
799 :
800 0 : return make_ok();
801 0 : }
802 :
803 0 : void PlaybackController::doPlay()
804 : {
805 0 : IF_ASSERT_FAILED(currentPlayer()) {
806 0 : return;
807 : }
808 :
809 0 : if (isLoopEnabled()) {
810 0 : secs_t startSecs = playbackStartSecs();
811 0 : seek(startSecs);
812 : }
813 :
814 0 : currentPlayer()->prepareToPlay().onResolve(this, [this](const Ret& ret) {
815 0 : if (!currentPlayer()) {
816 0 : return;
817 : }
818 :
819 0 : if (!ret) {
820 0 : LOGE() << ret.toString();
821 : }
822 :
823 0 : secs_t delay = 0.;
824 0 : if (notationConfiguration()->isCountInEnabled()) {
825 0 : notationPlayback()->triggerCountIn(m_currentTick, delay);
826 : }
827 :
828 0 : currentPlayer()->play(delay);
829 : });
830 : }
831 :
832 0 : void PlaybackController::doRewind(secs_t newPosition)
833 : {
834 0 : secs_t startSecs = playbackStartSecs();
835 0 : secs_t endSecs = totalPlayTime();
836 0 : newPosition = std::clamp(newPosition, startSecs, endSecs);
837 :
838 0 : seek(newPosition);
839 0 : }
840 :
841 0 : void PlaybackController::doPause(bool select)
842 : {
843 0 : IF_ASSERT_FAILED(currentPlayer()) {
844 0 : return;
845 : }
846 :
847 0 : if (isPaused()) {
848 0 : return;
849 : }
850 :
851 0 : currentPlayer()->pause();
852 :
853 0 : if (select && m_notation) {
854 0 : const Fraction playPositionFrac = Fraction::fromTicks(m_currentTick);
855 0 : interaction()->findAndSelectChordRest(playPositionFrac);
856 : }
857 : }
858 :
859 0 : void PlaybackController::doStop()
860 : {
861 0 : IF_ASSERT_FAILED(currentPlayer()) {
862 0 : return;
863 : }
864 :
865 0 : currentPlayer()->stop();
866 : }
867 :
868 0 : void PlaybackController::doResume()
869 : {
870 0 : IF_ASSERT_FAILED(currentPlayer()) {
871 0 : return;
872 : }
873 :
874 0 : currentPlayer()->prepareToPlay().onResolve(this, [this](const Ret& ret) {
875 0 : if (!currentPlayer()) {
876 0 : return;
877 : }
878 :
879 0 : if (!ret) {
880 0 : LOGE() << ret.toString();
881 : }
882 :
883 0 : secs_t delay = 0.;
884 0 : if (notationConfiguration()->isCountInEnabled()) {
885 0 : notationPlayback()->triggerCountIn(m_currentTick, delay);
886 : }
887 :
888 0 : currentPlayer()->resume(delay);
889 : });
890 : }
891 :
892 0 : void PlaybackController::onPlaybackStatusChanged()
893 : {
894 0 : const bool playing = isPlaying();
895 0 : m_isPlayingChanged.send(playing);
896 :
897 0 : if (!notationPlayback()) {
898 0 : return;
899 : }
900 :
901 0 : const auto& onlineSounds = m_onlineSoundsController->onlineSounds();
902 :
903 0 : for (const auto& pair : m_instrumentTrackIdMap) {
904 0 : bool shouldSendOnScoreChange = playing || muse::contains(onlineSounds, pair.second);
905 0 : notationPlayback()->setSendEventsOnScoreChange(pair.first, shouldSendOnScoreChange);
906 : }
907 : }
908 :
909 0 : secs_t PlaybackController::playbackStartSecs() const
910 : {
911 0 : if (!m_notation) {
912 0 : return 0;
913 : }
914 :
915 0 : const LoopBoundaries& loop = notationPlayback()->loopBoundaries();
916 0 : if (loop.enabled) {
917 : // Convert from raw ticks (visual tick != playback tick due to repeats etc)
918 0 : RetVal<tick_t> startTick = notationPlayback()->playPositionTickByRawTick(loop.loopInTick.ticks());
919 0 : if (!startTick.ret) {
920 0 : return 0;
921 : }
922 0 : return playedTickToSecs(startTick.val);
923 0 : }
924 :
925 0 : return 0;
926 : }
927 :
928 21 : InstrumentTrackIdSet PlaybackController::instrumentTrackIdSetForRangePlayback() const
929 : {
930 21 : std::vector<const Part*> selectedParts = selectionRange()->selectedParts();
931 21 : Fraction startTick = selectionRange()->startTick();
932 21 : int startTicks = startTick.ticks();
933 :
934 21 : InstrumentTrackIdSet result;
935 :
936 21 : for (const Part* part : selectedParts) {
937 0 : if (const Instrument* startInstrument = part->instrument(startTick)) {
938 0 : result.insert({ part->id(), startInstrument->id() });
939 : }
940 :
941 0 : for (auto [tick, instrument] : part->instruments()) {
942 0 : if (tick > startTicks) {
943 0 : result.insert({ part->id(), instrument->id() });
944 : }
945 : }
946 :
947 0 : if (part->hasChordSymbol()) {
948 0 : result.insert(notationPlayback()->chordSymbolsTrackId(part->id()));
949 : }
950 : }
951 :
952 21 : return result;
953 21 : }
954 :
955 0 : muse::Ret PlaybackController::togglePlayRepeats()
956 : {
957 0 : bool playRepeatsEnabled = notationConfiguration()->isPlayRepeatsEnabled();
958 0 : notationConfiguration()->setIsPlayRepeatsEnabled(!playRepeatsEnabled);
959 0 : return make_ok();
960 : }
961 :
962 0 : muse::Ret PlaybackController::togglePlayChordSymbols()
963 : {
964 0 : bool playChordSymbolsEnabled = notationConfiguration()->isPlayChordSymbolsEnabled();
965 0 : notationConfiguration()->setIsPlayChordSymbolsEnabled(!playChordSymbolsEnabled);
966 :
967 0 : for (auto it = m_instrumentTrackIdMap.cbegin(); it != m_instrumentTrackIdMap.cend(); ++it) {
968 0 : if (notationPlayback()->isChordSymbolsTrack(it->first)) {
969 0 : setTrackActivity(it->first, !playChordSymbolsEnabled);
970 : }
971 : }
972 0 : return make_ok();
973 : }
974 :
975 0 : muse::Ret PlaybackController::toggleAutomaticallyPan()
976 : {
977 0 : bool panEnabled = notationConfiguration()->isAutomaticallyPanEnabled();
978 0 : notationConfiguration()->setIsAutomaticallyPanEnabled(!panEnabled);
979 0 : return make_ok();
980 : }
981 :
982 0 : muse::Ret PlaybackController::toggleMetronome()
983 : {
984 0 : bool metronomeEnabled = notationConfiguration()->isMetronomeEnabled();
985 0 : bool countInEnabled = notationConfiguration()->isCountInEnabled();
986 :
987 0 : notationConfiguration()->setIsMetronomeEnabled(!metronomeEnabled);
988 :
989 0 : setTrackActivity(notationPlayback()->metronomeTrackId(), !metronomeEnabled || countInEnabled);
990 :
991 0 : return make_ok();
992 : }
993 :
994 0 : muse::Ret PlaybackController::toggleCountIn()
995 : {
996 0 : bool metronomeEnabled = notationConfiguration()->isMetronomeEnabled();
997 0 : bool countInEnabled = notationConfiguration()->isCountInEnabled();
998 :
999 0 : notationConfiguration()->setIsCountInEnabled(!countInEnabled);
1000 :
1001 0 : setTrackActivity(notationPlayback()->metronomeTrackId(), metronomeEnabled || !countInEnabled);
1002 :
1003 0 : return make_ok();
1004 : }
1005 :
1006 0 : muse::Ret PlaybackController::toggleMidiInput()
1007 : {
1008 0 : bool wasMidiInputEnabled = notationConfiguration()->isMidiInputEnabled();
1009 0 : notationConfiguration()->setIsMidiInputEnabled(!wasMidiInputEnabled);
1010 0 : return make_ok();
1011 : }
1012 :
1013 0 : muse::Ret PlaybackController::setMidiUseWrittenPitch(bool useWrittenPitch)
1014 : {
1015 0 : notationConfiguration()->setMidiUseWrittenPitch(useWrittenPitch);
1016 0 : return make_ok();
1017 : }
1018 :
1019 0 : muse::Ret PlaybackController::toggleLoopPlayback()
1020 : {
1021 0 : if (isLoopEnabled()) {
1022 0 : disableLoop();
1023 0 : return make_ok();
1024 : }
1025 :
1026 0 : if (loopBoundariesSet() && !selection()->isRange()) {
1027 0 : enableLoop();
1028 0 : return make_ok();
1029 : }
1030 :
1031 0 : int loopInTick = 0;
1032 0 : int loopOutTick = 0;
1033 :
1034 0 : if (!selection()->isNone()) {
1035 0 : loopInTick = selectionRange()->startTick().ticks();
1036 0 : loopOutTick = selectionRange()->endTick().ticks();
1037 : }
1038 :
1039 0 : if (loopInTick <= 0) {
1040 0 : loopInTick = INotationPlayback::FirstScoreTick;
1041 : }
1042 :
1043 0 : if (loopOutTick <= 0) {
1044 0 : loopOutTick = INotationPlayback::LastScoreTick;
1045 : }
1046 :
1047 0 : addLoopBoundaryToTick(LoopBoundaryType::LoopIn, loopInTick);
1048 0 : addLoopBoundaryToTick(LoopBoundaryType::LoopOut, loopOutTick);
1049 :
1050 0 : return make_ok();
1051 : }
1052 :
1053 0 : muse::Ret PlaybackController::toggleHearPlaybackWhenEditing()
1054 : {
1055 0 : bool wasPlayNotesWhenEditing = configuration()->playNotesWhenEditing();
1056 0 : configuration()->setPlayNotesWhenEditing(!wasPlayNotesWhenEditing);
1057 0 : return make_ok();
1058 : }
1059 :
1060 0 : muse::Ret PlaybackController::reloadPlaybackCache()
1061 : {
1062 0 : INotationPlaybackPtr nPlayback = notationPlayback();
1063 0 : if (nPlayback) {
1064 0 : nPlayback->reload();
1065 : }
1066 :
1067 0 : return make_ok();
1068 0 : }
1069 :
1070 0 : muse::Ret PlaybackController::addLoopBoundary(LoopBoundaryType type)
1071 : {
1072 0 : if (isPlaying()) {
1073 0 : addLoopBoundaryToTick(type, m_currentTick);
1074 : } else {
1075 0 : addLoopBoundaryToTick(type, INotationPlayback::SelectedNoteTick);
1076 : }
1077 :
1078 0 : return make_ok();
1079 : }
1080 :
1081 0 : void PlaybackController::addLoopBoundaryToTick(LoopBoundaryType type, int tick)
1082 : {
1083 0 : if (notationPlayback()) {
1084 0 : notationPlayback()->addLoopBoundary(type, tick);
1085 0 : enableLoop();
1086 : }
1087 0 : }
1088 :
1089 10 : void PlaybackController::updateLoop()
1090 : {
1091 10 : if (!notationPlayback() || !currentPlayer()) {
1092 10 : return;
1093 : }
1094 :
1095 0 : const LoopBoundaries& boundaries = notationPlayback()->loopBoundaries();
1096 :
1097 0 : if (!boundaries.enabled) {
1098 0 : disableLoop();
1099 0 : return;
1100 : }
1101 :
1102 : // Convert from raw ticks (visual tick != playback tick due to repeats etc)
1103 0 : RetVal<tick_t> playbackTickFrom = notationPlayback()->playPositionTickByRawTick(boundaries.loopInTick.ticks());
1104 0 : RetVal<tick_t> playbackTickTo = notationPlayback()->playPositionTickByRawTick(boundaries.loopOutTick.ticks());
1105 0 : if (!playbackTickFrom.ret || !playbackTickTo.ret) {
1106 0 : return;
1107 : }
1108 :
1109 0 : secs_t fromSecs = playedTickToSecs(playbackTickFrom.val);
1110 0 : secs_t toSecs = playedTickToSecs(playbackTickTo.val);
1111 0 : currentPlayer()->setLoop(fromSecs, toSecs);
1112 :
1113 0 : enableLoop();
1114 0 : }
1115 :
1116 0 : void PlaybackController::enableLoop()
1117 : {
1118 0 : if (notationPlayback()) {
1119 0 : notationPlayback()->setLoopBoundariesEnabled(true);
1120 : }
1121 0 : }
1122 :
1123 0 : void PlaybackController::disableLoop()
1124 : {
1125 0 : IF_ASSERT_FAILED(notationPlayback() && currentPlayer()) {
1126 0 : return;
1127 : }
1128 :
1129 0 : currentPlayer()->resetLoop();
1130 0 : notationPlayback()->setLoopBoundariesEnabled(false);
1131 : }
1132 :
1133 192 : mu::project::IProjectAudioSettingsPtr PlaybackController::audioSettings() const
1134 : {
1135 192 : INotationProjectPtr project = projectSession()->project();
1136 192 : IF_ASSERT_FAILED(project) {
1137 0 : return nullptr;
1138 : }
1139 :
1140 192 : return project->audioSettings();
1141 192 : }
1142 :
1143 0 : void PlaybackController::resetPlayback()
1144 : {
1145 0 : auto player = m_player;
1146 :
1147 0 : m_player = nullptr;
1148 0 : m_currentTick = 0;
1149 :
1150 0 : if (player) {
1151 0 : player->playbackPositionChanged().disconnect(this);
1152 0 : player->playbackStatusChanged().disconnect(this);
1153 :
1154 0 : player->stop();
1155 0 : player->seek(0);
1156 0 : m_playbackPositionChanged.send(0);
1157 0 : m_isPlayingChanged.send(false);
1158 : }
1159 :
1160 0 : playback()->clearSources();
1161 0 : playback()->sourceParamsChanged().disconnect(this);
1162 0 : playback()->controlParamsChanged().disconnect(this);
1163 0 : playback()->fxChainParamsChanged().disconnect(this);
1164 0 : playback()->auxSendsParamsChanged().disconnect(this);
1165 0 : playback()->clearAllFx();
1166 0 : playback()->masterControlParamsChanged().disconnect(this);
1167 0 : playback()->masterFxChainParamsChanged().disconnect(this);
1168 0 : playback()->masterAuxSendsParamsChanged().disconnect(this);
1169 0 : playback()->clearMasterOutputParams();
1170 :
1171 0 : m_seqAsyncReceiver.async_disconnectAll();
1172 :
1173 0 : m_instrumentTrackIdMap.clear();
1174 0 : m_auxTrackIdMap.clear();
1175 0 : m_automationEnvelopesCache.clear();
1176 0 : m_masterAutomationEnvelopes = {};
1177 :
1178 0 : m_isRangeSelection = false;
1179 :
1180 0 : m_isPlaybackInited = false;
1181 0 : m_playbackInited.send(m_isPlaybackInited);
1182 :
1183 0 : m_onlineSoundsController->reset();
1184 0 : }
1185 :
1186 10 : void PlaybackController::addTrack(const InstrumentTrackId& instrumentTrackId, bool projectHadNoAudioSettings,
1187 : const TrackAddFinished& onFinished)
1188 : {
1189 10 : const std::optional<std::string> trackName = notationPlayback()->trackName(instrumentTrackId);
1190 10 : if (trackName) {
1191 10 : doAddTrack(instrumentTrackId, *trackName, projectHadNoAudioSettings, onFinished);
1192 : }
1193 10 : }
1194 :
1195 10 : void PlaybackController::doAddTrack(const InstrumentTrackId& instrumentTrackId, const std::string& title,
1196 : bool projectHadNoAudioSettings, const TrackAddFinished& onFinished)
1197 : {
1198 10 : IF_ASSERT_FAILED(notationPlayback() && playback()) {
1199 0 : return;
1200 : }
1201 :
1202 10 : if (!instrumentTrackId.isValid()) {
1203 0 : return;
1204 : }
1205 :
1206 10 : mpe::PlaybackData playbackData = notationPlayback()->trackPlaybackData(instrumentTrackId);
1207 10 : if (!playbackData.isValid()) {
1208 0 : return;
1209 : }
1210 :
1211 10 : AudioInputParams inParams = audioSettings()->trackInputParams(instrumentTrackId);
1212 10 : AudioOutputParams originParams = trackOutputParams(instrumentTrackId);
1213 10 : AudioResourceMeta originMeta = inParams.resourceMeta;
1214 :
1215 10 : bool isMetronome = notationPlayback()->metronomeTrackId() == instrumentTrackId;
1216 :
1217 10 : if (!inParams.isValid()) {
1218 0 : if (isMetronome) {
1219 0 : const SoundProfile& profile = profilesRepo()->profile(configuration()->basicSoundProfileName());
1220 0 : inParams = { profile.findResource(playbackData.setupData), {} };
1221 : } else {
1222 0 : const SoundProfile& profile = profilesRepo()->profile(audioSettings()->activeSoundProfile());
1223 0 : inParams = { profile.findResource(playbackData.setupData), {} };
1224 : }
1225 : }
1226 :
1227 10 : if (!isMetronome && originParams.auxSends.empty()) {
1228 10 : const muse::String& instrumentSoundId = inParams.resourceMeta.attributeVal(PLAYBACK_SETUP_DATA_ATTRIBUTE);
1229 10 : AudioSourceType sourceType = inParams.isValid() ? inParams.type() : AudioSourceType::Fluid;
1230 :
1231 30 : for (aux_channel_idx_t idx = 0; idx < AUX_CHANNEL_NUM; ++idx) {
1232 20 : gain_t signalAmount = configuration()->defaultAuxSendValue(idx, sourceType, instrumentSoundId);
1233 20 : originParams.auxSends.emplace_back(AuxSendParams { signalAmount, true });
1234 : }
1235 : }
1236 :
1237 10 : uint64_t playbackKey = notationPlaybackKey();
1238 :
1239 10 : TrackParams trackParams;
1240 10 : trackParams.source = inParams;
1241 10 : trackParams.fxChain = originParams.fxChain;
1242 10 : trackParams.auxSends = originParams.auxSends;
1243 10 : trackParams.control = trackControlParams(instrumentTrackId, originParams);
1244 :
1245 : struct {
1246 : uint64_t playbackKey;
1247 : InstrumentTrackId instrumentTrackId;
1248 : bool projectHadNoAudioSettings;
1249 : AudioOutputParams originParams;
1250 : TrackAddFinished onFinished;
1251 : AudioResourceMeta originMeta;
1252 10 : } tctx = { playbackKey, instrumentTrackId, projectHadNoAudioSettings, originParams, onFinished, originMeta };
1253 :
1254 10 : playback()->addTrack(title, std::move(playbackData), trackParams)
1255 20 : .onResolve(this, [this, tctx](const TrackId trackId, const TrackParams& appliedParams) {
1256 : //! NOTE It may be that while we were adding a track, the notation was already closed (or opened another)
1257 : //! This situation can be if the notation was opened and immediately closed.
1258 10 : if (notationPlaybackKey() != tctx.playbackKey) {
1259 0 : return;
1260 : }
1261 :
1262 : // context variables
1263 10 : const InstrumentTrackId instrumentTrackId = tctx.instrumentTrackId;
1264 10 : const bool projectHadNoAudioSettings = tctx.projectHadNoAudioSettings;
1265 10 : const AudioOutputParams& originParams = tctx.originParams;
1266 10 : const TrackAddFinished onFinished = tctx.onFinished;
1267 10 : const AudioResourceMeta& originMeta = tctx.originMeta;
1268 :
1269 10 : m_instrumentTrackIdMap.insert({ instrumentTrackId, trackId });
1270 :
1271 : const bool trackNewlyAdded = projectHadNoAudioSettings
1272 10 : || !audioSettings()->trackHasExistingOutputParams(instrumentTrackId);
1273 :
1274 10 : auto appliedOutParams = originParams;
1275 10 : appliedOutParams.fxChain = appliedParams.fxChain;
1276 :
1277 10 : audioSettings()->setTrackInputParams(instrumentTrackId, appliedParams.source, !projectHadNoAudioSettings);
1278 10 : audioSettings()->setTrackOutputParams(instrumentTrackId, appliedOutParams, !projectHadNoAudioSettings);
1279 :
1280 10 : updateSoloMuteStates();
1281 :
1282 10 : onFinished();
1283 :
1284 10 : m_trackAdded.send(trackId);
1285 :
1286 10 : if (trackNewlyAdded) {
1287 10 : onTrackNewlyAdded(instrumentTrackId);
1288 : }
1289 :
1290 10 : if (shouldLoadDrumset(instrumentTrackId, originMeta, appliedParams.source.resourceMeta)) {
1291 0 : m_drumsetLoader.loadDrumset(m_notation, instrumentTrackId, appliedParams.source.resourceMeta);
1292 : }
1293 :
1294 10 : if (muse::audio::isOnlineAudioResource(appliedParams.source.resourceMeta)) {
1295 0 : m_onlineSoundsController->addOnlineTrack(trackId, appliedParams.source.resourceMeta);
1296 :
1297 0 : if (notationPlayback()) {
1298 0 : notationPlayback()->setSendEventsOnScoreChange(instrumentTrackId, true);
1299 : }
1300 : }
1301 10 : })
1302 10 : .onReject(this, [instrumentTrackId, onFinished](int code, const std::string& msg) {
1303 0 : LOGE() << "can't add a new track, code: [" << code << "] " << msg;
1304 :
1305 0 : onFinished();
1306 0 : });
1307 :
1308 10 : m_loadingTrackCount++;
1309 10 : }
1310 :
1311 20 : void PlaybackController::addAuxTrack(aux_channel_idx_t index, bool projectHadNoAudioSettings, const TrackAddFinished& onFinished)
1312 : {
1313 20 : IF_ASSERT_FAILED(notationPlayback() && playback()) {
1314 0 : return;
1315 : }
1316 :
1317 20 : AudioOutputParams originParams;
1318 :
1319 20 : if (audioSettings()->containsAuxOutputParams(index)) {
1320 0 : originParams = audioSettings()->auxOutputParams(index);
1321 20 : } else if (index == REVERB_CHANNEL_IDX) {
1322 10 : originParams = makeReverbOutputParams();
1323 : }
1324 :
1325 20 : TrackParams trackParams;
1326 20 : trackParams.source = {};
1327 20 : trackParams.fxChain = originParams.fxChain;
1328 20 : trackParams.auxSends = originParams.auxSends;
1329 20 : trackParams.control = originParams.control();
1330 :
1331 20 : std::string title = resolveAuxTrackTitle(index, originParams, false);
1332 20 : uint64_t playbackKey = notationPlaybackKey();
1333 :
1334 : struct {
1335 : uint64_t playbackKey;
1336 : aux_channel_idx_t index;
1337 : bool projectHadNoAudioSettings;
1338 : AudioOutputParams originParams;
1339 : TrackAddFinished onFinished;
1340 20 : } tctx = { playbackKey, index, projectHadNoAudioSettings, originParams, onFinished };
1341 :
1342 20 : playback()->addAuxTrack(title, trackParams)
1343 40 : .onResolve(this, [this, tctx](const TrackId trackId, const TrackParams& appliedParams) {
1344 : //! NOTE It may be that while we were adding a track, the notation was already closed (or opened another)
1345 : //! This situation can be if the notation was opened and immediately closed.
1346 0 : if (notationPlaybackKey() != tctx.playbackKey) {
1347 0 : return;
1348 : }
1349 :
1350 : // context variables
1351 0 : const aux_channel_idx_t index = tctx.index;
1352 0 : const bool projectHadNoAudioSettings = tctx.projectHadNoAudioSettings;
1353 0 : const AudioOutputParams& originParams = tctx.originParams;
1354 0 : const TrackAddFinished onFinished = tctx.onFinished;
1355 :
1356 0 : m_auxTrackIdMap.insert({ index, trackId });
1357 :
1358 0 : auto appliedOutParams = originParams;
1359 0 : appliedOutParams.fxChain = appliedParams.fxChain;
1360 :
1361 0 : audioSettings()->setAuxOutputParams(index, appliedOutParams, !projectHadNoAudioSettings);
1362 :
1363 0 : updateSoloMuteStates();
1364 0 : onFinished();
1365 :
1366 0 : m_trackAdded.send(trackId);
1367 0 : })
1368 20 : .onReject(this, [onFinished](int code, const std::string& msg) {
1369 20 : LOGE() << "can't add a new aux track, code: [" << code << "] " << msg;
1370 :
1371 20 : onFinished();
1372 20 : });
1373 :
1374 20 : m_loadingTrackCount++;
1375 40 : }
1376 :
1377 0 : void PlaybackController::setTrackActivity(const engraving::InstrumentTrackId& instrumentTrackId, const bool isActive)
1378 : {
1379 0 : IF_ASSERT_FAILED(audioSettings() && playback()) {
1380 0 : return;
1381 : }
1382 :
1383 0 : AudioOutputParams outParams = audioSettings()->trackOutputParams(instrumentTrackId);
1384 0 : ControlParams control = trackControlParams(instrumentTrackId, outParams, /*rebuildVolume*/ false, /*rebuildPan*/ false);
1385 :
1386 0 : control.muted = !isActive;
1387 :
1388 0 : audio::TrackId trackId = m_instrumentTrackIdMap[instrumentTrackId];
1389 0 : playback()->setControlParams(trackId, control);
1390 0 : }
1391 :
1392 26 : AudioOutputParams PlaybackController::trackOutputParams(const InstrumentTrackId& instrumentTrackId) const
1393 : {
1394 26 : IF_ASSERT_FAILED(audioSettings()) {
1395 0 : return {};
1396 : }
1397 :
1398 26 : AudioOutputParams result = audioSettings()->trackOutputParams(instrumentTrackId);
1399 26 : result.muted = resolveTrackMuted(instrumentTrackId, result.muted);
1400 26 : return result;
1401 26 : }
1402 :
1403 26 : bool PlaybackController::resolveTrackMuted(const InstrumentTrackId& instrumentTrackId, bool savedMuted) const
1404 : {
1405 26 : IF_ASSERT_FAILED(notationPlayback() && notationConfiguration()) {
1406 0 : return savedMuted;
1407 : }
1408 :
1409 26 : if (instrumentTrackId == notationPlayback()->metronomeTrackId()) {
1410 0 : return !notationConfiguration()->isMetronomeEnabled() && !notationConfiguration()->isCountInEnabled();
1411 : }
1412 :
1413 26 : if (notationPlayback()->isChordSymbolsTrack(instrumentTrackId)) {
1414 0 : return !notationConfiguration()->isPlayChordSymbolsEnabled();
1415 : }
1416 :
1417 26 : return savedMuted;
1418 : }
1419 :
1420 26 : ControlParams PlaybackController::trackControlParams(const InstrumentTrackId& instrumentTrackId,
1421 : const AudioOutputParams& outParams,
1422 : bool rebuildVolume, bool rebuildPan)
1423 : {
1424 : // Fixed values always come from the mixer settings; only envelopes are cached
1425 26 : ControlParams control = outParams.control();
1426 :
1427 26 : const bool rebuild = rebuildVolume || rebuildPan;
1428 26 : const INotationAutomationPtr automation = m_masterNotation ? m_masterNotation->automation() : nullptr;
1429 26 : const AutomationDataConstPtr automationData = automation ? automation->automationData() : nullptr;
1430 :
1431 26 : if (rebuild && (!automationData || !instrumentTrackId.isValid())) {
1432 0 : m_automationEnvelopesCache.erase(instrumentTrackId);
1433 0 : return control;
1434 : }
1435 :
1436 26 : const auto it = rebuild ? m_automationEnvelopesCache.try_emplace(instrumentTrackId).first
1437 26 : : m_automationEnvelopesCache.find(instrumentTrackId);
1438 26 : if (it == m_automationEnvelopesCache.end()) {
1439 5 : return control;
1440 : }
1441 :
1442 21 : AutomationEnvelopes& envelopes = it->second;
1443 21 : if (rebuildVolume) {
1444 15 : envelopes.volume = buildAutomationEnvelope(AutomationCurveKey::instrument(AutomationType::Volume, instrumentTrackId));
1445 : }
1446 21 : if (rebuildPan) {
1447 10 : envelopes.pan = buildAutomationEnvelope(AutomationCurveKey::instrument(AutomationType::Pan, instrumentTrackId));
1448 : }
1449 :
1450 21 : if (!envelopes.volume && !envelopes.pan) {
1451 6 : m_automationEnvelopesCache.erase(it);
1452 6 : return control;
1453 : }
1454 :
1455 15 : applyEnvelopes(envelopes, control);
1456 15 : return control;
1457 26 : }
1458 :
1459 7 : void PlaybackController::onAutomationDataChanged(const AutomationChanges& changes)
1460 : {
1461 7 : if (changes.isFullReset) {
1462 0 : resendMasterControlParams();
1463 0 : resendTrackControlParams();
1464 0 : return;
1465 : }
1466 :
1467 7 : InstrumentTrackIdSet volumeTrackIds;
1468 7 : InstrumentTrackIdSet panTrackIds;
1469 7 : bool rebuildMasterVolume = false;
1470 7 : bool rebuildMasterPan = false;
1471 :
1472 : // Envelopes are in seconds, so a tempo change moves them even if the total length doesn't change
1473 7 : if (muse::contains(changes.affectedKeys, TEMPO_KEY)) {
1474 3 : rebuildMasterVolume = m_masterAutomationEnvelopes.volume.has_value();
1475 3 : rebuildMasterPan = m_masterAutomationEnvelopes.pan.has_value();
1476 3 : collectEnvelopeTrackIds(volumeTrackIds, panTrackIds);
1477 : }
1478 :
1479 15 : for (const AutomationCurveKey& key : changes.affectedKeys) {
1480 8 : switch (key.type) {
1481 5 : case AutomationType::Volume:
1482 5 : if (key.isGlobal()) {
1483 1 : rebuildMasterVolume = true;
1484 4 : } else if (const std::optional<InstrumentTrackId> trackId = key.trackId()) {
1485 4 : volumeTrackIds.insert(*trackId);
1486 4 : }
1487 5 : break;
1488 0 : case AutomationType::Pan:
1489 0 : if (key.isGlobal()) {
1490 0 : rebuildMasterPan = true;
1491 0 : } else if (const std::optional<InstrumentTrackId> trackId = key.trackId()) {
1492 0 : panTrackIds.insert(*trackId);
1493 0 : }
1494 0 : break;
1495 3 : default:
1496 3 : break;
1497 : }
1498 : }
1499 :
1500 7 : if (rebuildMasterVolume || rebuildMasterPan) {
1501 3 : resendMasterControlParams(rebuildMasterVolume, rebuildMasterPan);
1502 : }
1503 :
1504 7 : if (!volumeTrackIds.empty() || !panTrackIds.empty()) {
1505 5 : resendTrackControlParams(volumeTrackIds, panTrackIds);
1506 : }
1507 7 : }
1508 :
1509 10 : void PlaybackController::resendAutomationEnvelopes()
1510 : {
1511 10 : const bool masterVolume = m_masterAutomationEnvelopes.volume.has_value();
1512 10 : const bool masterPan = m_masterAutomationEnvelopes.pan.has_value();
1513 10 : if (masterVolume || masterPan) {
1514 0 : resendMasterControlParams(masterVolume, masterPan);
1515 : }
1516 :
1517 10 : InstrumentTrackIdSet volumeTrackIds;
1518 10 : InstrumentTrackIdSet panTrackIds;
1519 10 : collectEnvelopeTrackIds(volumeTrackIds, panTrackIds);
1520 :
1521 10 : if (volumeTrackIds.empty() && panTrackIds.empty()) {
1522 10 : return;
1523 : }
1524 :
1525 0 : resendTrackControlParams(volumeTrackIds, panTrackIds);
1526 20 : }
1527 :
1528 13 : void PlaybackController::collectEnvelopeTrackIds(InstrumentTrackIdSet& volumeTrackIds, InstrumentTrackIdSet& panTrackIds) const
1529 : {
1530 14 : for (const auto& [trackId, envelopes] : m_automationEnvelopesCache) {
1531 1 : if (envelopes.volume) {
1532 1 : volumeTrackIds.insert(trackId);
1533 : }
1534 1 : if (envelopes.pan) {
1535 0 : panTrackIds.insert(trackId);
1536 : }
1537 : }
1538 13 : }
1539 :
1540 5 : void PlaybackController::resendTrackControlParams(std::optional<InstrumentTrackIdSet> volumeTrackIds,
1541 : std::optional<InstrumentTrackIdSet> panTrackIds)
1542 : {
1543 5 : if (!playback()) {
1544 0 : return;
1545 : }
1546 :
1547 10 : for (const auto& pair : m_instrumentTrackIdMap) {
1548 5 : const bool rebuildVolume = !volumeTrackIds || muse::contains(*volumeTrackIds, pair.first);
1549 5 : const bool rebuildPan = !panTrackIds || muse::contains(*panTrackIds, pair.first);
1550 :
1551 5 : if (!rebuildVolume && !rebuildPan) {
1552 0 : continue;
1553 : }
1554 :
1555 5 : const AudioOutputParams outParams = trackOutputParams(pair.first);
1556 5 : playback()->setControlParams(pair.second, trackControlParams(pair.first, outParams, rebuildVolume, rebuildPan));
1557 5 : }
1558 : }
1559 :
1560 13 : void PlaybackController::resendMasterControlParams(bool rebuildVolume, bool rebuildPan)
1561 : {
1562 13 : if (!playback() || !audioSettings()) {
1563 0 : return;
1564 : }
1565 :
1566 13 : if (rebuildVolume) {
1567 13 : m_masterAutomationEnvelopes.volume = buildAutomationEnvelope(AutomationCurveKey::global(AutomationType::Volume));
1568 : }
1569 13 : if (rebuildPan) {
1570 10 : m_masterAutomationEnvelopes.pan = buildAutomationEnvelope(AutomationCurveKey::global(AutomationType::Pan));
1571 : }
1572 :
1573 13 : playback()->setMasterControlParams(currentMasterControlParams());
1574 : }
1575 :
1576 48 : std::optional<AutomationEnvelope> PlaybackController::buildAutomationEnvelope(const AutomationCurveKey& key) const
1577 : {
1578 48 : const INotationAutomationPtr automation = m_masterNotation ? m_masterNotation->automation() : nullptr;
1579 48 : const AutomationDataConstPtr automationData = automation ? automation->automationData() : nullptr;
1580 48 : if (!automationData) {
1581 0 : return std::nullopt;
1582 : }
1583 :
1584 48 : const AutomationCurve& curve = automationData->curve(key);
1585 48 : if (curve.empty()) {
1586 32 : return std::nullopt;
1587 : }
1588 :
1589 16 : AutomationEnvelope envelope;
1590 32 : for (const auto& [tick, point] : curve) {
1591 16 : envelope.insert({ playedTickToSecs(tick), point.value });
1592 : }
1593 :
1594 16 : return envelope;
1595 48 : }
1596 :
1597 28 : void PlaybackController::applyEnvelopes(const AutomationEnvelopes& envelopes, ControlParams& control)
1598 : {
1599 28 : if (envelopes.volume) {
1600 19 : control.volume = *envelopes.volume;
1601 : }
1602 28 : if (envelopes.pan) {
1603 5 : control.balance = *envelopes.pan;
1604 : }
1605 28 : }
1606 :
1607 0 : void PlaybackController::removeTrack(const InstrumentTrackId& instrumentTrackId)
1608 : {
1609 0 : IF_ASSERT_FAILED(notationPlayback() && playback()) {
1610 0 : return;
1611 : }
1612 :
1613 0 : auto search = m_instrumentTrackIdMap.find(instrumentTrackId);
1614 :
1615 0 : if (search == m_instrumentTrackIdMap.end()) {
1616 0 : return;
1617 : }
1618 :
1619 0 : playback()->removeTrack(search->second);
1620 0 : audioSettings()->removeTrackParams(instrumentTrackId);
1621 :
1622 0 : m_masterNotation->notation()->soloMuteState()->removeTrackSoloMuteState(instrumentTrackId);
1623 0 : for (const IExcerptNotationPtr& excerpt : m_masterNotation->excerpts()) {
1624 0 : if (const INotationPtr& notation = excerpt->notation()) {
1625 0 : notation->soloMuteState()->removeTrackSoloMuteState(instrumentTrackId);
1626 0 : }
1627 : }
1628 :
1629 0 : m_onlineSoundsController->removeOnlineTrack(search->second);
1630 :
1631 0 : m_trackRemoved.send(search->second);
1632 0 : m_instrumentTrackIdMap.erase(instrumentTrackId);
1633 0 : m_automationEnvelopesCache.erase(instrumentTrackId);
1634 : }
1635 :
1636 10 : void PlaybackController::onTrackNewlyAdded(const InstrumentTrackId& instrumentTrackId)
1637 : {
1638 10 : for (const IExcerptNotationPtr& excerpt : m_masterNotation->excerpts()) {
1639 0 : if (const INotationPtr& notation = excerpt->notation()) {
1640 0 : if (notation == m_notation || notation->soloMuteState()->trackSoloMuteStateExists(instrumentTrackId)) {
1641 0 : continue;
1642 : }
1643 :
1644 0 : const Part* part = notation->parts()->part(instrumentTrackId.partId);
1645 0 : const bool shouldMute = !part || !part->show();
1646 :
1647 0 : const INotationSoloMuteState::SoloMuteState soloMuteState = { shouldMute, /*solo*/ false };
1648 0 : notation->soloMuteState()->setTrackSoloMuteState(instrumentTrackId, soloMuteState);
1649 0 : }
1650 : }
1651 10 : }
1652 :
1653 17 : void PlaybackController::setupPlayback()
1654 : {
1655 17 : playback()->removeAllTracks();
1656 :
1657 17 : m_player = playback()->player();
1658 :
1659 17 : if (!notationPlayback()) {
1660 7 : return;
1661 : }
1662 :
1663 10 : const AudioOutputParams& masterOutputParams = audioSettings()->masterAudioOutputParams();
1664 10 : playback()->setMasterFxChainParams(masterOutputParams.fxChain);
1665 10 : playback()->setMasterAuxSendsParams(masterOutputParams.auxSends);
1666 10 : resendMasterControlParams();
1667 :
1668 10 : subscribeOnAudioParamsChanges();
1669 10 : setupTracks();
1670 10 : setupPlayer();
1671 :
1672 10 : m_isPlaybackInited = true;
1673 10 : m_playbackInited.send(m_isPlaybackInited);
1674 : }
1675 :
1676 10 : void PlaybackController::subscribeOnAudioParamsChanges()
1677 : {
1678 10 : playback()->masterControlParamsChanged().onReceive(this, [this](const ControlParams& params) {
1679 0 : AudioOutputParams outParams = audioSettings()->masterAudioOutputParams();
1680 0 : outParams.setControl(params);
1681 0 : audioSettings()->setMasterAudioOutputParams(outParams);
1682 0 : });
1683 :
1684 10 : playback()->masterFxChainParamsChanged().onReceive(this, [this](const AudioFxChain& params) {
1685 0 : AudioOutputParams outParams = audioSettings()->masterAudioOutputParams();
1686 0 : outParams.fxChain = params;
1687 0 : audioSettings()->setMasterAudioOutputParams(outParams);
1688 0 : });
1689 :
1690 10 : playback()->masterAuxSendsParamsChanged().onReceive(this, [this](const AuxSendsParams& params) {
1691 0 : AudioOutputParams outParams = audioSettings()->masterAudioOutputParams();
1692 0 : outParams.auxSends = params;
1693 0 : audioSettings()->setMasterAudioOutputParams(outParams);
1694 0 : });
1695 :
1696 10 : playback()->sourceParamsChanged().onReceive(this, [this](const TrackId trackId, const AudioInputParams& params) {
1697 0 : auto search = std::find_if(m_instrumentTrackIdMap.begin(), m_instrumentTrackIdMap.end(), [trackId](const auto& pair) {
1698 0 : return pair.second == trackId;
1699 : });
1700 :
1701 0 : if (search != m_instrumentTrackIdMap.end()) {
1702 0 : const AudioResourceMeta& oldMeta = audioSettings()->trackInputParams(search->first).resourceMeta;
1703 0 : onAudioResourceChanged(trackId, search->first, oldMeta, params.resourceMeta);
1704 :
1705 0 : audioSettings()->setTrackInputParams(search->first, params);
1706 : }
1707 0 : });
1708 :
1709 10 : playback()->fxChainParamsChanged().onReceive(this, [this](const TrackId trackId, const AudioFxChain& params) {
1710 0 : auto instrumentIt = std::find_if(m_instrumentTrackIdMap.begin(), m_instrumentTrackIdMap.end(), [trackId](const auto& pair) {
1711 0 : return pair.second == trackId;
1712 : });
1713 :
1714 0 : if (instrumentIt != m_instrumentTrackIdMap.end()) {
1715 0 : AudioOutputParams outParams = audioSettings()->trackOutputParams(instrumentIt->first);
1716 0 : outParams.fxChain = params;
1717 0 : audioSettings()->setTrackOutputParams(instrumentIt->first, outParams);
1718 0 : return;
1719 0 : }
1720 :
1721 0 : auto auxIt = std::find_if(m_auxTrackIdMap.begin(), m_auxTrackIdMap.end(), [trackId](const auto& pair) {
1722 0 : return pair.second == trackId;
1723 : });
1724 :
1725 0 : if (auxIt != m_auxTrackIdMap.end()) {
1726 0 : aux_channel_idx_t auxIdx = auxIt->first;
1727 0 : std::string oldName = resolveAuxTrackTitle(auxIdx, audioSettings()->auxOutputParams(auxIdx));
1728 0 : AudioOutputParams outParams = audioSettings()->auxOutputParams(auxIdx);
1729 0 : outParams.fxChain = params;
1730 0 : std::string newName = resolveAuxTrackTitle(auxIdx, outParams);
1731 :
1732 0 : audioSettings()->setAuxOutputParams(auxIdx, outParams);
1733 :
1734 0 : if (oldName != newName) {
1735 0 : m_auxChannelNameChanged.send(auxIdx, newName);
1736 : }
1737 0 : }
1738 : });
1739 :
1740 10 : playback()->controlParamsChanged().onReceive(this, [this](const TrackId trackId, const ControlParams& params) {
1741 0 : auto instrumentIt = std::find_if(m_instrumentTrackIdMap.begin(), m_instrumentTrackIdMap.end(), [trackId](const auto& pair) {
1742 0 : return pair.second == trackId;
1743 : });
1744 :
1745 0 : if (instrumentIt != m_instrumentTrackIdMap.end()) {
1746 0 : AudioOutputParams outParams = audioSettings()->trackOutputParams(instrumentIt->first);
1747 0 : outParams.setControl(params);
1748 0 : audioSettings()->setTrackOutputParams(instrumentIt->first, outParams);
1749 0 : return;
1750 0 : }
1751 :
1752 0 : auto auxIt = std::find_if(m_auxTrackIdMap.begin(), m_auxTrackIdMap.end(), [trackId](const auto& pair) {
1753 0 : return pair.second == trackId;
1754 : });
1755 :
1756 0 : if (auxIt != m_auxTrackIdMap.end()) {
1757 0 : aux_channel_idx_t auxIdx = auxIt->first;
1758 0 : AudioOutputParams outParams = audioSettings()->auxOutputParams(auxIdx);
1759 0 : outParams.setControl(params);
1760 0 : audioSettings()->setAuxOutputParams(auxIdx, outParams);
1761 0 : }
1762 : });
1763 :
1764 10 : playback()->auxSendsParamsChanged().onReceive(this, [this](const TrackId trackId, const AuxSendsParams& params) {
1765 0 : auto instrumentIt = std::find_if(m_instrumentTrackIdMap.begin(), m_instrumentTrackIdMap.end(), [trackId](const auto& pair) {
1766 0 : return pair.second == trackId;
1767 : });
1768 :
1769 0 : if (instrumentIt != m_instrumentTrackIdMap.end()) {
1770 0 : AudioOutputParams outParams = audioSettings()->trackOutputParams(instrumentIt->first);
1771 0 : outParams.auxSends = params;
1772 0 : audioSettings()->setTrackOutputParams(instrumentIt->first, outParams);
1773 0 : return;
1774 0 : }
1775 :
1776 0 : auto auxIt = std::find_if(m_auxTrackIdMap.begin(), m_auxTrackIdMap.end(), [trackId](const auto& pair) {
1777 0 : return pair.second == trackId;
1778 : });
1779 :
1780 0 : if (auxIt != m_auxTrackIdMap.end()) {
1781 0 : aux_channel_idx_t auxIdx = auxIt->first;
1782 0 : AudioOutputParams outParams = audioSettings()->auxOutputParams(auxIdx);
1783 0 : outParams.auxSends = params;
1784 0 : audioSettings()->setAuxOutputParams(auxIdx, outParams);
1785 0 : }
1786 : });
1787 10 : }
1788 :
1789 10 : void PlaybackController::setupTracks()
1790 : {
1791 10 : m_instrumentTrackIdMap.clear();
1792 :
1793 10 : if (!masterNotationParts()) {
1794 0 : return;
1795 : }
1796 :
1797 10 : const bool projectHadNoAudioSettings = !audioSettings()->hasAnyAudioSettings();
1798 :
1799 10 : m_loadingTrackCount = 0;
1800 :
1801 10 : InstrumentTrackIdSet trackIdSet = notationPlayback()->existingTrackIdSet();
1802 10 : size_t trackCount = trackIdSet.size() + AUX_CHANNEL_NUM;
1803 10 : std::string title = muse::trc("playback", "Loading audio samples");
1804 :
1805 30 : auto onAddFinished = [this, trackCount, title]() {
1806 30 : m_loadingTrackCount--;
1807 :
1808 30 : size_t current = trackCount - m_loadingTrackCount;
1809 30 : m_loadingProgress.progress(current, trackCount, title);
1810 :
1811 30 : if (m_loadingTrackCount == 0) {
1812 10 : m_loadingProgress.finish(muse::make_ok());
1813 10 : m_isPlayAllowedChanged.send(isPlayAllowed());
1814 : }
1815 40 : };
1816 :
1817 20 : for (const InstrumentTrackId& trackId : trackIdSet) {
1818 10 : addTrack(trackId, projectHadNoAudioSettings, onAddFinished);
1819 : }
1820 :
1821 30 : for (aux_channel_idx_t idx = 0; idx < AUX_CHANNEL_NUM; ++idx) {
1822 20 : addAuxTrack(idx, projectHadNoAudioSettings, onAddFinished);
1823 : }
1824 :
1825 10 : m_loadingProgress.progress(0, trackCount, title);
1826 :
1827 10 : notationPlayback()->trackAdded().onReceive(this, [this, onAddFinished](const InstrumentTrackId& instrumentTrackId) {
1828 0 : addTrack(instrumentTrackId, false /*projectHadNoAudioSettings*/, onAddFinished);
1829 0 : });
1830 :
1831 10 : notationPlayback()->trackRemoved().onReceive(this, [this](const InstrumentTrackId& instrumentTrackId) {
1832 0 : removeTrack(instrumentTrackId);
1833 0 : });
1834 :
1835 10 : NotifyList<const Part*> partList = masterNotationParts()->partList();
1836 :
1837 : //! HACK - ideally we would use "this" (PlaybackController) instead of m_seqAsyncReceiver for the following
1838 : //! subscription, but we've already subscribed to onItemChanged for a different reason in setNotation...
1839 10 : partList.onItemChanged(&m_seqAsyncReceiver, [this](const Part*) {
1840 0 : updateSoloMuteStates();
1841 0 : });
1842 :
1843 10 : audioSettings()->auxSoloMuteStateChanged().onReceive(
1844 0 : this, [this](aux_channel_idx_t, const notation::INotationSoloMuteState::SoloMuteState&) {
1845 0 : updateSoloMuteStates();
1846 0 : });
1847 :
1848 10 : m_isPlayAllowedChanged.send(isPlayAllowed());
1849 10 : }
1850 :
1851 10 : void PlaybackController::setupPlayer()
1852 : {
1853 10 : currentPlayer()->playbackPositionChanged().onReceive(this, [this](const audio::secs_t pos) {
1854 0 : m_playbackPositionChanged.send(pos);
1855 :
1856 0 : m_currentTick = notationPlayback()->secToTick(pos);
1857 :
1858 0 : updateCurrentTempo();
1859 :
1860 0 : secs_t endSecs = totalPlayTime();
1861 0 : if (pos + muse::msecs_to_secs(1) >= endSecs) {
1862 0 : doStop();
1863 : }
1864 0 : });
1865 :
1866 10 : currentPlayer()->playbackStatusChanged().onReceive(this, [this](PlaybackStatus) {
1867 0 : onPlaybackStatusChanged();
1868 0 : });
1869 :
1870 10 : currentPlayer()->setDuration(notationPlayback()->totalPlayTime());
1871 :
1872 10 : notationPlayback()->totalPlayTimeChanged().onReceive(this, [this](const audio::secs_t totalPlaybackTime) {
1873 0 : currentPlayer()->setDuration(totalPlaybackTime);
1874 0 : m_totalPlayTimeChanged.notify();
1875 0 : });
1876 10 : }
1877 :
1878 21 : void PlaybackController::updateSoloMuteStates()
1879 : {
1880 21 : if (!audioSettings() || !playback() || !m_notation) {
1881 0 : return;
1882 : }
1883 :
1884 22 : TRACEFUNC;
1885 :
1886 21 : InstrumentTrackIdSet existingTrackIdSet = notationPlayback()->existingTrackIdSet();
1887 21 : bool hasSolo = false;
1888 :
1889 42 : for (const InstrumentTrackId& instrumentTrackId : existingTrackIdSet) {
1890 21 : if (instrumentTrackId == notationPlayback()->metronomeTrackId()) {
1891 0 : continue;
1892 : }
1893 21 : if (m_notation->soloMuteState()->trackSoloMuteState(instrumentTrackId).solo) {
1894 0 : hasSolo = true;
1895 0 : break;
1896 : }
1897 : }
1898 :
1899 21 : InstrumentTrackIdSet allowedInstrumentTrackIdSet = instrumentTrackIdSetForRangePlayback();
1900 21 : bool isRangePlaybackMode = !m_isExportingAudio && selection()->isRange() && !allowedInstrumentTrackIdSet.empty();
1901 :
1902 42 : for (const InstrumentTrackId& instrumentTrackId : existingTrackIdSet) {
1903 21 : if (!muse::contains(m_instrumentTrackIdMap, instrumentTrackId)) {
1904 10 : continue;
1905 : }
1906 :
1907 11 : if (instrumentTrackId == notationPlayback()->metronomeTrackId()) {
1908 0 : continue;
1909 : }
1910 :
1911 : // 1. Recall the solo-mute state for this notation
1912 11 : const auto& soloMuteState = m_notation->soloMuteState()->trackSoloMuteState(instrumentTrackId);
1913 :
1914 : // 2. Evaluate "force mute" (disabling the mute button)
1915 11 : bool shouldForceMute = hasSolo && !soloMuteState.solo;
1916 11 : if (notationPlayback()->isChordSymbolsTrack(instrumentTrackId) && !shouldForceMute) {
1917 0 : shouldForceMute = !notationConfiguration()->isPlayChordSymbolsEnabled();
1918 : }
1919 :
1920 11 : if (isRangePlaybackMode && !shouldForceMute) {
1921 0 : shouldForceMute = !muse::contains(allowedInstrumentTrackIdSet, instrumentTrackId);
1922 : }
1923 :
1924 : // 3. Update params for playback / mixer
1925 11 : AudioOutputParams params = trackOutputParams(instrumentTrackId);
1926 11 : params.solo = soloMuteState.solo;
1927 11 : params.muted = soloMuteState.mute || shouldForceMute;
1928 11 : params.forceMute = shouldForceMute;
1929 :
1930 11 : audio::TrackId trackId = m_instrumentTrackIdMap.at(instrumentTrackId);
1931 11 : playback()->setControlParams(trackId, trackControlParams(instrumentTrackId, params, /*rebuildVolume*/ false, /*rebuildPan*/ false));
1932 11 : }
1933 :
1934 21 : updateAuxMuteStates();
1935 21 : }
1936 :
1937 21 : void PlaybackController::updateAuxMuteStates()
1938 : {
1939 21 : for (const auto& pair : m_auxTrackIdMap) {
1940 0 : auto soloMuteState = audioSettings()->auxSoloMuteState(pair.first);
1941 :
1942 0 : AudioOutputParams params = audioSettings()->auxOutputParams(pair.first);
1943 0 : if (params.muted == soloMuteState.mute) {
1944 0 : continue;
1945 : }
1946 :
1947 0 : params.muted = soloMuteState.mute;
1948 0 : playback()->setControlParams(pair.second, params.control());
1949 0 : }
1950 21 : }
1951 :
1952 0 : secs_t PlaybackController::totalPlayTime() const
1953 : {
1954 0 : auto np = notationPlayback();
1955 0 : return np ? np->totalPlayTime() : secs_t { 0.0 };
1956 0 : }
1957 :
1958 0 : Notification PlaybackController::totalPlayTimeChanged() const
1959 : {
1960 0 : return m_totalPlayTimeChanged;
1961 : }
1962 :
1963 0 : const Tempo& PlaybackController::currentTempo() const
1964 : {
1965 0 : return m_currentTempo;
1966 : }
1967 :
1968 0 : Notification PlaybackController::currentTempoChanged() const
1969 : {
1970 0 : return m_currentTempoChanged;
1971 : }
1972 :
1973 0 : MeasureBeat PlaybackController::currentBeat() const
1974 : {
1975 0 : return notationPlayback() ? notationPlayback()->beat(m_currentTick) : MeasureBeat();
1976 : }
1977 :
1978 0 : secs_t PlaybackController::beatToSecs(int measureIndex, int beatIndex) const
1979 : {
1980 0 : if (!notationPlayback()) {
1981 0 : return 0;
1982 : }
1983 :
1984 0 : muse::midi::tick_t rawTick = notationPlayback()->beatToRawTick(measureIndex, beatIndex);
1985 0 : muse::midi::tick_t playedTick = notationPlayback()->playPositionTickByRawTick(rawTick).val;
1986 :
1987 0 : return playedTickToSecs(playedTick);
1988 : }
1989 :
1990 0 : double PlaybackController::tempoMultiplier() const
1991 : {
1992 0 : return notationPlayback() ? notationPlayback()->tempoMultiplier() : 1.0;
1993 : }
1994 :
1995 0 : void PlaybackController::setTempoMultiplier(double multiplier)
1996 : {
1997 0 : if (!notationPlayback()) {
1998 0 : return;
1999 : }
2000 :
2001 0 : tick_t tick = m_currentTick;
2002 0 : bool playing = isPlaying();
2003 :
2004 0 : if (playing) {
2005 0 : doPause();
2006 : }
2007 :
2008 0 : notationPlayback()->setTempoMultiplier(multiplier);
2009 0 : seekRawTick(tick);
2010 0 : updateLoop();
2011 :
2012 0 : if (playing) {
2013 0 : doResume();
2014 : }
2015 : }
2016 :
2017 0 : muse::Progress PlaybackController::loadingProgress() const
2018 : {
2019 0 : return m_loadingProgress;
2020 : }
2021 :
2022 0 : void PlaybackController::applyProfile(const SoundProfileName& profileName)
2023 : {
2024 0 : project::IProjectAudioSettingsPtr audioSettingsPtr = audioSettings();
2025 :
2026 0 : IF_ASSERT_FAILED(audioSettingsPtr) {
2027 0 : return;
2028 : }
2029 :
2030 0 : const SoundProfile& profile = profilesRepo()->profile(profileName);
2031 0 : if (!profile.isValid()) {
2032 0 : return;
2033 : }
2034 :
2035 0 : notationPlayback()->removeSoundFlags(notationPlayback()->existingTrackIdSet());
2036 :
2037 0 : const InstrumentTrackId& metronomeTrackId = notationPlayback()->metronomeTrackId();
2038 :
2039 0 : for (const auto& pair : m_instrumentTrackIdMap) {
2040 0 : if (pair.first == metronomeTrackId) {
2041 0 : continue;
2042 : }
2043 :
2044 0 : const mpe::PlaybackData& playbackData = notationPlayback()->trackPlaybackData(pair.first);
2045 0 : AudioSourceParams newSourceParams { profile.findResource(playbackData.setupData), {} };
2046 :
2047 0 : playback()->setSourceParams(pair.second, newSourceParams);
2048 0 : }
2049 :
2050 0 : audioSettingsPtr->setActiveSoundProfile(profileName);
2051 0 : }
2052 :
2053 22 : void PlaybackController::setNotation(notation::INotationPtr notation)
2054 : {
2055 22 : if (m_notation == notation) {
2056 12 : return;
2057 : }
2058 :
2059 10 : if (m_notation) {
2060 0 : INotationPartsPtr notationParts = m_notation->parts();
2061 0 : NotifyList<const Part*> partList = notationParts->partList();
2062 0 : partList.disconnect(this);
2063 :
2064 0 : m_notation->interaction()->selectionChanged().disconnect(this);
2065 0 : m_notation->interaction()->textEditingEnded().disconnect(this);
2066 0 : m_notation->soloMuteState()->trackSoloMuteStateChanged().disconnect(this);
2067 0 : }
2068 :
2069 10 : m_notation = notation;
2070 :
2071 10 : m_isPlayAllowedChanged.send(isPlayAllowed());
2072 :
2073 10 : if (!m_notation) {
2074 0 : setMasterNotation(nullptr);
2075 0 : return;
2076 : }
2077 :
2078 10 : setMasterNotation(m_notation->masterNotation());
2079 :
2080 10 : if (!m_notation->hasVisibleParts()) {
2081 0 : doPause();
2082 : }
2083 :
2084 10 : updateSoloMuteStates();
2085 :
2086 10 : NotifyList<const Part*> partList = m_notation->parts()->partList();
2087 :
2088 10 : partList.onItemAdded(this, [this](const Part* part) {
2089 0 : onPartChanged(part);
2090 0 : });
2091 :
2092 10 : partList.onItemChanged(this, [this](const Part* part) {
2093 0 : onPartChanged(part);
2094 0 : });
2095 :
2096 10 : m_notation->interaction()->selectionChanged().onNotify(this, [this]() {
2097 0 : onSelectionChanged();
2098 0 : });
2099 :
2100 10 : m_notation->interaction()->textEditingEnded().onReceive(this, [this](engraving::TextBase* text) {
2101 0 : if (text && text->isHarmony()) {
2102 0 : playElements({ text });
2103 : }
2104 0 : });
2105 :
2106 10 : m_notation->soloMuteState()->trackSoloMuteStateChanged().onReceive(
2107 1 : this, [this](const InstrumentTrackId&, const notation::INotationSoloMuteState::SoloMuteState&) {
2108 1 : updateSoloMuteStates();
2109 1 : });
2110 10 : }
2111 :
2112 10 : void PlaybackController::setMasterNotation(notation::IMasterNotationPtr masterNotation)
2113 : {
2114 10 : if (m_masterNotation == masterNotation) {
2115 0 : return;
2116 : }
2117 :
2118 10 : if (m_masterNotation) {
2119 0 : m_masterNotation->hasPartsChanged().disconnect(this);
2120 0 : m_masterNotation->playback()->loopBoundariesChanged().disconnect(this);
2121 0 : m_masterNotation->playback()->loopEnabledChanged().disconnect(this);
2122 :
2123 0 : if (const AutomationDataConstPtr automationData = m_masterNotation->automation()->automationData()) {
2124 0 : automationData->changed().disconnect(this);
2125 0 : }
2126 : }
2127 :
2128 10 : m_masterNotation = masterNotation;
2129 :
2130 10 : m_totalPlayTimeChanged.notify();
2131 :
2132 10 : if (!m_masterNotation) {
2133 0 : return;
2134 : }
2135 :
2136 10 : m_masterNotation->hasPartsChanged().onNotify(this, [this]() {
2137 0 : m_isPlayAllowedChanged.send(isPlayAllowed());
2138 0 : });
2139 :
2140 10 : m_masterNotation->playback()->loopBoundariesChanged().onNotify(this, [this]() {
2141 0 : updateLoop();
2142 0 : });
2143 :
2144 10 : m_masterNotation->playback()->loopEnabledChanged().onReceive(this, [this](bool value) {
2145 0 : m_loopEnabledChanged.send(value);
2146 0 : });
2147 :
2148 10 : if (const AutomationDataConstPtr automationData = m_masterNotation->automation()->automationData()) {
2149 10 : automationData->changed().onReceive(this, [this](const AutomationChanges& changes) {
2150 7 : onAutomationDataChanged(changes);
2151 7 : });
2152 10 : }
2153 : }
2154 :
2155 0 : void PlaybackController::setIsExportingAudio(bool exporting)
2156 : {
2157 0 : if (m_isExportingAudio == exporting) {
2158 0 : return;
2159 : }
2160 :
2161 0 : m_isExportingAudio = exporting;
2162 0 : updateSoloMuteStates();
2163 :
2164 0 : if (exporting && notationPlayback()) {
2165 0 : notationPlayback()->sendEventsForChangedTracks();
2166 : }
2167 : }
2168 :
2169 0 : const std::map<TrackId, AudioResourceMeta>& PlaybackController::onlineSounds() const
2170 : {
2171 0 : return m_onlineSoundsController->onlineSounds();
2172 : }
2173 :
2174 0 : muse::async::Notification PlaybackController::onlineSoundsChanged() const
2175 : {
2176 0 : return m_onlineSoundsController->onlineSoundsChanged();
2177 : }
2178 :
2179 0 : muse::Progress PlaybackController::onlineSoundsProcessingProgress() const
2180 : {
2181 0 : return m_onlineSoundsController->onlineSoundsProcessingProgress();
2182 : }
2183 :
2184 16 : muse::audio::secs_t PlaybackController::playedTickToSecs(int tick) const
2185 : {
2186 16 : return secs_t(notationPlayback()->playedTickToSec(tick));
2187 : }
|