aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs
blob: 225f7d31b0ff9e45cd30ed984f7dd8612e983144 (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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
using Ryujinx.Audio.Common;
using Ryujinx.Audio.Renderer.Common;
using Ryujinx.Audio.Renderer.Dsp.State;
using Ryujinx.Audio.Renderer.Parameter;
using Ryujinx.Audio.Renderer.Server.MemoryPool;
using Ryujinx.Common.Memory;
using Ryujinx.Common.Utilities;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using static Ryujinx.Audio.Renderer.Common.BehaviourParameter;
using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter;
using PlayState = Ryujinx.Audio.Renderer.Server.Types.PlayState;

namespace Ryujinx.Audio.Renderer.Server.Voice
{
    [StructLayout(LayoutKind.Sequential, Pack = Alignment)]
    public struct VoiceState
    {
        public const int Alignment = 0x10;

        /// <summary>
        /// Set to true if the voice is used.
        /// </summary>
        [MarshalAs(UnmanagedType.I1)]
        public bool InUse;

        /// <summary>
        /// Set to true if the voice is new.
        /// </summary>
        [MarshalAs(UnmanagedType.I1)]
        public bool IsNew;

        [MarshalAs(UnmanagedType.I1)]
        public bool WasPlaying;

        /// <summary>
        /// The <see cref="SampleFormat"/> of the voice.
        /// </summary>
        public SampleFormat SampleFormat;

        /// <summary>
        /// The sample rate of the voice.
        /// </summary>
        public uint SampleRate;

        /// <summary>
        /// The total channel count used.
        /// </summary>
        public uint ChannelsCount;

        /// <summary>
        /// Id of the voice.
        /// </summary>
        public int Id;

        /// <summary>
        /// Node id of the voice.
        /// </summary>
        public int NodeId;

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

        /// <summary>
        /// The current voice <see cref="Types.PlayState"/>.
        /// </summary>
        public PlayState PlayState;

        /// <summary>
        /// The previous voice <see cref="Types.PlayState"/>.
        /// </summary>
        public PlayState PreviousPlayState;

        /// <summary>
        /// The priority of the voice.
        /// </summary>
        public uint Priority;

        /// <summary>
        /// Target sorting position of the voice. (used to sort voice with the same <see cref="Priority"/>)
        /// </summary>
        public uint SortingOrder;

        /// <summary>
        /// The pitch used on the voice.
        /// </summary>
        public float Pitch;

        /// <summary>
        /// The output volume of the voice.
        /// </summary>
        public float Volume;

        /// <summary>
        /// The previous output volume of the voice.
        /// </summary>
        public float PreviousVolume;

        /// <summary>
        /// Biquad filters to apply to the output of the voice.
        /// </summary>
        public Array2<BiquadFilterParameter> BiquadFilters;

        /// <summary>
        /// Total count of <see cref="WaveBufferInternal"/> of the voice.
        /// </summary>
        public uint WaveBuffersCount;

        /// <summary>
        /// Current playing <see cref="WaveBufferInternal"/> of the voice.
        /// </summary>
        public uint WaveBuffersIndex;

        /// <summary>
        /// Change the behaviour of the voice.
        /// </summary>
        /// <remarks>This was added on REV5.</remarks>
        public DecodingBehaviour DecodingBehaviour;

        /// <summary>
        /// User state <see cref="AddressInfo"/> required by the data source.
        /// </summary>
        /// <remarks>Only used for <see cref="SampleFormat.Adpcm"/> as the GC-ADPCM coefficients.</remarks>
        public AddressInfo DataSourceStateAddressInfo;

        /// <summary>
        /// The wavebuffers of this voice.
        /// </summary>
        public Array4<WaveBuffer> WaveBuffers;

        /// <summary>
        /// The channel resource ids associated to the voice.
        /// </summary>
        public Array6<int> ChannelResourceIds;

        /// <summary>
        /// The target splitter id of the voice.
        /// </summary>
        public uint SplitterId;

        /// <summary>
        /// Change the Sample Rate Conversion (SRC) quality of the voice.
        /// </summary>
        /// <remarks>This was added on REV8.</remarks>
        public SampleRateConversionQuality SrcQuality;

        /// <summary>
        /// If set to true, the voice was dropped.
        /// </summary>
        [MarshalAs(UnmanagedType.I1)]
        public bool VoiceDropFlag;

        /// <summary>
        /// Set to true if the data source state work buffer wasn't mapped.
        /// </summary>
        [MarshalAs(UnmanagedType.I1)]
        public bool DataSourceStateUnmapped;

        /// <summary>
        /// Set to true if any of the <see cref="WaveBuffer.BufferAddressInfo"/> work buffer wasn't mapped.
        /// </summary>
        [MarshalAs(UnmanagedType.I1)]
        public bool BufferInfoUnmapped;

        /// <summary>
        /// The biquad filter initialization state storage.
        /// </summary>
        private BiquadFilterNeedInitializationArrayStruct _biquadFilterNeedInitialization;

        /// <summary>
        /// Flush the amount of wavebuffer specified. This will result in the wavebuffer being skipped and marked played.
        /// </summary>
        /// <remarks>This was added on REV5.</remarks>
        public byte FlushWaveBufferCount;

        [StructLayout(LayoutKind.Sequential, Size = Constants.VoiceBiquadFilterCount)]
        private struct BiquadFilterNeedInitializationArrayStruct { }

        /// <summary>
        /// The biquad filter initialization state array.
        /// </summary>
        public Span<bool> BiquadFilterNeedInitialization => SpanHelpers.AsSpan<BiquadFilterNeedInitializationArrayStruct, bool>(ref _biquadFilterNeedInitialization);

        /// <summary>
        /// Initialize the <see cref="VoiceState"/>.
        /// </summary>
        public void Initialize()
        {
            IsNew = false;
            VoiceDropFlag = false;
            DataSourceStateUnmapped = false;
            BufferInfoUnmapped = false;
            FlushWaveBufferCount = 0;
            PlayState = PlayState.Stopped;
            Priority = Constants.VoiceLowestPriority;
            Id = 0;
            NodeId = 0;
            SampleRate = 0;
            SampleFormat = SampleFormat.Invalid;
            ChannelsCount = 0;
            Pitch = 0.0f;
            Volume = 0.0f;
            PreviousVolume = 0.0f;
            BiquadFilters.AsSpan().Clear();
            WaveBuffersCount = 0;
            WaveBuffersIndex = 0;
            MixId = Constants.UnusedMixId;
            SplitterId = Constants.UnusedSplitterId;
            DataSourceStateAddressInfo.Setup(0, 0);

            InitializeWaveBuffers();
        }

        /// <summary>
        /// Initialize the <see cref="WaveBuffer"/> in this <see cref="VoiceState"/>.
        /// </summary>
        private void InitializeWaveBuffers()
        {
            for (int i = 0; i < WaveBuffers.Length; i++)
            {
                WaveBuffers[i].StartSampleOffset = 0;
                WaveBuffers[i].EndSampleOffset = 0;
                WaveBuffers[i].ShouldLoop = false;
                WaveBuffers[i].IsEndOfStream = false;
                WaveBuffers[i].BufferAddressInfo.Setup(0, 0);
                WaveBuffers[i].ContextAddressInfo.Setup(0, 0);
                WaveBuffers[i].IsSendToAudioProcessor = true;
            }
        }

        /// <summary>
        /// Check if the voice needs to be skipped.
        /// </summary>
        /// <returns>Returns true if the voice needs to be skipped.</returns>
        public readonly bool ShouldSkip()
        {
            return !InUse || WaveBuffersCount == 0 || DataSourceStateUnmapped || BufferInfoUnmapped || VoiceDropFlag;
        }

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

        /// <summary>
        /// Indicate if the server voice information needs to be updated.
        /// </summary>
        /// <param name="parameter">The user parameter.</param>
        /// <returns>Return true, if the server voice information needs to be updated.</returns>
        private readonly bool ShouldUpdateParameters(ref VoiceInParameter parameter)
        {
            if (DataSourceStateAddressInfo.CpuAddress == parameter.DataSourceStateAddress)
            {
                return DataSourceStateAddressInfo.Size != parameter.DataSourceStateSize;
            }

            return DataSourceStateAddressInfo.CpuAddress != parameter.DataSourceStateAddress ||
                   DataSourceStateAddressInfo.Size != parameter.DataSourceStateSize ||
                   DataSourceStateUnmapped;
        }

        /// <summary>
        /// Update the internal state from a user parameter.
        /// </summary>
        /// <param name="outErrorInfo">The possible <see cref="ErrorInfo"/> that was generated.</param>
        /// <param name="parameter">The user parameter.</param>
        /// <param name="poolMapper">The mapper to use.</param>
        /// <param name="behaviourContext">The behaviour context.</param>
        public void UpdateParameters(out ErrorInfo outErrorInfo, ref VoiceInParameter parameter, ref PoolMapper poolMapper, ref BehaviourContext behaviourContext)
        {
            InUse = parameter.InUse;
            Id = parameter.Id;
            NodeId = parameter.NodeId;

            UpdatePlayState(parameter.PlayState);

            SrcQuality = parameter.SrcQuality;

            Priority = parameter.Priority;
            SortingOrder = parameter.SortingOrder;
            SampleRate = parameter.SampleRate;
            SampleFormat = parameter.SampleFormat;
            ChannelsCount = parameter.ChannelCount;
            Pitch = parameter.Pitch;
            Volume = parameter.Volume;
            parameter.BiquadFilters.AsSpan().CopyTo(BiquadFilters.AsSpan());
            WaveBuffersCount = parameter.WaveBuffersCount;
            WaveBuffersIndex = parameter.WaveBuffersIndex;

            if (behaviourContext.IsFlushVoiceWaveBuffersSupported())
            {
                FlushWaveBufferCount += parameter.FlushWaveBufferCount;
            }

            MixId = parameter.MixId;

            if (behaviourContext.IsSplitterSupported())
            {
                SplitterId = parameter.SplitterId;
            }
            else
            {
                SplitterId = Constants.UnusedSplitterId;
            }

            parameter.ChannelResourceIds.AsSpan().CopyTo(ChannelResourceIds.AsSpan());

            DecodingBehaviour behaviour = DecodingBehaviour.Default;

            if (behaviourContext.IsDecodingBehaviourFlagSupported())
            {
                behaviour = parameter.DecodingBehaviourFlags;
            }

            DecodingBehaviour = behaviour;

            if (parameter.ResetVoiceDropFlag)
            {
                VoiceDropFlag = false;
            }

            if (ShouldUpdateParameters(ref parameter))
            {
                DataSourceStateUnmapped = !poolMapper.TryAttachBuffer(out outErrorInfo, ref DataSourceStateAddressInfo, parameter.DataSourceStateAddress, parameter.DataSourceStateSize);
            }
            else
            {
                outErrorInfo = new ErrorInfo();
            }
        }

        /// <summary>
        /// Update the internal play state from user play state.
        /// </summary>
        /// <param name="userPlayState">The target user play state.</param>
        public void UpdatePlayState(Common.PlayState userPlayState)
        {
            PlayState oldServerPlayState = PlayState;

            PreviousPlayState = oldServerPlayState;

            PlayState newServerPlayState;

            switch (userPlayState)
            {
                case Common.PlayState.Start:
                    newServerPlayState = PlayState.Started;
                    break;

                case Common.PlayState.Stop:
                    if (oldServerPlayState == PlayState.Stopped)
                    {
                        return;
                    }

                    newServerPlayState = PlayState.Stopping;
                    break;

                case Common.PlayState.Pause:
                    newServerPlayState = PlayState.Paused;
                    break;

                default:
                    throw new NotImplementedException($"Unhandled PlayState.{userPlayState}");
            }

            PlayState = newServerPlayState;
        }

        /// <summary>
        /// Write the status of the voice to the given user output.
        /// </summary>
        /// <param name="outStatus">The given user output.</param>
        /// <param name="parameter">The user parameter.</param>
        /// <param name="voiceUpdateStates">The voice states associated to the <see cref="VoiceState"/>.</param>
        public void WriteOutStatus(ref VoiceOutStatus outStatus, ref VoiceInParameter parameter, ReadOnlySpan<Memory<VoiceUpdateState>> voiceUpdateStates)
        {
#if DEBUG
            // Sanity check in debug mode of the internal state
            if (!parameter.IsNew && !IsNew)
            {
                for (int i = 1; i < ChannelsCount; i++)
                {
                    ref VoiceUpdateState stateA = ref voiceUpdateStates[i - 1].Span[0];
                    ref VoiceUpdateState stateB = ref voiceUpdateStates[i].Span[0];

                    Debug.Assert(stateA.WaveBufferConsumed == stateB.WaveBufferConsumed);
                    Debug.Assert(stateA.PlayedSampleCount == stateB.PlayedSampleCount);
                    Debug.Assert(stateA.Offset == stateB.Offset);
                    Debug.Assert(stateA.WaveBufferIndex == stateB.WaveBufferIndex);
                    Debug.Assert(stateA.Fraction == stateB.Fraction);
                    Debug.Assert(stateA.IsWaveBufferValid.SequenceEqual(stateB.IsWaveBufferValid));
                }
            }
#endif
            if (parameter.IsNew || IsNew)
            {
                IsNew = true;

                outStatus.VoiceDropFlag = false;
                outStatus.PlayedWaveBuffersCount = 0;
                outStatus.PlayedSampleCount = 0;
            }
            else
            {
                ref VoiceUpdateState state = ref voiceUpdateStates[0].Span[0];

                outStatus.VoiceDropFlag = VoiceDropFlag;
                outStatus.PlayedWaveBuffersCount = state.WaveBufferConsumed;
                outStatus.PlayedSampleCount = state.PlayedSampleCount;
            }
        }

        /// <summary>
        /// Update the internal state of all the <see cref="WaveBuffer"/> of the <see cref="VoiceState"/>.
        /// </summary>
        /// <param name="errorInfos">An array of <see cref="ErrorInfo"/> used to report errors when mapping any of the <see cref="WaveBuffer"/>.</param>
        /// <param name="parameter">The user parameter.</param>
        /// <param name="voiceUpdateStates">The voice states associated to the <see cref="VoiceState"/>.</param>
        /// <param name="mapper">The mapper to use.</param>
        /// <param name="behaviourContext">The behaviour context.</param>
        public void UpdateWaveBuffers(out ErrorInfo[] errorInfos, ref VoiceInParameter parameter, ReadOnlySpan<Memory<VoiceUpdateState>> voiceUpdateStates, ref PoolMapper mapper, ref BehaviourContext behaviourContext)
        {
            errorInfos = new ErrorInfo[Constants.VoiceWaveBufferCount * 2];

            if (parameter.IsNew)
            {
                InitializeWaveBuffers();

                for (int i = 0; i < parameter.ChannelCount; i++)
                {
                    voiceUpdateStates[i].Span[0].IsWaveBufferValid.Clear();
                }
            }

            ref VoiceUpdateState voiceUpdateState = ref voiceUpdateStates[0].Span[0];

            for (int i = 0; i < Constants.VoiceWaveBufferCount; i++)
            {
                UpdateWaveBuffer(errorInfos.AsSpan(i * 2, 2), ref WaveBuffers[i], ref parameter.WaveBuffers[i], parameter.SampleFormat, voiceUpdateState.IsWaveBufferValid[i], ref mapper, ref behaviourContext);
            }
        }

        /// <summary>
        /// Update the internal state of one of the <see cref="WaveBuffer"/> of the <see cref="VoiceState"/>.
        /// </summary>
        /// <param name="errorInfos">A <see cref="Span{ErrorInfo}"/> used to report errors when mapping the <see cref="WaveBuffer"/>.</param>
        /// <param name="waveBuffer">The <see cref="WaveBuffer"/> to update.</param>
        /// <param name="inputWaveBuffer">The <see cref="WaveBufferInternal"/> from the user input.</param>
        /// <param name="sampleFormat">The <see cref="SampleFormat"/> from the user input.</param>
        /// <param name="isValid">If set to true, the server side wavebuffer is considered valid.</param>
        /// <param name="mapper">The mapper to use.</param>
        /// <param name="behaviourContext">The behaviour context.</param>
        private void UpdateWaveBuffer(Span<ErrorInfo> errorInfos, ref WaveBuffer waveBuffer, ref WaveBufferInternal inputWaveBuffer, SampleFormat sampleFormat, bool isValid, ref PoolMapper mapper, ref BehaviourContext behaviourContext)
        {
            if (!isValid && waveBuffer.IsSendToAudioProcessor && waveBuffer.BufferAddressInfo.CpuAddress != 0)
            {
                mapper.ForceUnmap(ref waveBuffer.BufferAddressInfo);
                waveBuffer.BufferAddressInfo.Setup(0, 0);
            }

            if (!inputWaveBuffer.SentToServer || BufferInfoUnmapped)
            {
                if (inputWaveBuffer.IsSampleOffsetValid(sampleFormat))
                {
                    Debug.Assert(waveBuffer.IsSendToAudioProcessor);

                    waveBuffer.IsSendToAudioProcessor = false;
                    waveBuffer.StartSampleOffset = inputWaveBuffer.StartSampleOffset;
                    waveBuffer.EndSampleOffset = inputWaveBuffer.EndSampleOffset;
                    waveBuffer.ShouldLoop = inputWaveBuffer.ShouldLoop;
                    waveBuffer.IsEndOfStream = inputWaveBuffer.IsEndOfStream;
                    waveBuffer.LoopStartSampleOffset = inputWaveBuffer.LoopFirstSampleOffset;
                    waveBuffer.LoopEndSampleOffset = inputWaveBuffer.LoopLastSampleOffset;
                    waveBuffer.LoopCount = inputWaveBuffer.LoopCount;

                    BufferInfoUnmapped = !mapper.TryAttachBuffer(out ErrorInfo bufferInfoError, ref waveBuffer.BufferAddressInfo, inputWaveBuffer.Address, inputWaveBuffer.Size);

                    errorInfos[0] = bufferInfoError;

                    if (sampleFormat == SampleFormat.Adpcm && behaviourContext.IsAdpcmLoopContextBugFixed() && inputWaveBuffer.ContextAddress != 0)
                    {
                        bool adpcmLoopContextMapped = mapper.TryAttachBuffer(out ErrorInfo adpcmLoopContextInfoError,
                                                                             ref waveBuffer.ContextAddressInfo,
                                                                             inputWaveBuffer.ContextAddress,
                                                                             inputWaveBuffer.ContextSize);

                        errorInfos[1] = adpcmLoopContextInfoError;

                        if (adpcmLoopContextMapped)
                        {
                            BufferInfoUnmapped = DataSourceStateUnmapped;
                        }
                        else
                        {
                            BufferInfoUnmapped = true;
                        }
                    }
                    else
                    {
                        waveBuffer.ContextAddressInfo.Setup(0, 0);
                    }
                }
                else
                {
                    errorInfos[0].ErrorCode = ResultCode.InvalidAddressInfo;
                    errorInfos[0].ExtraErrorInfo = inputWaveBuffer.Address;
                }
            }
        }

        /// <summary>
        /// Reset the resources associated to this <see cref="VoiceState"/>.
        /// </summary>
        /// <param name="context">The voice context.</param>
        private void ResetResources(VoiceContext context)
        {
            for (int i = 0; i < ChannelsCount; i++)
            {
                int channelResourceId = ChannelResourceIds[i];

                ref VoiceChannelResource voiceChannelResource = ref context.GetChannelResource(channelResourceId);

                Debug.Assert(voiceChannelResource.IsUsed);

                Memory<VoiceUpdateState> dspSharedState = context.GetUpdateStateForDsp(channelResourceId);

                MemoryMarshal.Cast<VoiceUpdateState, byte>(dspSharedState.Span).Clear();

                voiceChannelResource.UpdateState();
            }
        }

        /// <summary>
        /// Flush a certain amount of <see cref="WaveBuffer"/>.
        /// </summary>
        /// <param name="waveBufferCount">The amount of wavebuffer to flush.</param>
        /// <param name="voiceUpdateStates">The voice states associated to the <see cref="VoiceState"/>.</param>
        /// <param name="channelCount">The channel count from user input.</param>
        private void FlushWaveBuffers(uint waveBufferCount, Memory<VoiceUpdateState>[] voiceUpdateStates, uint channelCount)
        {
            uint waveBufferIndex = WaveBuffersIndex;

            for (int i = 0; i < waveBufferCount; i++)
            {
                WaveBuffers[(int)waveBufferIndex].IsSendToAudioProcessor = true;

                for (int j = 0; j < channelCount; j++)
                {
                    ref VoiceUpdateState voiceUpdateState = ref voiceUpdateStates[j].Span[0];

                    voiceUpdateState.WaveBufferIndex = (voiceUpdateState.WaveBufferIndex + 1) % Constants.VoiceWaveBufferCount;
                    voiceUpdateState.WaveBufferConsumed++;
                    voiceUpdateState.IsWaveBufferValid[(int)waveBufferIndex] = false;
                }

                waveBufferIndex = (waveBufferIndex + 1) % Constants.VoiceWaveBufferCount;
            }
        }

        /// <summary>
        /// Update the internal parameters for command generation.
        /// </summary>
        /// <param name="voiceUpdateStates">The voice states associated to the <see cref="VoiceState"/>.</param>
        /// <returns>Return true if this voice should be played.</returns>
        public bool UpdateParametersForCommandGeneration(Memory<VoiceUpdateState>[] voiceUpdateStates)
        {
            if (FlushWaveBufferCount != 0)
            {
                FlushWaveBuffers(FlushWaveBufferCount, voiceUpdateStates, ChannelsCount);

                FlushWaveBufferCount = 0;
            }

            switch (PlayState)
            {
                case PlayState.Started:
                    for (int i = 0; i < WaveBuffers.Length; i++)
                    {
                        ref WaveBuffer wavebuffer = ref WaveBuffers[i];

                        if (!wavebuffer.IsSendToAudioProcessor)
                        {
                            for (int y = 0; y < ChannelsCount; y++)
                            {
                                Debug.Assert(!voiceUpdateStates[y].Span[0].IsWaveBufferValid[i]);

                                voiceUpdateStates[y].Span[0].IsWaveBufferValid[i] = true;
                            }

                            wavebuffer.IsSendToAudioProcessor = true;
                        }
                    }

                    WasPlaying = false;

                    ref VoiceUpdateState primaryVoiceUpdateState = ref voiceUpdateStates[0].Span[0];

                    for (int i = 0; i < primaryVoiceUpdateState.IsWaveBufferValid.Length; i++)
                    {
                        if (primaryVoiceUpdateState.IsWaveBufferValid[i])
                        {
                            return true;
                        }
                    }

                    return false;

                case PlayState.Stopping:
                    for (int i = 0; i < WaveBuffers.Length; i++)
                    {
                        ref WaveBuffer wavebuffer = ref WaveBuffers[i];

                        wavebuffer.IsSendToAudioProcessor = true;

                        for (int j = 0; j < ChannelsCount; j++)
                        {
                            ref VoiceUpdateState voiceUpdateState = ref voiceUpdateStates[j].Span[0];

                            if (voiceUpdateState.IsWaveBufferValid[i])
                            {
                                voiceUpdateState.WaveBufferIndex = (voiceUpdateState.WaveBufferIndex + 1) % Constants.VoiceWaveBufferCount;
                                voiceUpdateState.WaveBufferConsumed++;
                            }

                            voiceUpdateState.IsWaveBufferValid[i] = false;
                        }
                    }

                    for (int i = 0; i < ChannelsCount; i++)
                    {
                        ref VoiceUpdateState voiceUpdateState = ref voiceUpdateStates[i].Span[0];

                        voiceUpdateState.Offset = 0;
                        voiceUpdateState.PlayedSampleCount = 0;
                        voiceUpdateState.Pitch.AsSpan().Clear();
                        voiceUpdateState.Fraction = 0;
                        voiceUpdateState.LoopContext = new AdpcmLoopContext();
                    }

                    PlayState = PlayState.Stopped;
                    WasPlaying = PreviousPlayState == PlayState.Started;

                    return WasPlaying;

                case PlayState.Stopped:
                case PlayState.Paused:
                    foreach (ref WaveBuffer wavebuffer in WaveBuffers.AsSpan())
                    {
                        wavebuffer.BufferAddressInfo.GetReference(true);
                        wavebuffer.ContextAddressInfo.GetReference(true);
                    }

                    if (SampleFormat == SampleFormat.Adpcm)
                    {
                        if (DataSourceStateAddressInfo.CpuAddress != 0)
                        {
                            DataSourceStateAddressInfo.GetReference(true);
                        }
                    }

                    WasPlaying = PreviousPlayState == PlayState.Started;

                    return WasPlaying;
                default:
                    throw new NotImplementedException($"{PlayState}");
            }
        }

        /// <summary>
        /// Update the internal state for command generation.
        /// </summary>
        /// <param name="context">The voice context.</param>
        /// <returns>Return true if this voice should be played.</returns>
        public bool UpdateForCommandGeneration(VoiceContext context)
        {
            if (IsNew)
            {
                ResetResources(context);
                PreviousVolume = Volume;
                IsNew = false;
            }

            Memory<VoiceUpdateState>[] voiceUpdateStates = new Memory<VoiceUpdateState>[Constants.VoiceChannelCountMax];

            for (int i = 0; i < ChannelsCount; i++)
            {
                voiceUpdateStates[i] = context.GetUpdateStateForDsp(ChannelResourceIds[i]);
            }

            return UpdateParametersForCommandGeneration(voiceUpdateStates);
        }
    }
}