summaryrefslogtreecommitdiffstats
path: root/src/audio_core/audio_manager.cpp
blob: e23af0ef5bd65d702bf9487bb6d8a84cd0aff97a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "audio_core/audio_manager.h"
#include "core/core.h"

namespace AudioCore {

AudioManager::AudioManager() {
    thread = std::jthread([this]() { ThreadFunc(); });
}

void AudioManager::Shutdown() {
    running = false;
    events.SetAudioEvent(Event::Type::Max, true);
    thread.join();
}

Result AudioManager::SetOutManager(BufferEventFunc buffer_func) {
    if (!running) {
        return Service::Audio::ERR_OPERATION_FAILED;
    }

    std::scoped_lock l{lock};

    const auto index{events.GetManagerIndex(Event::Type::AudioOutManager)};
    if (buffer_events[index] == nullptr) {
        buffer_events[index] = std::move(buffer_func);
        needs_update = true;
        events.SetAudioEvent(Event::Type::AudioOutManager, true);
    }
    return ResultSuccess;
}

Result AudioManager::SetInManager(BufferEventFunc buffer_func) {
    if (!running) {
        return Service::Audio::ERR_OPERATION_FAILED;
    }

    std::scoped_lock l{lock};

    const auto index{events.GetManagerIndex(Event::Type::AudioInManager)};
    if (buffer_events[index] == nullptr) {
        buffer_events[index] = std::move(buffer_func);
        needs_update = true;
        events.SetAudioEvent(Event::Type::AudioInManager, true);
    }
    return ResultSuccess;
}

void AudioManager::SetEvent(const Event::Type type, const bool signalled) {
    events.SetAudioEvent(type, signalled);
}

void AudioManager::ThreadFunc() {
    std::unique_lock l{events.GetAudioEventLock()};
    events.ClearEvents();
    running = true;

    while (running) {
        const auto timed_out{events.Wait(l, std::chrono::seconds(2))};

        if (events.CheckAudioEventSet(Event::Type::Max)) {
            break;
        }

        for (size_t i = 0; i < buffer_events.size(); i++) {
            const auto event_type = static_cast<Event::Type>(i);

            if (events.CheckAudioEventSet(event_type) || timed_out) {
                if (buffer_events[i]) {
                    buffer_events[i]();
                }
            }
            events.SetAudioEvent(event_type, false);
        }
    }
}

} // namespace AudioCore