aboutsummaryrefslogtreecommitdiffstats
path: root/al/event.cpp
blob: 6c004ef3b8ea778d58b38a26c69d8c8bd1b73d72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210

#include "config.h"

#include "event.h"

#include <algorithm>
#include <atomic>
#include <cstring>
#include <exception>
#include <memory>
#include <mutex>
#include <new>
#include <string>
#include <thread>
#include <utility>

#include "AL/al.h"
#include "AL/alc.h"

#include "albyte.h"
#include "alcontext.h"
#include "alexcpt.h"
#include "almalloc.h"
#include "effects/base.h"
#include "inprogext.h"
#include "logging.h"
#include "opthelpers.h"
#include "ringbuffer.h"
#include "threads.h"


static int EventThread(ALCcontext *context)
{
    RingBuffer *ring{context->mAsyncEvents.get()};
    bool quitnow{false};
    while LIKELY(!quitnow)
    {
        auto evt_data = ring->getReadVector().first;
        if(evt_data.len == 0)
        {
            context->mEventSem.wait();
            continue;
        }

        std::lock_guard<std::mutex> _{context->mEventCbLock};
        do {
            auto *evt_ptr = reinterpret_cast<AsyncEvent*>(evt_data.buf);
            evt_data.buf += sizeof(AsyncEvent);
            evt_data.len -= 1;

            AsyncEvent evt{*evt_ptr};
            al::destroy_at(evt_ptr);
            ring->readAdvance(1);

            quitnow = evt.EnumType == EventType_KillThread;
            if UNLIKELY(quitnow) break;

            if(evt.EnumType == EventType_ReleaseEffectState)
            {
                evt.u.mEffectState->release();
                continue;
            }
            if(evt.EnumType == EventType_ReleaseEffectBuffer)
            {
                evt.u.mEffectBuffer->release();
                continue;
            }

            ALbitfieldSOFT enabledevts{context->mEnabledEvts.load(std::memory_order_acquire)};
            if(!context->mEventCb) continue;

            if(evt.EnumType == EventType_SourceStateChange)
            {
                if(!(enabledevts&EventType_SourceStateChange))
                    continue;
                std::string msg{"Source ID " + std::to_string(evt.u.srcstate.id)};
                msg += " state has changed to ";
                msg += (evt.u.srcstate.state==AL_INITIAL) ? "AL_INITIAL" :
                    (evt.u.srcstate.state==AL_PLAYING) ? "AL_PLAYING" :
                    (evt.u.srcstate.state==AL_PAUSED) ? "AL_PAUSED" :
                    (evt.u.srcstate.state==AL_STOPPED) ? "AL_STOPPED" : "<unknown>";
                context->mEventCb(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT, evt.u.srcstate.id,
                    static_cast<ALuint>(evt.u.srcstate.state), static_cast<ALsizei>(msg.length()),
                    msg.c_str(), context->mEventParam);
            }
            else if(evt.EnumType == EventType_BufferCompleted)
            {
                if(!(enabledevts&EventType_BufferCompleted))
                    continue;
                std::string msg{std::to_string(evt.u.bufcomp.count)};
                if(evt.u.bufcomp.count == 1) msg += " buffer completed";
                else msg += " buffers completed";
                context->mEventCb(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT, evt.u.bufcomp.id,
                    evt.u.bufcomp.count, static_cast<ALsizei>(msg.length()), msg.c_str(),
                    context->mEventParam);
            }
            else if((enabledevts&evt.EnumType) == evt.EnumType)
                context->mEventCb(evt.u.user.type, evt.u.user.id, evt.u.user.param,
                    static_cast<ALsizei>(strlen(evt.u.user.msg)), evt.u.user.msg,
                    context->mEventParam);
        } while(evt_data.len != 0);
    }
    return 0;
}

void StartEventThrd(ALCcontext *ctx)
{
    try {
        ctx->mEventThread = std::thread{EventThread, ctx};
    }
    catch(std::exception& e) {
        ERR("Failed to start event thread: %s\n", e.what());
    }
    catch(...) {
        ERR("Failed to start event thread! Expect problems.\n");
    }
}

void StopEventThrd(ALCcontext *ctx)
{
    RingBuffer *ring{ctx->mAsyncEvents.get()};
    auto evt_data = ring->getWriteVector().first;
    if(evt_data.len == 0)
    {
        do {
            std::this_thread::yield();
            evt_data = ring->getWriteVector().first;
        } while(evt_data.len == 0);
    }
    ::new(evt_data.buf) AsyncEvent{EventType_KillThread};
    ring->writeAdvance(1);

    ctx->mEventSem.post();
    if(ctx->mEventThread.joinable())
        ctx->mEventThread.join();
}

AL_API void AL_APIENTRY alEventControlSOFT(ALsizei count, const ALenum *types, ALboolean enable)
START_API_FUNC
{
    ContextRef context{GetContextRef()};
    if UNLIKELY(!context) return;

    if(count < 0) context->setError(AL_INVALID_VALUE, "Controlling %d events", count);
    if(count <= 0) return;
    if(!types) SETERR_RETURN(context, AL_INVALID_VALUE,, "NULL pointer");

    ALbitfieldSOFT flags{0};
    const ALenum *types_end = types+count;
    auto bad_type = std::find_if_not(types, types_end,
        [&flags](ALenum type) noexcept -> bool
        {
            if(type == AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT)
                flags |= EventType_BufferCompleted;
            else if(type == AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT)
                flags |= EventType_SourceStateChange;
            else if(type == AL_EVENT_TYPE_ERROR_SOFT)
                flags |= EventType_Error;
            else if(type == AL_EVENT_TYPE_PERFORMANCE_SOFT)
                flags |= EventType_Performance;
            else if(type == AL_EVENT_TYPE_DEPRECATED_SOFT)
                flags |= EventType_Deprecated;
            else if(type == AL_EVENT_TYPE_DISCONNECTED_SOFT)
                flags |= EventType_Disconnected;
            else
                return false;
            return true;
        }
    );
    if(bad_type != types_end)
        SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid event type 0x%04x", *bad_type);

    if(enable)
    {
        ALbitfieldSOFT enabledevts{context->mEnabledEvts.load(std::memory_order_relaxed)};
        while(context->mEnabledEvts.compare_exchange_weak(enabledevts, enabledevts|flags,
            std::memory_order_acq_rel, std::memory_order_acquire) == 0)
        {
            /* enabledevts is (re-)filled with the current value on failure, so
             * just try again.
             */
        }
    }
    else
    {
        ALbitfieldSOFT enabledevts{context->mEnabledEvts.load(std::memory_order_relaxed)};
        while(context->mEnabledEvts.compare_exchange_weak(enabledevts, enabledevts&~flags,
            std::memory_order_acq_rel, std::memory_order_acquire) == 0)
        {
        }
        /* Wait to ensure the event handler sees the changed flags before
         * returning.
         */
        std::lock_guard<std::mutex>{context->mEventCbLock};
    }
}
END_API_FUNC

AL_API void AL_APIENTRY alEventCallbackSOFT(ALEVENTPROCSOFT callback, void *userParam)
START_API_FUNC
{
    ContextRef context{GetContextRef()};
    if UNLIKELY(!context) return;

    std::lock_guard<std::mutex> _{context->mPropLock};
    std::lock_guard<std::mutex> __{context->mEventCbLock};
    context->mEventCb = callback;
    context->mEventParam = userParam;
}
END_API_FUNC