aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs
blob: 028d0885422c2dc89810a71fe74fe8e530276350 (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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//
// Copyright (c) 2019-2021 Ryujinx
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

using Ryujinx.Audio.Renderer.Common;
using Ryujinx.Audio.Renderer.Parameter;
using Ryujinx.Audio.Renderer.Server.Effect;
using Ryujinx.Audio.Renderer.Server.Splitter;
using Ryujinx.Common.Utilities;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

using static Ryujinx.Audio.Constants;

namespace Ryujinx.Audio.Renderer.Server.Mix
{
    /// <summary>
    /// Server state for a mix.
    /// </summary>
    [StructLayout(LayoutKind.Sequential, Size = 0x940, Pack = Alignment)]
    public struct MixState
    {
        public const uint InvalidDistanceFromFinalMix = 0x80000000;

        public const int Alignment = 0x10;

        /// <summary>
        /// Base volume of the mix.
        /// </summary>
        public float Volume;

        /// <summary>
        /// Target sample rate of the mix.
        /// </summary>
        public uint SampleRate;

        /// <summary>
        /// Target buffer count.
        /// </summary>
        public uint BufferCount;

        /// <summary>
        /// Set to true if in use.
        /// </summary>
        [MarshalAs(UnmanagedType.I1)]
        public bool IsUsed;

        /// <summary>
        /// The id of the mix.
        /// </summary>
        public int MixId;

        /// <summary>
        /// The mix node id.
        /// </summary>
        public int NodeId;

        /// <summary>
        /// the buffer offset to use for command generation.
        /// </summary>
        public uint BufferOffset;

        /// <summary>
        /// The distance of the mix from the final mix.
        /// </summary>
        public uint DistanceFromFinalMix;

        /// <summary>
        /// The effect processing order storage.
        /// </summary>
        private IntPtr _effectProcessingOrderArrayPointer;

        /// <summary>
        /// The max element count that can be found in the effect processing order storage.
        /// </summary>
        public uint EffectProcessingOrderArrayMaxCount;

        /// <summary>
        /// The mix to output the result of this mix.
        /// </summary>
        public int DestinationMixId;

        /// <summary>
        /// Mix buffer volumes storage.
        /// </summary>
        private MixVolumeArray _mixVolumeArray;

        /// <summary>
        /// The splitter to output the result of this mix.
        /// </summary>
        public uint DestinationSplitterId;

        /// <summary>
        /// If set to true, the long size pre-delay is supported on the reverb command.
        /// </summary>
        [MarshalAs(UnmanagedType.I1)]
        public bool IsLongSizePreDelaySupported;

        [StructLayout(LayoutKind.Sequential, Size = Size, Pack = 1)]
        private struct MixVolumeArray
        {
            private const int Size = 4 * MixBufferCountMax * MixBufferCountMax;
        }

        /// <summary>
        /// Mix buffer volumes.
        /// </summary>
        /// <remarks>Used when no splitter id is specified.</remarks>
        public Span<float> MixBufferVolume => SpanHelpers.AsSpan<MixVolumeArray, float>(ref _mixVolumeArray);

        /// <summary>
        /// Get the volume for a given connection destination.
        /// </summary>
        /// <param name="sourceIndex">The source node index.</param>
        /// <param name="destinationIndex">The destination node index</param>
        /// <returns>The volume for the given connection destination.</returns>
        public float GetMixBufferVolume(int sourceIndex, int destinationIndex)
        {
            return MixBufferVolume[sourceIndex * MixBufferCountMax + destinationIndex];
        }

        /// <summary>
        /// The array used to order effects associated to this mix.
        /// </summary>
        public Span<int> EffectProcessingOrderArray
        {
            get
            {
                if (_effectProcessingOrderArrayPointer == IntPtr.Zero)
                {
                    return Span<int>.Empty;
                }

                unsafe
                {
                    return new Span<int>((void*)_effectProcessingOrderArrayPointer, (int)EffectProcessingOrderArrayMaxCount);
                }
            }
        }

        /// <summary>
        /// Create a new <see cref="MixState"/>
        /// </summary>
        /// <param name="effectProcessingOrderArray"></param>
        /// <param name="behaviourContext"></param>
        public MixState(Memory<int> effectProcessingOrderArray, ref BehaviourContext behaviourContext) : this()
        {
            MixId = UnusedMixId;

            DistanceFromFinalMix = InvalidDistanceFromFinalMix;

            DestinationMixId = UnusedMixId;

            DestinationSplitterId = UnusedSplitterId;

            unsafe
            {
                // SAFETY: safe as effectProcessingOrderArray comes from the work buffer memory that is pinned.
                _effectProcessingOrderArrayPointer = (IntPtr)Unsafe.AsPointer(ref MemoryMarshal.GetReference(effectProcessingOrderArray.Span));
            }

            EffectProcessingOrderArrayMaxCount = (uint)effectProcessingOrderArray.Length;

            IsLongSizePreDelaySupported = behaviourContext.IsLongSizePreDelaySupported();

            ClearEffectProcessingOrder();
        }

        /// <summary>
        /// Clear the <see cref="DistanceFromFinalMix"/> value to its default state.
        /// </summary>
        public void ClearDistanceFromFinalMix()
        {
            DistanceFromFinalMix = InvalidDistanceFromFinalMix;
        }

        /// <summary>
        /// Clear the <see cref="EffectProcessingOrderArray"/> to its default state.
        /// </summary>
        public void ClearEffectProcessingOrder()
        {
            EffectProcessingOrderArray.Fill(-1);
        }

        /// <summary>
        /// Return true if the mix has any destinations.
        /// </summary>
        /// <returns>True if the mix has any destinations.</returns>
        public bool HasAnyDestination()
        {
            return DestinationMixId != UnusedMixId || DestinationSplitterId != UnusedSplitterId;
        }

        /// <summary>
        /// Update the mix connection on the adjacency matrix.
        /// </summary>
        /// <param name="edgeMatrix">The adjacency matrix.</param>
        /// <param name="parameter">The input parameter of the mix.</param>
        /// <param name="splitterContext">The splitter context.</param>
        /// <returns>Return true, new connections were done on the adjacency matrix.</returns>
        private bool UpdateConnection(EdgeMatrix edgeMatrix, ref MixParameter parameter, ref SplitterContext splitterContext)
        {
            bool hasNewConnections;

            if (DestinationSplitterId == UnusedSplitterId)
            {
                hasNewConnections = false;
            }
            else
            {
                ref SplitterState splitter = ref splitterContext.GetState((int)DestinationSplitterId);

                hasNewConnections = splitter.HasNewConnection;
            }

            if (DestinationMixId == parameter.DestinationMixId && DestinationSplitterId == parameter.DestinationSplitterId && !hasNewConnections)
            {
                return false;
            }

            edgeMatrix.RemoveEdges(MixId);

            if (parameter.DestinationMixId == UnusedMixId)
            {
                if (parameter.DestinationSplitterId != UnusedSplitterId)
                {
                    ref SplitterState splitter = ref splitterContext.GetState((int)parameter.DestinationSplitterId);

                    for (int i = 0; i < splitter.DestinationCount; i++)
                    {
                        Span<SplitterDestination> destination = splitter.GetData(i);

                        if (!destination.IsEmpty)
                        {
                            int destinationMixId = destination[0].DestinationId;

                            if (destinationMixId != UnusedMixId)
                            {
                                edgeMatrix.Connect(MixId, destinationMixId);
                            }
                        }
                    }
                }
            }
            else
            {
                edgeMatrix.Connect(MixId, parameter.DestinationMixId);
            }

            DestinationMixId = parameter.DestinationMixId;
            DestinationSplitterId = parameter.DestinationSplitterId;

            return true;
        }

        /// <summary>
        /// Update the mix from user information.
        /// </summary>
        /// <param name="edgeMatrix">The adjacency matrix.</param>
        /// <param name="parameter">The input parameter of the mix.</param>
        /// <param name="effectContext">The effect context.</param>
        /// <param name="splitterContext">The splitter context.</param>
        /// <param name="behaviourContext">The behaviour context.</param>
        /// <returns>Return true if the mix was changed.</returns>
        public bool Update(EdgeMatrix edgeMatrix, ref MixParameter parameter, EffectContext effectContext, SplitterContext splitterContext, BehaviourContext behaviourContext)
        {
            bool isDirty;

            Volume = parameter.Volume;
            SampleRate = parameter.SampleRate;
            BufferCount = parameter.BufferCount;
            IsUsed = parameter.IsUsed;
            MixId = parameter.MixId;
            NodeId = parameter.NodeId;
            parameter.MixBufferVolume.CopyTo(MixBufferVolume);

            if (behaviourContext.IsSplitterSupported())
            {
                isDirty = UpdateConnection(edgeMatrix, ref parameter, ref splitterContext);
            }
            else
            {
                isDirty = DestinationMixId != parameter.DestinationMixId;

                if (DestinationMixId != parameter.DestinationMixId)
                {
                    DestinationMixId = parameter.DestinationMixId;
                }

                DestinationSplitterId = UnusedSplitterId;
            }

            ClearEffectProcessingOrder();

            for (int i = 0; i < effectContext.GetCount(); i++)
            {
                ref BaseEffect effect = ref effectContext.GetEffect(i);

                if (effect.MixId == MixId)
                {
                    Debug.Assert(effect.ProcessingOrder <= EffectProcessingOrderArrayMaxCount);

                    if (effect.ProcessingOrder > EffectProcessingOrderArrayMaxCount)
                    {
                        return isDirty;
                    }

                    EffectProcessingOrderArray[(int)effect.ProcessingOrder] = i;
                }
            }

            return isDirty;
        }
    }
}