Skip to content

Commit bbad26a

Browse files
committed
Set stream delay
1 parent e09c6cc commit bbad26a

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

Runtime/Scripts/RtcAudioSource.cs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using LiveKit.Internal;
55
using System.Threading;
66
using LiveKit.Internal.FFIClients.Requests;
7+
using UnityEngine;
78

89
namespace LiveKit
910
{
@@ -52,11 +53,15 @@ public abstract class RtcAudioSource : IRtcSource
5253

5354
protected RtcAudioSource(int channels = 2, RtcAudioSourceType audioSourceType = RtcAudioSourceType.AudioSourceCustom)
5455
{
55-
var isMicrophone = audioSourceType == RtcAudioSourceType.AudioSourceMicrophone;
5656
_sourceType = audioSourceType;
57+
58+
var isMicrophone = audioSourceType == RtcAudioSourceType.AudioSourceMicrophone;
5759
_apm = new AudioProcessingModule(isMicrophone, true, true, true);
5860
if (isMicrophone)
61+
{
5962
_apmReverseStream = new ApmReverseStream(_apm);
63+
_apm.SetStreamDelayMs(EstimateStreamDelayMs());
64+
}
6065

6166
using var request = FFIBridge.Instance.NewRequest<NewAudioSourceRequest>();
6267
var newAudioSource = request.request;
@@ -101,14 +106,8 @@ private void Update()
101106
var frame = _captureBuffer.ReadDuration(AudioProcessingModule.FRAME_DURATION_MS);
102107
if (_muted || frame == null) continue;
103108

104-
if (_apmReverseStream != null)
105-
{
106-
// TODO: calculate stream delay
107-
var delayMs = 0;
108-
_apm.SetStreamDelayMs(delayMs);
109-
}
110-
_apm.ProcessStream(frame);
111-
109+
if (_apm != null)
110+
_apm.ProcessStream(frame);
112111
Capture(frame);
113112
}
114113
}
@@ -157,5 +156,14 @@ public override void SetMute(bool muted)
157156
{
158157
_muted = muted;
159158
}
159+
160+
private int EstimateStreamDelayMs()
161+
{
162+
// TODO: estimate more accurately
163+
int bufferLength, numBuffers;
164+
int sampleRate = AudioSettings.outputSampleRate;
165+
AudioSettings.GetDSPBufferSize(out bufferLength, out numBuffers);
166+
return 2 * (int)(1000f * bufferLength * numBuffers / sampleRate);
167+
}
160168
}
161169
}

0 commit comments

Comments
 (0)