aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Audio/Input/AudioInputManager.cs
blob: 4d1796c965521a8b460140b0fd885198e80e7dee (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
using Ryujinx.Audio.Common;
using Ryujinx.Audio.Integration;
using Ryujinx.Common.Logging;
using Ryujinx.Memory;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;

namespace Ryujinx.Audio.Input
{
    /// <summary>
    /// The audio input manager.
    /// </summary>
    public class AudioInputManager : IDisposable
    {
        private readonly object _lock = new();

        /// <summary>
        /// Lock used for session allocation.
        /// </summary>
        private readonly object _sessionLock = new();

        /// <summary>
        /// The session ids allocation table.
        /// </summary>
        private readonly int[] _sessionIds;

        /// <summary>
        /// The device driver.
        /// </summary>
        private IHardwareDeviceDriver _deviceDriver;

        /// <summary>
        /// The events linked to each session.
        /// </summary>
        private IWritableEvent[] _sessionsBufferEvents;

        /// <summary>
        /// The <see cref="AudioInputSystem"/> session instances.
        /// </summary>
        private readonly AudioInputSystem[] _sessions;

        /// <summary>
        /// The count of active sessions.
        /// </summary>
        private int _activeSessionCount;

        /// <summary>
        /// The dispose state.
        /// </summary>
        private int _disposeState;

        /// <summary>
        /// Create a new <see cref="AudioInputManager"/>.
        /// </summary>
        public AudioInputManager()
        {
            _sessionIds = new int[Constants.AudioInSessionCountMax];
            _sessions = new AudioInputSystem[Constants.AudioInSessionCountMax];
            _activeSessionCount = 0;

            for (int i = 0; i < _sessionIds.Length; i++)
            {
                _sessionIds[i] = i;
            }
        }

        /// <summary>
        /// Initialize the <see cref="AudioInputManager"/>.
        /// </summary>
        /// <param name="deviceDriver">The device driver.</param>
        /// <param name="sessionRegisterEvents">The events associated to each session.</param>
        public void Initialize(IHardwareDeviceDriver deviceDriver, IWritableEvent[] sessionRegisterEvents)
        {
            _deviceDriver = deviceDriver;
            _sessionsBufferEvents = sessionRegisterEvents;
        }

        /// <summary>
        /// Acquire a new session id.
        /// </summary>
        /// <returns>A new session id.</returns>
        private int AcquireSessionId()
        {
            lock (_sessionLock)
            {
                int index = _activeSessionCount;

                Debug.Assert(index < _sessionIds.Length);

                int sessionId = _sessionIds[index];

                _sessionIds[index] = -1;

                _activeSessionCount++;

                Logger.Info?.Print(LogClass.AudioRenderer, $"Registered new input ({sessionId})");

                return sessionId;
            }
        }

        /// <summary>
        /// Release a given <paramref name="sessionId"/>.
        /// </summary>
        /// <param name="sessionId">The session id to release.</param>
        private void ReleaseSessionId(int sessionId)
        {
            lock (_sessionLock)
            {
                Debug.Assert(_activeSessionCount > 0);

                int newIndex = --_activeSessionCount;

                _sessionIds[newIndex] = sessionId;
            }

            Logger.Info?.Print(LogClass.AudioRenderer, $"Unregistered input ({sessionId})");
        }

        /// <summary>
        /// Used to update audio input system.
        /// </summary>
        public void Update()
        {
            lock (_sessionLock)
            {
                foreach (AudioInputSystem input in _sessions)
                {
                    input?.Update();
                }
            }
        }

        /// <summary>
        /// Register a new <see cref="AudioInputSystem"/>.
        /// </summary>
        /// <param name="input">The <see cref="AudioInputSystem"/> to register.</param>
        private void Register(AudioInputSystem input)
        {
            lock (_sessionLock)
            {
                _sessions[input.GetSessionId()] = input;
            }
        }

        /// <summary>
        /// Unregister a new <see cref="AudioInputSystem"/>.
        /// </summary>
        /// <param name="input">The <see cref="AudioInputSystem"/> to unregister.</param>
        internal void Unregister(AudioInputSystem input)
        {
            lock (_sessionLock)
            {
                int sessionId = input.GetSessionId();

                _sessions[input.GetSessionId()] = null;

                ReleaseSessionId(sessionId);
            }
        }

        /// <summary>
        /// Get the list of all audio inputs names.
        /// </summary>
        /// <param name="filtered">If true, filter disconnected devices</param>
        /// <returns>The list of all audio inputs name</returns>
#pragma warning disable CA1822 // Mark member as static
        public string[] ListAudioIns(bool filtered)
        {
            if (filtered)
            {
                // TODO: Detect if the driver supports audio input
            }

            return new[] { Constants.DefaultDeviceInputName };
        }
#pragma warning restore CA1822

        /// <summary>
        /// Open a new <see cref="AudioInputSystem"/>.
        /// </summary>
        /// <param name="outputDeviceName">The output device name selected by the <see cref="AudioInputSystem"/></param>
        /// <param name="outputConfiguration">The output audio configuration selected by the <see cref="AudioInputSystem"/></param>
        /// <param name="obj">The new <see cref="AudioInputSystem"/></param>
        /// <param name="memoryManager">The memory manager that will be used for all guest memory operations</param>
        /// <param name="inputDeviceName">The input device name wanted by the user</param>
        /// <param name="sampleFormat">The sample format to use</param>
        /// <param name="parameter">The user configuration</param>
        /// <param name="appletResourceUserId">The applet resource user id of the application</param>
        /// <param name="processHandle">The process handle of the application</param>
        /// <returns>A <see cref="ResultCode"/> reporting an error or a success</returns>
        public ResultCode OpenAudioIn(out string outputDeviceName,
                                      out AudioOutputConfiguration outputConfiguration,
                                      out AudioInputSystem obj,
                                      IVirtualMemoryManager memoryManager,
                                      string inputDeviceName,
                                      SampleFormat sampleFormat,
                                      ref AudioInputConfiguration parameter,
                                      ulong appletResourceUserId,
                                      uint processHandle)
        {
            int sessionId = AcquireSessionId();

            _sessionsBufferEvents[sessionId].Clear();

            IHardwareDeviceSession deviceSession = _deviceDriver.OpenDeviceSession(IHardwareDeviceDriver.Direction.Input, memoryManager, sampleFormat, parameter.SampleRate, parameter.ChannelCount);

            AudioInputSystem audioIn = new(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]);

            ResultCode result = audioIn.Initialize(inputDeviceName, sampleFormat, ref parameter, sessionId);

            if (result == ResultCode.Success)
            {
                outputDeviceName = audioIn.DeviceName;
                outputConfiguration = new AudioOutputConfiguration
                {
                    ChannelCount = audioIn.ChannelCount,
                    SampleFormat = audioIn.SampleFormat,
                    SampleRate = audioIn.SampleRate,
                    AudioOutState = audioIn.GetState(),
                };

                obj = audioIn;

                Register(audioIn);
            }
            else
            {
                ReleaseSessionId(sessionId);

                obj = null;
                outputDeviceName = null;
                outputConfiguration = default;
            }

            return result;
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);

            if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0)
            {
                Dispose(true);
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Clone the sessions array to dispose them outside the lock.
                AudioInputSystem[] sessions;

                lock (_sessionLock)
                {
                    sessions = _sessions.ToArray();
                }

                foreach (AudioInputSystem input in sessions)
                {
                    input?.Dispose();
                }
            }
        }
    }
}