4
4
using LiveKit . Internal ;
5
5
using System . Threading ;
6
6
using LiveKit . Internal . FFIClients . Requests ;
7
+ using UnityEngine ;
7
8
8
9
namespace LiveKit
9
10
{
@@ -52,11 +53,15 @@ public abstract class RtcAudioSource : IRtcSource
52
53
53
54
protected RtcAudioSource ( int channels = 2 , RtcAudioSourceType audioSourceType = RtcAudioSourceType . AudioSourceCustom )
54
55
{
55
- var isMicrophone = audioSourceType == RtcAudioSourceType . AudioSourceMicrophone ;
56
56
_sourceType = audioSourceType ;
57
+
58
+ var isMicrophone = audioSourceType == RtcAudioSourceType . AudioSourceMicrophone ;
57
59
_apm = new AudioProcessingModule ( isMicrophone , true , true , true ) ;
58
60
if ( isMicrophone )
61
+ {
59
62
_apmReverseStream = new ApmReverseStream ( _apm ) ;
63
+ _apm . SetStreamDelayMs ( EstimateStreamDelayMs ( ) ) ;
64
+ }
60
65
61
66
using var request = FFIBridge . Instance . NewRequest < NewAudioSourceRequest > ( ) ;
62
67
var newAudioSource = request . request ;
@@ -101,14 +106,8 @@ private void Update()
101
106
var frame = _captureBuffer . ReadDuration ( AudioProcessingModule . FRAME_DURATION_MS ) ;
102
107
if ( _muted || frame == null ) continue ;
103
108
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 ) ;
112
111
Capture ( frame ) ;
113
112
}
114
113
}
@@ -157,5 +156,14 @@ public override void SetMute(bool muted)
157
156
{
158
157
_muted = muted ;
159
158
}
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
+ }
160
168
}
161
169
}
0 commit comments