Skip to content

Commit 383b580

Browse files
Move OnPCMData calls outside buffer lock to avoid blocking
Dequeue PCM data into a batch while holding the lock, then deliver outside the lock. This prevents the receiver's processing time from blocking the other socket handler. Co-authored-by: YimingZhanshen <76594627+YimingZhanshen@users.noreply.github.com>
1 parent b6f299c commit 383b580

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

AirPlay/Listeners/AudioListener.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ public override async Task OnRawCSocketAsync(Socket cSocket, CancellationToken c
101101
}
102102

103103
// Dequeue and play audio received on control socket (used during screen mirroring)
104+
var pcmBatch = new System.Collections.Generic.List<PcmData>();
104105
byte[] audiobuf;
105106
int audiobuflen = 0;
106107
uint timestamp = 0;
@@ -116,9 +117,15 @@ public override async Task OnRawCSocketAsync(Socket cSocket, CancellationToken c
116117
pcmData.Data = audiobuf;
117118
pcmData.Pts = (ulong)(timestamp - _sync_timestamp) * 1000000UL / 44100 + _sync_time;
118119

119-
_receiver.OnPCMData(pcmData);
120+
pcmBatch.Add(pcmData);
120121
}
121122
}
123+
124+
// Deliver PCM outside the lock to avoid blocking the data handler
125+
foreach (var pcm in pcmBatch)
126+
{
127+
_receiver.OnPCMData(pcm);
128+
}
122129
}
123130
else if (type_c == 0x54)
124131
{
@@ -217,6 +224,7 @@ public override async Task OnRawDSocketAsync(Socket dSocket, CancellationToken c
217224
}
218225

219226
// Dequeue all available frames from buffer
227+
var pcmBatch = new System.Collections.Generic.List<PcmData>();
220228
lock (_bufferLock)
221229
{
222230
while ((audiobuf = RaopBufferDequeue(_raopBuffer, ref audiobuflen, ref timestamp, no_resend)) != null)
@@ -230,10 +238,16 @@ public override async Task OnRawDSocketAsync(Socket dSocket, CancellationToken c
230238

231239
pcmData.Pts = (ulong)(timestamp - _sync_timestamp) * 1000000UL / 44100 + _sync_time;
232240

233-
_receiver.OnPCMData(pcmData);
241+
pcmBatch.Add(pcmData);
234242
}
235243
}
236244

245+
// Deliver PCM outside the lock to avoid blocking the control handler
246+
foreach (var pcm in pcmBatch)
247+
{
248+
_receiver.OnPCMData(pcm);
249+
}
250+
237251
/* Handle possible resend requests */
238252
if (!no_resend)
239253
{

0 commit comments

Comments
 (0)