FreeRDP
Loading...
Searching...
No Matches
server/rdpsnd_main.c
1
21
22#include <freerdp/config.h>
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27
28#include <winpr/crt.h>
29#include <winpr/assert.h>
30#include <winpr/cast.h>
31#include <winpr/print.h>
32#include <winpr/stream.h>
33
34#include <freerdp/freerdp.h>
35#include <freerdp/channels/log.h>
36
37#include "rdpsnd_common.h"
38#include "rdpsnd_main.h"
39
40static wStream* rdpsnd_server_get_buffer(RdpsndServerContext* context)
41{
42 wStream* s = nullptr;
43 WINPR_ASSERT(context);
44 WINPR_ASSERT(context->priv);
45
46 s = context->priv->rdpsnd_pdu;
47 Stream_ResetPosition(s);
48 return s;
49}
50
56static UINT rdpsnd_server_send_formats(RdpsndServerContext* context)
57{
58 wStream* s = rdpsnd_server_get_buffer(context);
59 BOOL status = FALSE;
60 ULONG written = 0;
61
62 if (!Stream_EnsureRemainingCapacity(s, 24))
63 return ERROR_OUTOFMEMORY;
64
65 Stream_Write_UINT8(s, SNDC_FORMATS);
66 Stream_Write_UINT8(s, 0);
67 Stream_Seek_UINT16(s);
68 Stream_Write_UINT32(s, 0); /* dwFlags */
69 Stream_Write_UINT32(s, 0); /* dwVolume */
70 Stream_Write_UINT32(s, 0); /* dwPitch */
71 Stream_Write_UINT16(s, 0); /* wDGramPort */
72 Stream_Write_UINT16(
73 s, WINPR_ASSERTING_INT_CAST(uint16_t, context->num_server_formats)); /* wNumberOfFormats */
74 Stream_Write_UINT8(s, context->block_no); /* cLastBlockConfirmed */
75 Stream_Write_UINT16(s, CHANNEL_VERSION_WIN_MAX); /* wVersion */
76 Stream_Write_UINT8(s, 0); /* bPad */
77
78 for (size_t i = 0; i < context->num_server_formats; i++)
79 {
80 const AUDIO_FORMAT* format = &context->server_formats[i];
81
82 if (!audio_format_write(s, format))
83 goto fail;
84 }
85
86 {
87 const size_t pos = Stream_GetPosition(s);
88 if (pos > UINT16_MAX)
89 goto fail;
90
91 WINPR_ASSERT(pos >= 4);
92 if (!Stream_SetPosition(s, 2))
93 goto fail;
94 Stream_Write_UINT16(s, (UINT16)(pos - 4));
95 if (!Stream_SetPosition(s, pos))
96 goto fail;
97
98 WINPR_ASSERT(context->priv);
99
100 status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char),
101 (UINT32)pos, &written);
102 Stream_ResetPosition(s);
103 }
104fail:
105 return status ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR;
106}
107
113static UINT rdpsnd_server_recv_waveconfirm(RdpsndServerContext* context, wStream* s)
114{
115 UINT16 timestamp = 0;
116 BYTE confirmBlockNum = 0;
117 UINT error = CHANNEL_RC_OK;
118
119 WINPR_ASSERT(context);
120
121 if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
122 return ERROR_INVALID_DATA;
123
124 Stream_Read_UINT16(s, timestamp);
125 Stream_Read_UINT8(s, confirmBlockNum);
126 Stream_Seek_UINT8(s);
127 IFCALLRET(context->ConfirmBlock, error, context, confirmBlockNum, timestamp);
128
129 if (error)
130 WLog_ERR(TAG, "context->ConfirmBlock failed with error %" PRIu32 "", error);
131
132 return error;
133}
134
140static UINT rdpsnd_server_recv_trainingconfirm(RdpsndServerContext* context, wStream* s)
141{
142 UINT16 timestamp = 0;
143 UINT16 packsize = 0;
144 UINT error = CHANNEL_RC_OK;
145
146 WINPR_ASSERT(context);
147
148 if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
149 return ERROR_INVALID_DATA;
150
151 Stream_Read_UINT16(s, timestamp);
152 Stream_Read_UINT16(s, packsize);
153
154 IFCALLRET(context->TrainingConfirm, error, context, timestamp, packsize);
155 if (error)
156 WLog_ERR(TAG, "context->TrainingConfirm failed with error %" PRIu32 "", error);
157
158 return error;
159}
160
166static UINT rdpsnd_server_recv_quality_mode(RdpsndServerContext* context, wStream* s)
167{
168 WINPR_ASSERT(context);
169
170 if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
171 {
172 WLog_ERR(TAG, "not enough data in stream!");
173 return ERROR_INVALID_DATA;
174 }
175
176 Stream_Read_UINT16(s, context->qualityMode); /* wQualityMode */
177 Stream_Seek_UINT16(s); /* Reserved */
178
179 WLog_DBG(TAG, "Client requested sound quality: 0x%04" PRIX16 "", context->qualityMode);
180
181 return CHANNEL_RC_OK;
182}
183
184static void rdpsnd_server_client_format_free(RdpsndServerContext* context)
185{
186 WINPR_ASSERT(context);
187 EnterCriticalSection(&context->priv->lock);
188 audio_formats_free(context->client_formats, context->num_client_formats);
189 context->client_formats = nullptr;
190 context->num_client_formats = 0;
191 LeaveCriticalSection(&context->priv->lock);
192}
193
199static UINT rdpsnd_server_recv_formats(RdpsndServerContext* context, wStream* s)
200{
201 UINT error = ERROR_INTERNAL_ERROR;
202
203 WINPR_ASSERT(context);
204
205 rdpsnd_server_client_format_free(context);
206
207 if (!Stream_CheckAndLogRequiredLength(TAG, s, 20))
208 return ERROR_INVALID_DATA;
209
210 Stream_Read_UINT32(s, context->capsFlags); /* dwFlags */
211 Stream_Read_UINT32(s, context->initialVolume); /* dwVolume */
212 Stream_Read_UINT32(s, context->initialPitch); /* dwPitch */
213 Stream_Read_UINT16(s, context->udpPort); /* wDGramPort */
214 const UINT16 wNumberOfFormats = Stream_Get_UINT16(s); /* wNumberOfFormats */
215 Stream_Read_UINT8(s, context->lastblock); /* cLastBlockConfirmed */
216 Stream_Read_UINT16(s, context->clientVersion); /* wVersion */
217 Stream_Seek_UINT8(s); /* bPad */
218
219 /* this check is only a guess as cbSize can influence the size of a format record */
220 if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, wNumberOfFormats, 18ull))
221 return ERROR_INVALID_DATA;
222
223 if (wNumberOfFormats == 0)
224 {
225 WLog_ERR(TAG, "client doesn't support any format!");
226 return CHANNEL_RC_OK;
227 }
228
229 EnterCriticalSection(&context->priv->lock);
230 context->client_formats = audio_formats_new(wNumberOfFormats);
231
232 if (!context->client_formats)
233 {
234 WLog_ERR(TAG, "calloc failed!");
235 error = CHANNEL_RC_NO_MEMORY;
236 goto out_free;
237 }
238
239 context->num_client_formats = wNumberOfFormats;
240
241 for (UINT16 i = 0; i < context->num_client_formats; i++)
242 {
243 AUDIO_FORMAT* format = &context->client_formats[i];
244 audio_format_free(format);
245
246 if (!audio_format_read(s, format))
247 goto out_free;
248
249 /* nChannels and nBlockAlign are used as divisors when sending audio
250 * (rdpsnd_server_align_wave_pdu: size % nBlockAlign; ADPCM frame sizing
251 * divides by nChannels). A malicious client can advertise a format with
252 * either field set to 0, causing a division by zero. No valid
253 * WAVEFORMATEX has zero channels or zero block alignment. */
254 if ((format->nChannels == 0) || (format->nBlockAlign == 0))
255 {
256 WLog_ERR(TAG, "invalid client audio format: nChannels or nBlockAlign is 0");
257 error = ERROR_INVALID_DATA;
258 goto out_free;
259 }
260
261 /* Some wave formats have stricter requirements */
262 switch (format->wFormatTag)
263 {
264 case WAVE_FORMAT_DVI_ADPCM:
265 if (format->nBlockAlign < 4)
266 {
267 WLog_ERR(TAG,
268 "invalid client audio format %s: nBlockAlign is %" PRIu32
269 ", must be >= 4",
270 audio_format_get_tag_string(format->wFormatTag), format->nBlockAlign);
271 error = ERROR_INVALID_DATA;
272 goto out_free;
273 }
274 break;
275 case WAVE_FORMAT_ADPCM:
276 if (format->nBlockAlign < 8)
277 {
278 WLog_ERR(TAG,
279 "invalid client audio format %s: nBlockAlign is %" PRIu32
280 ", must be >= 8",
281 audio_format_get_tag_string(format->wFormatTag), format->nBlockAlign);
282 error = ERROR_INVALID_DATA;
283 goto out_free;
284 }
285 break;
286 default:
287 break;
288 }
289 }
290
291 if (!context->num_client_formats)
292 {
293 WLog_ERR(TAG, "client doesn't support any known format!");
294 goto out_free;
295 }
296 LeaveCriticalSection(&context->priv->lock);
297
298 return CHANNEL_RC_OK;
299out_free:
300 LeaveCriticalSection(&context->priv->lock);
301 rdpsnd_server_client_format_free(context);
302 return error;
303}
304
305static DWORD WINAPI rdpsnd_server_thread(LPVOID arg)
306{
307 DWORD nCount = 0;
308 DWORD status = 0;
309 HANDLE events[2] = WINPR_C_ARRAY_INIT;
310 RdpsndServerContext* context = (RdpsndServerContext*)arg;
311 UINT error = CHANNEL_RC_OK;
312
313 WINPR_ASSERT(context);
314 WINPR_ASSERT(context->priv);
315
316 events[nCount++] = context->priv->channelEvent;
317 events[nCount++] = context->priv->StopEvent;
318
319 WINPR_ASSERT(nCount <= ARRAYSIZE(events));
320
321 while (TRUE)
322 {
323 status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE);
324
325 if (status == WAIT_FAILED)
326 {
327 error = GetLastError();
328 WLog_ERR(TAG, "WaitForMultipleObjects failed with error %" PRIu32 "!", error);
329 break;
330 }
331
332 status = WaitForSingleObject(context->priv->StopEvent, 0);
333
334 if (status == WAIT_FAILED)
335 {
336 error = GetLastError();
337 WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error);
338 break;
339 }
340
341 if (status == WAIT_OBJECT_0)
342 break;
343
344 if ((error = rdpsnd_server_handle_messages(context)))
345 {
346 WLog_ERR(TAG, "rdpsnd_server_handle_messages failed with error %" PRIu32 "", error);
347 break;
348 }
349 }
350
351 if (error && context->rdpcontext)
352 setChannelError(context->rdpcontext, error, "rdpsnd_server_thread reported an error");
353
354 ExitThread(error);
355 return error;
356}
357
363static UINT rdpsnd_server_initialize(RdpsndServerContext* context, BOOL ownThread)
364{
365 WINPR_ASSERT(context);
366 WINPR_ASSERT(context->priv);
367
368 context->priv->ownThread = ownThread;
369 return context->Start(context);
370}
371
377static UINT rdpsnd_server_select_format(RdpsndServerContext* context, UINT16 client_format_index)
378{
379 UINT error = ERROR_INVALID_DATA;
380
381 WINPR_ASSERT(context);
382 WINPR_ASSERT(context->priv);
383
384 EnterCriticalSection(&context->priv->lock);
385 if ((client_format_index >= context->num_client_formats) || (!context->src_format))
386 {
387 WLog_ERR(TAG, "index %" PRIu16 " is not correct.", client_format_index);
388 goto out;
389 }
390
391 // Invalidate currently selected format. Should anything fail no function will touch the
392 // buffers.
393 context->selected_client_format = UINT16_MAX;
394
395 context->priv->src_bytes_per_sample = context->src_format->wBitsPerSample / 8;
396 context->priv->src_bytes_per_frame =
397 context->priv->src_bytes_per_sample * context->src_format->nChannels;
398
399 const AUDIO_FORMAT* format = &context->client_formats[client_format_index];
400
401 if (format->nSamplesPerSec == 0)
402 {
403 WLog_ERR(TAG, "invalid Client Sound Format!");
404 error = ERROR_INVALID_DATA;
405 goto out;
406 }
407
408 if (context->latency <= 0)
409 context->latency = 50;
410
411 context->priv->out_frames = context->src_format->nSamplesPerSec * context->latency / 1000;
412
413 if (context->priv->out_frames < 1)
414 context->priv->out_frames = 1;
415
416 switch (format->wFormatTag)
417 {
418 case WAVE_FORMAT_DVI_ADPCM:
419 {
420 error = ERROR_INVALID_DATA;
421 if (format->nBlockAlign / 4ull < format->nChannels)
422 goto out;
423 if (format->nChannels == 0)
424 goto out;
425
426 error = CHANNEL_RC_OK;
427
428 /* maximum:
429 * 1: nBlockAlign=0xFFFF - 4 * nChannels=1 == 0xFFFB
430 * 2: 4 * 0xFFFB = 0x3FFEC
431 */
432 const size_t bs = 4ULL * (format->nBlockAlign - 4ULL * format->nChannels);
433 if (bs == 0)
434 goto out;
435
436 context->priv->out_frames -= context->priv->out_frames % bs;
437
438 if (context->priv->out_frames < bs)
439 context->priv->out_frames = bs;
440 }
441 break;
442
443 case WAVE_FORMAT_ADPCM:
444 {
445 error = ERROR_INVALID_DATA;
446 if (format->nBlockAlign / 7 < format->nChannels)
447 goto out;
448 if (format->nChannels == 0)
449 goto out;
450
451 error = CHANNEL_RC_OK;
452
453 /* maximum:
454 * 1: nBlockAlign=0xFFFF - 7 * nChannels=1 == 0xFFF8
455 * 2: 2 * 0xFFF8 = 0x1FFF0
456 * 3: 0x1FFF0 / nChannels=1 + 2 = 0x1FFF2
457 */
458 const size_t bs =
459 (format->nBlockAlign - 7 * format->nChannels) * 2 / format->nChannels + 2;
460
461 context->priv->out_frames -= context->priv->out_frames % bs;
462
463 if (context->priv->out_frames < bs)
464 context->priv->out_frames = bs;
465 }
466 break;
467 default:
468 break;
469 }
470
471 context->priv->out_pending_frames = 0;
472 if (context->priv->out_frames > UINT32_MAX / context->priv->src_bytes_per_frame)
473 goto out;
474
475 const size_t out_buffer_size = context->priv->out_frames * context->priv->src_bytes_per_frame;
476 if (context->priv->out_buffer_size < out_buffer_size)
477 {
478 BYTE* newBuffer = (BYTE*)realloc(context->priv->out_buffer, out_buffer_size);
479
480 if (!newBuffer)
481 {
482 WLog_ERR(TAG, "realloc failed!");
483 error = CHANNEL_RC_NO_MEMORY;
484 goto out;
485 }
486
487 context->priv->out_buffer = newBuffer;
488 context->priv->out_buffer_size = out_buffer_size;
489 }
490
491 if (!freerdp_dsp_context_reset(context->priv->dsp_context, format, 0u))
492 {
493 error = ERROR_INTERNAL_ERROR;
494 goto out;
495 }
496
497 context->selected_client_format = client_format_index;
498 error = CHANNEL_RC_OK;
499out:
500 LeaveCriticalSection(&context->priv->lock);
501 return error;
502}
503
509static UINT rdpsnd_server_training(RdpsndServerContext* context, UINT16 timestamp, UINT16 packsize,
510 BYTE* data)
511{
512 ULONG written = 0;
513 BOOL status = 0;
514 wStream* s = rdpsnd_server_get_buffer(context);
515
516 if (!Stream_EnsureRemainingCapacity(s, 8))
517 return ERROR_INTERNAL_ERROR;
518
519 Stream_Write_UINT8(s, SNDC_TRAINING);
520 Stream_Write_UINT8(s, 0);
521 Stream_Seek_UINT16(s);
522 Stream_Write_UINT16(s, timestamp);
523 Stream_Write_UINT16(s, packsize);
524
525 if (packsize > 0)
526 {
527 if (!Stream_EnsureRemainingCapacity(s, packsize))
528 {
529 Stream_ResetPosition(s);
530 return ERROR_INTERNAL_ERROR;
531 }
532
533 Stream_Write(s, data, packsize);
534 }
535
536 const size_t end = Stream_GetPosition(s);
537 if ((end < 4) || (end > UINT16_MAX))
538 return ERROR_INTERNAL_ERROR;
539
540 if (!Stream_SetPosition(s, 2))
541 return ERROR_INTERNAL_ERROR;
542 Stream_Write_UINT16(s, (UINT16)(end - 4));
543
544 status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char),
545 (UINT32)end, &written);
546
547 Stream_ResetPosition(s);
548
549 return status ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR;
550}
551
552/* Pads the wave with zeros to a multiple of the block alignment of its format.
553 * Not an Opus packet: it has no frame sync, every byte after it is taken as
554 * part of it, and with zeros there it no longer decodes (the client echoes
555 * back the alignment the server offered, which may well be more than 1). */
556static BOOL rdpsnd_server_align_wave_pdu(wStream* s, const AUDIO_FORMAT* format)
557{
558 size_t size = 0;
559 Stream_SealLength(s);
560 size = Stream_Length(s);
561
562 WINPR_ASSERT(format);
563 const UINT32 alignment = format->nBlockAlign;
564 if ((format->wFormatTag != WAVE_FORMAT_OPUS) && ((size % alignment) != 0))
565 {
566 size_t offset = alignment - size % alignment;
567
568 if (!Stream_EnsureRemainingCapacity(s, offset))
569 return FALSE;
570
571 Stream_Zero(s, offset);
572 }
573
574 Stream_SealLength(s);
575 return TRUE;
576}
577
584static UINT rdpsnd_server_send_wave_pdu_int(RdpsndServerContext* context, UINT16 wTimestamp)
585{
586 ULONG written = 0;
587 UINT error = CHANNEL_RC_OK;
588 wStream* s = rdpsnd_server_get_buffer(context);
589
590 if (context->selected_client_format > context->num_client_formats)
591 return ERROR_INTERNAL_ERROR;
592
593 WINPR_ASSERT(context->client_formats);
594
595 const AUDIO_FORMAT* format = &context->client_formats[context->selected_client_format];
596 /* WaveInfo PDU */
597 Stream_ResetPosition(s);
598
599 if (!Stream_EnsureRemainingCapacity(s, 16))
600 return ERROR_OUTOFMEMORY;
601
602 Stream_Write_UINT8(s, SNDC_WAVE); /* msgType */
603 Stream_Write_UINT8(s, 0); /* bPad */
604 Stream_Write_UINT16(s, 0); /* BodySize */
605 Stream_Write_UINT16(s, wTimestamp); /* wTimeStamp */
606 Stream_Write_UINT16(s, context->selected_client_format); /* wFormatNo */
607 Stream_Write_UINT8(s, context->block_no); /* cBlockNo */
608 Stream_Seek(s, 3); /* bPad */
609 const size_t start = Stream_GetPosition(s);
610 const BYTE* src = context->priv->out_buffer;
611 const size_t length =
612 1ull * context->priv->out_pending_frames * context->priv->src_bytes_per_frame;
613
614 if (!freerdp_dsp_encode(context->priv->dsp_context, context->src_format, src, length, s))
615 return ERROR_INTERNAL_ERROR;
616
617 /* Set stream size */
618 if (!rdpsnd_server_align_wave_pdu(s, format))
619 return ERROR_INTERNAL_ERROR;
620
621 const size_t end = Stream_GetPosition(s);
622 const size_t pos = end - start + 8ULL;
623 if (pos > UINT16_MAX)
624 return ERROR_INTERNAL_ERROR;
625 if (!Stream_SetPosition(s, 2))
626 return ERROR_INTERNAL_ERROR;
627 Stream_Write_UINT16(s, (UINT16)pos);
628 if (!Stream_SetPosition(s, end))
629 return ERROR_INTERNAL_ERROR;
630
631 if (!WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char),
632 (UINT32)(start + 4), &written))
633 {
634 WLog_ERR(TAG, "WTSVirtualChannelWrite failed!");
635 error = ERROR_INTERNAL_ERROR;
636 }
637
638 if (error != CHANNEL_RC_OK)
639 {
640 WLog_ERR(TAG, "WTSVirtualChannelWrite failed!");
641 error = ERROR_INTERNAL_ERROR;
642 goto out;
643 }
644
645 if (!Stream_SetPosition(s, start))
646 {
647 error = ERROR_INTERNAL_ERROR;
648 goto out;
649 }
650 Stream_Write_UINT32(s, 0); /* bPad */
651 if (!Stream_SetPosition(s, start))
652 {
653 error = ERROR_INTERNAL_ERROR;
654 goto out;
655 }
656
657 WINPR_ASSERT((end - start) <= UINT32_MAX);
658 if (!WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_Pointer(s),
659 (UINT32)(end - start), &written))
660 {
661 WLog_ERR(TAG, "WTSVirtualChannelWrite failed!");
662 error = ERROR_INTERNAL_ERROR;
663 }
664
665 context->block_no = (context->block_no + 1) % 256;
666
667out:
668 Stream_ResetPosition(s);
669 context->priv->out_pending_frames = 0;
670 return error;
671}
672
673static UINT rdpsnd_server_send_wave_pdu(RdpsndServerContext* context, UINT16 wTimestamp)
674{
675 WINPR_ASSERT(context);
676 EnterCriticalSection(&context->priv->lock);
677 const UINT rc = rdpsnd_server_send_wave_pdu_int(context, wTimestamp);
678 LeaveCriticalSection(&context->priv->lock);
679 return rc;
680}
687static UINT rdpsnd_server_send_wave2_pdu(RdpsndServerContext* context, UINT16 formatNo,
688 const BYTE* data, size_t size, BOOL encoded,
689 UINT16 timestamp, UINT32 audioTimeStamp)
690{
691 ULONG written = 0;
692 UINT error = CHANNEL_RC_OK;
693 wStream* s = rdpsnd_server_get_buffer(context);
694
695 if (!Stream_EnsureRemainingCapacity(s, 16))
696 {
697 error = ERROR_INTERNAL_ERROR;
698 goto out;
699 }
700
701 /* Wave2 PDU */
702 Stream_Write_UINT8(s, SNDC_WAVE2); /* msgType */
703 Stream_Write_UINT8(s, 0); /* bPad */
704 Stream_Write_UINT16(s, 0); /* BodySize */
705 Stream_Write_UINT16(s, timestamp); /* wTimeStamp */
706 Stream_Write_UINT16(s, formatNo); /* wFormatNo */
707 Stream_Write_UINT8(s, context->block_no); /* cBlockNo */
708 Stream_Write_UINT8(s, 0); /* bPad */
709 Stream_Write_UINT8(s, 0); /* bPad */
710 Stream_Write_UINT8(s, 0); /* bPad */
711 Stream_Write_UINT32(s, audioTimeStamp); /* dwAudioTimeStamp */
712
713 if (encoded)
714 {
715 if (!Stream_EnsureRemainingCapacity(s, size))
716 {
717 error = ERROR_INTERNAL_ERROR;
718 goto out;
719 }
720
721 Stream_Write(s, data, size);
722 }
723 else
724 {
725 if (!freerdp_dsp_encode(context->priv->dsp_context, context->src_format, data, size, s))
726 {
727 error = ERROR_INTERNAL_ERROR;
728 goto out;
729 }
730
731 EnterCriticalSection(&context->priv->lock);
732 const AUDIO_FORMAT* format = &context->client_formats[formatNo];
733 const BOOL rc = rdpsnd_server_align_wave_pdu(s, format);
734 LeaveCriticalSection(&context->priv->lock);
735 if (!rc)
736 {
737 error = ERROR_INTERNAL_ERROR;
738 goto out;
739 }
740 }
741
742 {
743 const size_t end = Stream_GetPosition(s);
744 if (end > UINT16_MAX + 4)
745 {
746 error = ERROR_INTERNAL_ERROR;
747 goto out;
748 }
749
750 if (!Stream_SetPosition(s, 2))
751 {
752 error = ERROR_INTERNAL_ERROR;
753 goto out;
754 }
755 Stream_Write_UINT16(s, (UINT16)(end - 4));
756
757 const BOOL status = WTSVirtualChannelWrite(context->priv->ChannelHandle,
758 Stream_BufferAs(s, char), (UINT32)end, &written);
759
760 if (!status || (end != written))
761 {
762 WLog_ERR(TAG,
763 "WTSVirtualChannelWrite failed! [stream length=%" PRIuz " - written=%" PRIu32,
764 end, written);
765 error = ERROR_INTERNAL_ERROR;
766 }
767 }
768
769 context->block_no = (context->block_no + 1) % 256;
770
771out:
772 Stream_ResetPosition(s);
773 context->priv->out_pending_frames = 0;
774 return error;
775}
776
777/* Wrapper function to send WAVE or WAVE2 PDU depending on client connected */
778static UINT rdpsnd_server_send_audio_pdu(RdpsndServerContext* context, UINT16 wTimestamp)
779{
780 const BYTE* src = nullptr;
781 size_t length = 0;
782
783 WINPR_ASSERT(context);
784 WINPR_ASSERT(context->priv);
785
786 if (context->selected_client_format >= context->num_client_formats)
787 return ERROR_INTERNAL_ERROR;
788
789 src = context->priv->out_buffer;
790 length = context->priv->out_pending_frames * context->priv->src_bytes_per_frame;
791
792 if (context->clientVersion >= CHANNEL_VERSION_WIN_8)
793 return rdpsnd_server_send_wave2_pdu(context, context->selected_client_format, src, length,
794 FALSE, wTimestamp, wTimestamp);
795 else
796 return rdpsnd_server_send_wave_pdu(context, wTimestamp);
797}
798
804static UINT rdpsnd_server_send_samples(RdpsndServerContext* context, const void* buf,
805 size_t nframes, UINT16 wTimestamp)
806{
807 UINT error = CHANNEL_RC_OK;
808
809 WINPR_ASSERT(context);
810 WINPR_ASSERT(context->priv);
811
812 EnterCriticalSection(&context->priv->lock);
813
814 if (context->selected_client_format >= context->num_client_formats)
815 {
816 /* It's possible while format negotiation has not been done */
817 WLog_WARN(TAG, "Drop samples because client format has not been negotiated.");
818 error = ERROR_NOT_READY;
819 goto out;
820 }
821
822 while (nframes > 0)
823 {
824 const size_t cframes =
825 MIN(nframes, context->priv->out_frames - context->priv->out_pending_frames);
826 size_t cframesize = cframes * context->priv->src_bytes_per_frame;
827 CopyMemory(context->priv->out_buffer +
828 (context->priv->out_pending_frames * context->priv->src_bytes_per_frame),
829 buf, cframesize);
830 buf = (const BYTE*)buf + cframesize;
831 nframes -= cframes;
832 context->priv->out_pending_frames += cframes;
833
834 if (context->priv->out_pending_frames >= context->priv->out_frames)
835 {
836 if ((error = rdpsnd_server_send_audio_pdu(context, wTimestamp)))
837 {
838 WLog_ERR(TAG, "rdpsnd_server_send_audio_pdu failed with error %" PRIu32 "", error);
839 break;
840 }
841 }
842 }
843
844out:
845 LeaveCriticalSection(&context->priv->lock);
846 return error;
847}
848
854static UINT rdpsnd_server_send_samples2(RdpsndServerContext* context, UINT16 formatNo,
855 const void* buf, size_t size, UINT16 timestamp,
856 UINT32 audioTimeStamp)
857{
858 UINT error = CHANNEL_RC_OK;
859
860 WINPR_ASSERT(context);
861 WINPR_ASSERT(context->priv);
862
863 if (context->clientVersion < CHANNEL_VERSION_WIN_8)
864 return ERROR_INTERNAL_ERROR;
865
866 EnterCriticalSection(&context->priv->lock);
867
868 error =
869 rdpsnd_server_send_wave2_pdu(context, formatNo, buf, size, TRUE, timestamp, audioTimeStamp);
870
871 LeaveCriticalSection(&context->priv->lock);
872
873 return error;
874}
875
881static UINT rdpsnd_server_set_volume(RdpsndServerContext* context, UINT16 left, UINT16 right)
882{
883 BOOL status = 0;
884 ULONG written = 0;
885 wStream* s = rdpsnd_server_get_buffer(context);
886
887 if (!Stream_EnsureRemainingCapacity(s, 8))
888 return ERROR_NOT_ENOUGH_MEMORY;
889
890 Stream_Write_UINT8(s, SNDC_SETVOLUME);
891 Stream_Write_UINT8(s, 0);
892 Stream_Write_UINT16(s, 4); /* Payload length */
893 Stream_Write_UINT16(s, left);
894 Stream_Write_UINT16(s, right);
895
896 const size_t len = Stream_GetPosition(s);
897 WINPR_ASSERT(len <= UINT32_MAX);
898 status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char),
899 (ULONG)len, &written);
900 Stream_ResetPosition(s);
901 return status ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR;
902}
903
909static UINT rdpsnd_server_close(RdpsndServerContext* context)
910{
911 BOOL status = 0;
912 ULONG written = 0;
913 UINT error = CHANNEL_RC_OK;
914 wStream* s = rdpsnd_server_get_buffer(context);
915
916 EnterCriticalSection(&context->priv->lock);
917
918 if (context->priv->out_pending_frames > 0)
919 {
920 if (context->selected_client_format >= context->num_client_formats)
921 {
922 WLog_ERR(TAG, "Pending audio frame exists while no format selected.");
923 error = ERROR_INVALID_DATA;
924 }
925 else if ((error = rdpsnd_server_send_audio_pdu(context, 0)))
926 {
927 WLog_ERR(TAG, "rdpsnd_server_send_audio_pdu failed with error %" PRIu32 "", error);
928 }
929 }
930
931 LeaveCriticalSection(&context->priv->lock);
932
933 if (error)
934 return error;
935
936 context->selected_client_format = UINT16_MAX;
937
938 if (!Stream_EnsureRemainingCapacity(s, 4))
939 return ERROR_OUTOFMEMORY;
940
941 Stream_Write_UINT8(s, SNDC_CLOSE);
942 Stream_Write_UINT8(s, 0);
943 Stream_Seek_UINT16(s);
944 const size_t pos = Stream_GetPosition(s);
945 WINPR_ASSERT(pos >= 4);
946 if (!Stream_SetPosition(s, 2))
947 return ERROR_INVALID_DATA;
948 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(uint16_t, pos - 4));
949 if (!Stream_SetPosition(s, pos))
950 return ERROR_INVALID_DATA;
951
952 const size_t len = Stream_GetPosition(s);
953 WINPR_ASSERT(len <= UINT32_MAX);
954 status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char),
955 (UINT32)len, &written);
956 Stream_ResetPosition(s);
957 return status ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR;
958}
959
965static UINT rdpsnd_server_start(RdpsndServerContext* context)
966{
967 void* buffer = nullptr;
968 DWORD bytesReturned = 0;
969 RdpsndServerPrivate* priv = nullptr;
970 UINT error = ERROR_INTERNAL_ERROR;
971 PULONG pSessionId = nullptr;
972
973 WINPR_ASSERT(context);
974 WINPR_ASSERT(context->priv);
975
976 priv = context->priv;
977 priv->SessionId = WTS_CURRENT_SESSION;
978
979 if (context->use_dynamic_virtual_channel)
980 {
981 UINT32 channelId = 0;
982 BOOL status = TRUE;
983
984 if (WTSQuerySessionInformationA(context->vcm, WTS_CURRENT_SESSION, WTSSessionId,
985 (LPSTR*)&pSessionId, &bytesReturned))
986 {
987 priv->SessionId = (DWORD)*pSessionId;
988 WTSFreeMemory(pSessionId);
989 priv->ChannelHandle = WTSVirtualChannelOpenEx(priv->SessionId, RDPSND_DVC_CHANNEL_NAME,
990 WTS_CHANNEL_OPTION_DYNAMIC);
991 if (!priv->ChannelHandle)
992 {
993 WLog_ERR(TAG, "Open audio dynamic virtual channel (%s) failed!",
994 RDPSND_DVC_CHANNEL_NAME);
995 return ERROR_INTERNAL_ERROR;
996 }
997
998 channelId = WTSChannelGetIdByHandle(priv->ChannelHandle);
999
1000 IFCALLRET(context->ChannelIdAssigned, status, context, channelId);
1001 if (!status)
1002 {
1003 WLog_ERR(TAG, "context->ChannelIdAssigned failed!");
1004 goto out_close;
1005 }
1006 }
1007 else
1008 {
1009 WLog_ERR(TAG, "WTSQuerySessionInformationA failed!");
1010 return ERROR_INTERNAL_ERROR;
1011 }
1012 }
1013 else
1014 {
1015 priv->ChannelHandle =
1016 WTSVirtualChannelOpen(context->vcm, WTS_CURRENT_SESSION, RDPSND_CHANNEL_NAME);
1017 if (!priv->ChannelHandle)
1018 {
1019 WLog_ERR(TAG, "Open audio static virtual channel (rdpsnd) failed!");
1020 return ERROR_INTERNAL_ERROR;
1021 }
1022 }
1023
1024 if (!WTSVirtualChannelQuery(priv->ChannelHandle, WTSVirtualEventHandle, &buffer,
1025 &bytesReturned) ||
1026 (bytesReturned != sizeof(HANDLE)))
1027 {
1028 WLog_ERR(TAG,
1029 "error during WTSVirtualChannelQuery(WTSVirtualEventHandle) or invalid returned "
1030 "size(%" PRIu32 ")",
1031 bytesReturned);
1032
1033 if (buffer)
1034 WTSFreeMemory(buffer);
1035
1036 goto out_close;
1037 }
1038
1039 priv->channelEvent = *(HANDLE*)buffer;
1040 WTSFreeMemory(buffer);
1041 priv->rdpsnd_pdu = Stream_New(nullptr, 4096);
1042
1043 if (!priv->rdpsnd_pdu)
1044 {
1045 WLog_ERR(TAG, "Stream_New failed!");
1046 error = CHANNEL_RC_NO_MEMORY;
1047 goto out_close;
1048 }
1049
1050 if ((error = rdpsnd_server_send_formats(context)))
1051 {
1052 WLog_ERR(TAG, "rdpsnd_server_send_formats failed with error %" PRIu32 "", error);
1053 goto out_pdu;
1054 }
1055
1056 if (priv->ownThread)
1057 {
1058 context->priv->StopEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
1059
1060 if (!context->priv->StopEvent)
1061 {
1062 WLog_ERR(TAG, "CreateEvent failed!");
1063 goto out_pdu;
1064 }
1065
1066 context->priv->Thread =
1067 CreateThread(nullptr, 0, rdpsnd_server_thread, (void*)context, 0, nullptr);
1068
1069 if (!context->priv->Thread)
1070 {
1071 WLog_ERR(TAG, "CreateThread failed!");
1072 goto out_stopEvent;
1073 }
1074 }
1075
1076 return CHANNEL_RC_OK;
1077out_stopEvent:
1078 (void)CloseHandle(context->priv->StopEvent);
1079 context->priv->StopEvent = nullptr;
1080out_pdu:
1081 Stream_Free(context->priv->rdpsnd_pdu, TRUE);
1082 context->priv->rdpsnd_pdu = nullptr;
1083out_close:
1084 (void)WTSVirtualChannelClose(context->priv->ChannelHandle);
1085 context->priv->ChannelHandle = nullptr;
1086 return error;
1087}
1088
1094static UINT rdpsnd_server_stop(RdpsndServerContext* context)
1095{
1096 UINT error = CHANNEL_RC_OK;
1097
1098 WINPR_ASSERT(context);
1099 WINPR_ASSERT(context->priv);
1100
1101 if (!context->priv->ChannelHandle)
1102 return error;
1103
1104 if (context->priv->ownThread)
1105 {
1106 if (context->priv->StopEvent)
1107 {
1108 (void)SetEvent(context->priv->StopEvent);
1109
1110 if (WaitForSingleObject(context->priv->Thread, INFINITE) == WAIT_FAILED)
1111 {
1112 error = GetLastError();
1113 WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error);
1114 return error;
1115 }
1116
1117 (void)CloseHandle(context->priv->Thread);
1118 (void)CloseHandle(context->priv->StopEvent);
1119 context->priv->Thread = nullptr;
1120 context->priv->StopEvent = nullptr;
1121 }
1122 }
1123
1124 if (context->priv->rdpsnd_pdu)
1125 {
1126 Stream_Free(context->priv->rdpsnd_pdu, TRUE);
1127 context->priv->rdpsnd_pdu = nullptr;
1128 }
1129
1130 if (context->priv->ChannelHandle)
1131 {
1132 (void)WTSVirtualChannelClose(context->priv->ChannelHandle);
1133 context->priv->ChannelHandle = nullptr;
1134 }
1135
1136 return error;
1137}
1138
1139RdpsndServerContext* rdpsnd_server_context_new(HANDLE vcm)
1140{
1141 RdpsndServerPrivate* priv = nullptr;
1142 RdpsndServerContext* context = (RdpsndServerContext*)calloc(1, sizeof(RdpsndServerContext));
1143
1144 if (!context)
1145 goto fail;
1146
1147 context->vcm = vcm;
1148 context->Start = rdpsnd_server_start;
1149 context->Stop = rdpsnd_server_stop;
1150 context->selected_client_format = UINT16_MAX;
1151 context->Initialize = rdpsnd_server_initialize;
1152 context->SendFormats = rdpsnd_server_send_formats;
1153 context->SelectFormat = rdpsnd_server_select_format;
1154 context->Training = rdpsnd_server_training;
1155 context->SendSamples = rdpsnd_server_send_samples;
1156 context->SendSamples2 = rdpsnd_server_send_samples2;
1157 context->SetVolume = rdpsnd_server_set_volume;
1158 context->Close = rdpsnd_server_close;
1159 context->priv = priv = (RdpsndServerPrivate*)calloc(1, sizeof(RdpsndServerPrivate));
1160
1161 if (!priv)
1162 {
1163 WLog_ERR(TAG, "calloc failed!");
1164 goto fail;
1165 }
1166
1167 priv->dsp_context = freerdp_dsp_context_new(TRUE);
1168
1169 if (!priv->dsp_context)
1170 {
1171 WLog_ERR(TAG, "freerdp_dsp_context_new failed!");
1172 goto fail;
1173 }
1174
1175 priv->input_stream = Stream_New(nullptr, 4);
1176
1177 if (!priv->input_stream)
1178 {
1179 WLog_ERR(TAG, "Stream_New failed!");
1180 goto fail;
1181 }
1182
1183 if (!InitializeCriticalSectionEx(&priv->lock, 0, 0))
1184 {
1185 WLog_ERR(TAG, "InitializeCriticalSectionEx failed!");
1186 goto fail;
1187 }
1188
1189 priv->expectedBytes = 4;
1190 priv->waitingHeader = TRUE;
1191 priv->ownThread = TRUE;
1192 return context;
1193fail:
1194 WINPR_PRAGMA_DIAG_PUSH
1195 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
1196 rdpsnd_server_context_free(context);
1197 WINPR_PRAGMA_DIAG_POP
1198 return nullptr;
1199}
1200
1201void rdpsnd_server_context_reset(RdpsndServerContext* context)
1202{
1203 WINPR_ASSERT(context);
1204 WINPR_ASSERT(context->priv);
1205
1206 context->priv->expectedBytes = 4;
1207 context->priv->waitingHeader = TRUE;
1208 Stream_ResetPosition(context->priv->input_stream);
1209}
1210
1211void rdpsnd_server_context_free(RdpsndServerContext* context)
1212{
1213 if (!context)
1214 return;
1215
1216 if (context->priv)
1217 {
1218 rdpsnd_server_stop(context);
1219
1220 free(context->priv->out_buffer);
1221
1222 if (context->priv->dsp_context)
1223 freerdp_dsp_context_free(context->priv->dsp_context);
1224
1225 if (context->priv->input_stream)
1226 Stream_Free(context->priv->input_stream, TRUE);
1227
1228 rdpsnd_server_client_format_free(context);
1229 DeleteCriticalSection(&context->priv->lock);
1230 }
1231
1232 free(context->server_formats);
1233 free(context->priv);
1234 free(context);
1235}
1236
1237HANDLE rdpsnd_server_get_event_handle(RdpsndServerContext* context)
1238{
1239 WINPR_ASSERT(context);
1240 WINPR_ASSERT(context->priv);
1241
1242 return context->priv->channelEvent;
1243}
1244
1245/*
1246 * Handle rpdsnd messages - server side
1247 *
1248 * @param Server side context
1249 *
1250 * @return 0 on success
1251 * ERROR_NO_DATA if no data could be read this time
1252 * otherwise error
1253 */
1259UINT rdpsnd_server_handle_messages(RdpsndServerContext* context)
1260{
1261 DWORD bytesReturned = 0;
1262 UINT ret = CHANNEL_RC_OK;
1263 RdpsndServerPrivate* priv = nullptr;
1264 wStream* s = nullptr;
1265
1266 WINPR_ASSERT(context);
1267 WINPR_ASSERT(context->priv);
1268
1269 priv = context->priv;
1270 s = priv->input_stream;
1271
1272 if (!WTSVirtualChannelRead(priv->ChannelHandle, 0, Stream_Pointer(s), priv->expectedBytes,
1273 &bytesReturned))
1274 {
1275 if (GetLastError() == ERROR_NO_DATA)
1276 return ERROR_NO_DATA;
1277
1278 WLog_ERR(TAG, "channel connection closed");
1279 return ERROR_INTERNAL_ERROR;
1280 }
1281
1282 priv->expectedBytes -= bytesReturned;
1283 Stream_Seek(s, bytesReturned);
1284
1285 if (priv->expectedBytes)
1286 return CHANNEL_RC_OK;
1287
1288 Stream_SealLength(s);
1289 Stream_ResetPosition(s);
1290
1291 if (priv->waitingHeader)
1292 {
1293 /* header case */
1294 Stream_Read_UINT8(s, priv->msgType);
1295 Stream_Seek_UINT8(s); /* bPad */
1296 Stream_Read_UINT16(s, priv->expectedBytes);
1297 priv->waitingHeader = FALSE;
1298 Stream_ResetPosition(s);
1299
1300 if (priv->expectedBytes)
1301 {
1302 if (!Stream_EnsureCapacity(s, priv->expectedBytes))
1303 {
1304 WLog_ERR(TAG, "Stream_EnsureCapacity failed!");
1305 return CHANNEL_RC_NO_MEMORY;
1306 }
1307
1308 return CHANNEL_RC_OK;
1309 }
1310 }
1311
1312 /* when here we have the header + the body */
1313#ifdef WITH_DEBUG_SND
1314 WLog_DBG(TAG, "message type %" PRIu8 "", priv->msgType);
1315#endif
1316 priv->expectedBytes = 4;
1317 priv->waitingHeader = TRUE;
1318
1319 EnterCriticalSection(&priv->lock);
1320 switch (priv->msgType)
1321 {
1322 case SNDC_WAVECONFIRM:
1323 ret = rdpsnd_server_recv_waveconfirm(context, s);
1324 break;
1325
1326 case SNDC_TRAINING:
1327 ret = rdpsnd_server_recv_trainingconfirm(context, s);
1328 break;
1329
1330 case SNDC_FORMATS:
1331 ret = rdpsnd_server_recv_formats(context, s);
1332
1333 if ((ret == CHANNEL_RC_OK) && (context->clientVersion < CHANNEL_VERSION_WIN_7))
1334 IFCALL(context->Activated, context);
1335
1336 break;
1337
1338 case SNDC_QUALITYMODE:
1339 ret = rdpsnd_server_recv_quality_mode(context, s);
1340
1341 if ((ret == CHANNEL_RC_OK) && (context->clientVersion >= CHANNEL_VERSION_WIN_7))
1342 IFCALL(context->Activated, context);
1343
1344 break;
1345
1346 default:
1347 WLog_ERR(TAG, "UNKNOWN MESSAGE TYPE!! (0x%02" PRIX8 ")", priv->msgType);
1348 ret = ERROR_INVALID_DATA;
1349 break;
1350 }
1351 LeaveCriticalSection(&priv->lock);
1352 Stream_ResetPosition(s);
1353 return ret;
1354}
1355
1356void rdpsnd_server_context_lock(RdpsndServerContext* context)
1357{
1358 WINPR_ASSERT(context);
1359 WINPR_ASSERT(context->priv);
1360 EnterCriticalSection(&context->priv->lock);
1361}
1362void rdpsnd_server_context_unlock(RdpsndServerContext* context)
1363{
1364 WINPR_ASSERT(context);
1365 WINPR_ASSERT(context->priv);
1366 LeaveCriticalSection(&context->priv->lock);
1367}