Coverage Report

Created: 2026-10-15 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/channels/rdpsnd/client/rdpsnd_main.c
Line
Count
Source
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Audio Output Virtual Channel
4
 *
5
 * Copyright 2009-2011 Jay Sorg
6
 * Copyright 2010-2011 Vic Lee
7
 * Copyright 2012-2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>
8
 * Copyright 2015 Thincast Technologies GmbH
9
 * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
10
 * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 *     http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24
25
#include <freerdp/config.h>
26
27
#ifndef _WIN32
28
#include <sys/time.h>
29
#include <signal.h>
30
#endif
31
32
#include <stdio.h>
33
#include <stdlib.h>
34
#include <string.h>
35
#include <errno.h>
36
37
#include <winpr/crt.h>
38
#include <winpr/assert.h>
39
#include <winpr/wlog.h>
40
#include <winpr/stream.h>
41
#include <winpr/cmdline.h>
42
#include <winpr/sysinfo.h>
43
#include <winpr/collections.h>
44
45
#include <freerdp/types.h>
46
#include <freerdp/addin.h>
47
#include <freerdp/freerdp.h>
48
#include <freerdp/codec/dsp.h>
49
#include <freerdp/client/channels.h>
50
51
#include "rdpsnd_common.h"
52
#include "rdpsnd_main.h"
53
54
struct rdpsnd_plugin
55
{
56
  IWTSPlugin iface;
57
  IWTSListener* listener;
58
  GENERIC_LISTENER_CALLBACK* listener_callback;
59
60
  CHANNEL_DEF channelDef;
61
  CHANNEL_ENTRY_POINTS_FREERDP_EX channelEntryPoints;
62
63
  wStreamPool* pool;
64
  wStream* data_in;
65
66
  void* InitHandle;
67
  DWORD OpenHandle;
68
69
  wLog* log;
70
71
  BYTE cBlockNo;
72
  UINT16 wQualityMode;
73
  UINT16 wCurrentFormatNo;
74
75
  AUDIO_FORMAT* ServerFormats;
76
  UINT16 NumberOfServerFormats;
77
78
  AUDIO_FORMAT* ClientFormats;
79
  UINT16 NumberOfClientFormats;
80
81
  BOOL attached;
82
  BOOL dynamic;
83
84
  BOOL expectingWave;
85
  BYTE waveData[4];
86
  UINT16 waveDataSize;
87
  UINT16 wTimeStamp;
88
  UINT64 wArrivalTime;
89
90
  UINT32 latency;
91
  BOOL isOpen;
92
  AUDIO_FORMAT* fixed_format;
93
94
  UINT32 startPlayTime;
95
  size_t totalPlaySize;
96
97
  char* subsystem;
98
  char* device_name;
99
100
  /* Device plugin */
101
  rdpsndDevicePlugin* device;
102
  rdpContext* rdpcontext;
103
104
  FREERDP_DSP_CONTEXT* dsp_context;
105
106
  HANDLE thread;
107
  wMessageQueue* queue;
108
  CRITICAL_SECTION asyncLock;
109
  BOOL initialized;
110
111
  UINT16 wVersion;
112
  UINT32 volume;
113
  BOOL applyVolume;
114
115
  size_t references;
116
  BOOL OnOpenCalled;
117
  BOOL async;
118
  BOOL firstFlagReceived;
119
  UINT32 totalLength;
120
  BOOL connected;
121
};
122
123
WINPR_ATTR_NODISCARD
124
static DWORD WINAPI play_thread(LPVOID arg);
125
126
WINPR_ATTR_NODISCARD
127
static const char* rdpsnd_is_dyn_str(BOOL dynamic)
128
0
{
129
0
  if (dynamic)
130
0
    return "[dynamic]";
131
0
  return "[static]";
132
0
}
133
134
static void rdpsnd_virtual_channel_event_terminated(rdpsndPlugin* rdpsnd);
135
136
/**
137
 * Function description
138
 *
139
 * @return 0 on success, otherwise a Win32 error code
140
 */
141
WINPR_ATTR_NODISCARD
142
static UINT rdpsnd_virtual_channel_write(rdpsndPlugin* rdpsnd, wStream* s);
143
144
/**
145
 * Function description
146
 *
147
 * @return 0 on success, otherwise a Win32 error code
148
 */
149
WINPR_ATTR_NODISCARD
150
static UINT rdpsnd_send_quality_mode_pdu(rdpsndPlugin* rdpsnd)
151
0
{
152
0
  wStream* pdu = nullptr;
153
0
  WINPR_ASSERT(rdpsnd);
154
0
  pdu = Stream_New(nullptr, 8);
155
156
0
  if (!pdu)
157
0
  {
158
0
    WLog_ERR(TAG, "%s Stream_New failed!", rdpsnd_is_dyn_str(rdpsnd->dynamic));
159
0
    return CHANNEL_RC_NO_MEMORY;
160
0
  }
161
162
0
  Stream_Write_UINT8(pdu, SNDC_QUALITYMODE);      /* msgType */
163
0
  Stream_Write_UINT8(pdu, 0);                     /* bPad */
164
0
  Stream_Write_UINT16(pdu, 4);                    /* BodySize */
165
0
  Stream_Write_UINT16(pdu, rdpsnd->wQualityMode); /* wQualityMode */
166
0
  Stream_Write_UINT16(pdu, 0);                    /* Reserved */
167
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s QualityMode: %" PRIu16 "",
168
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic), rdpsnd->wQualityMode);
169
0
  return rdpsnd_virtual_channel_write(rdpsnd, pdu);
170
0
}
171
172
static void rdpsnd_select_supported_audio_formats(rdpsndPlugin* rdpsnd)
173
0
{
174
0
  WINPR_ASSERT(rdpsnd);
175
0
  audio_formats_free(rdpsnd->ClientFormats, rdpsnd->NumberOfClientFormats);
176
0
  rdpsnd->NumberOfClientFormats = 0;
177
0
  rdpsnd->ClientFormats = nullptr;
178
179
0
  if (!rdpsnd->NumberOfServerFormats)
180
0
    return;
181
182
0
  rdpsnd->ClientFormats = audio_formats_new(rdpsnd->NumberOfServerFormats);
183
184
0
  if (!rdpsnd->ClientFormats || !rdpsnd->device)
185
0
    return;
186
187
0
  for (UINT16 index = 0; index < rdpsnd->NumberOfServerFormats; index++)
188
0
  {
189
0
    const AUDIO_FORMAT* serverFormat = &rdpsnd->ServerFormats[index];
190
191
0
    if (!audio_format_compatible(rdpsnd->fixed_format, serverFormat))
192
0
      continue;
193
194
0
    WINPR_ASSERT(rdpsnd->device->FormatSupported);
195
0
    if (freerdp_dsp_supports_format(serverFormat, FALSE) ||
196
0
        rdpsnd->device->FormatSupported(rdpsnd->device, serverFormat))
197
0
    {
198
0
      AUDIO_FORMAT* clientFormat = &rdpsnd->ClientFormats[rdpsnd->NumberOfClientFormats++];
199
0
      audio_format_copy(serverFormat, clientFormat);
200
0
    }
201
0
  }
202
0
}
203
204
/**
205
 * Function description
206
 *
207
 * @return 0 on success, otherwise a Win32 error code
208
 */
209
WINPR_ATTR_NODISCARD
210
static UINT rdpsnd_send_client_audio_formats(rdpsndPlugin* rdpsnd)
211
0
{
212
0
  wStream* pdu = nullptr;
213
0
  size_t length = 0;
214
0
  UINT32 dwVolume = 0;
215
0
  UINT16 wNumberOfFormats = 0;
216
0
  WINPR_ASSERT(rdpsnd);
217
218
0
  if (!rdpsnd->device || (!rdpsnd->dynamic && (rdpsnd->OpenHandle == 0)))
219
0
    return CHANNEL_RC_INITIALIZATION_ERROR;
220
221
0
  dwVolume = IFCALLRESULT(0, rdpsnd->device->GetVolume, rdpsnd->device);
222
0
  wNumberOfFormats = rdpsnd->NumberOfClientFormats;
223
0
  length = 4 + 20;
224
225
0
  for (UINT16 index = 0; index < wNumberOfFormats; index++)
226
0
    length += (18 + rdpsnd->ClientFormats[index].cbSize);
227
228
  /* BodySize is a UINT16 field, so the whole PDU must fit in UINT16_MAX. A server can inflate
229
   * the client format list through large per-format cbSize values; without this bound the
230
   * accumulator wrapped and Stream_New() below was undersized. Mirrors the server side check in
231
   * rdpsnd_server_send_formats(). */
232
0
  if (length > UINT16_MAX)
233
0
    return ERROR_INVALID_DATA;
234
235
0
  pdu = Stream_New(nullptr, length);
236
237
0
  if (!pdu)
238
0
  {
239
0
    WLog_ERR(TAG, "%s Stream_New failed!", rdpsnd_is_dyn_str(rdpsnd->dynamic));
240
0
    return CHANNEL_RC_NO_MEMORY;
241
0
  }
242
243
0
  Stream_Write_UINT8(pdu, SNDC_FORMATS);                        /* msgType */
244
0
  Stream_Write_UINT8(pdu, 0);                                   /* bPad */
245
0
  Stream_Write_UINT16(pdu, (UINT16)(length - 4));               /* BodySize */
246
0
  Stream_Write_UINT32(pdu, TSSNDCAPS_ALIVE | TSSNDCAPS_VOLUME); /* dwFlags */
247
0
  Stream_Write_UINT32(pdu, dwVolume);                           /* dwVolume */
248
0
  Stream_Write_UINT32(pdu, 0);                                  /* dwPitch */
249
0
  Stream_Write_UINT16(pdu, 0);                                  /* wDGramPort */
250
0
  Stream_Write_UINT16(pdu, wNumberOfFormats);                   /* wNumberOfFormats */
251
0
  Stream_Write_UINT8(pdu, 0);                                   /* cLastBlockConfirmed */
252
0
  Stream_Write_UINT16(pdu, CHANNEL_VERSION_WIN_MAX);            /* wVersion */
253
0
  Stream_Write_UINT8(pdu, 0);                                   /* bPad */
254
255
0
  for (UINT16 index = 0; index < wNumberOfFormats; index++)
256
0
  {
257
0
    const AUDIO_FORMAT* clientFormat = &rdpsnd->ClientFormats[index];
258
259
0
    if (!audio_format_write(pdu, clientFormat))
260
0
    {
261
0
      Stream_Free(pdu, TRUE);
262
0
      return ERROR_INTERNAL_ERROR;
263
0
    }
264
0
  }
265
266
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s Client Audio Formats",
267
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic));
268
0
  return rdpsnd_virtual_channel_write(rdpsnd, pdu);
269
0
}
270
271
/**
272
 * Function description
273
 *
274
 * @return 0 on success, otherwise a Win32 error code
275
 */
276
WINPR_ATTR_NODISCARD
277
static UINT rdpsnd_recv_server_audio_formats_pdu(rdpsndPlugin* rdpsnd, wStream* s)
278
0
{
279
0
  UINT16 wNumberOfFormats = 0;
280
0
  UINT ret = ERROR_BAD_LENGTH;
281
282
0
  WINPR_ASSERT(rdpsnd);
283
0
  audio_formats_free(rdpsnd->ServerFormats, rdpsnd->NumberOfServerFormats);
284
0
  rdpsnd->NumberOfServerFormats = 0;
285
0
  rdpsnd->ServerFormats = nullptr;
286
287
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 30))
288
0
    return ERROR_BAD_LENGTH;
289
290
  /* http://msdn.microsoft.com/en-us/library/cc240956.aspx */
291
0
  Stream_Seek_UINT32(s); /* dwFlags */
292
0
  Stream_Seek_UINT32(s); /* dwVolume */
293
0
  Stream_Seek_UINT32(s); /* dwPitch */
294
0
  Stream_Seek_UINT16(s); /* wDGramPort */
295
0
  Stream_Read_UINT16(s, wNumberOfFormats);
296
0
  Stream_Read_UINT8(s, rdpsnd->cBlockNo);  /* cLastBlockConfirmed */
297
0
  Stream_Read_UINT16(s, rdpsnd->wVersion); /* wVersion */
298
0
  Stream_Seek_UINT8(s);                    /* bPad */
299
0
  rdpsnd->NumberOfServerFormats = wNumberOfFormats;
300
301
0
  if (!Stream_CheckAndLogRequiredLengthOfSize(TAG, s, wNumberOfFormats, 14ull))
302
0
    return ERROR_BAD_LENGTH;
303
304
0
  if (rdpsnd->NumberOfServerFormats > 0)
305
0
  {
306
0
    rdpsnd->ServerFormats = audio_formats_new(wNumberOfFormats);
307
308
0
    if (!rdpsnd->ServerFormats)
309
0
      return CHANNEL_RC_NO_MEMORY;
310
311
0
    for (UINT16 index = 0; index < wNumberOfFormats; index++)
312
0
    {
313
0
      AUDIO_FORMAT* format = &rdpsnd->ServerFormats[index];
314
315
0
      if (!audio_format_read(s, format))
316
0
        goto out_fail;
317
0
    }
318
0
  }
319
320
0
  WINPR_ASSERT(rdpsnd->device);
321
0
  ret = IFCALLRESULT(CHANNEL_RC_OK, rdpsnd->device->ServerFormatAnnounce, rdpsnd->device,
322
0
                     rdpsnd->ServerFormats, rdpsnd->NumberOfServerFormats);
323
0
  if (ret != CHANNEL_RC_OK)
324
0
    goto out_fail;
325
326
0
  rdpsnd_select_supported_audio_formats(rdpsnd);
327
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s Server Audio Formats",
328
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic));
329
0
  ret = rdpsnd_send_client_audio_formats(rdpsnd);
330
331
0
  if (ret == CHANNEL_RC_OK)
332
0
  {
333
0
    if (rdpsnd->wVersion >= CHANNEL_VERSION_WIN_7)
334
0
      ret = rdpsnd_send_quality_mode_pdu(rdpsnd);
335
0
  }
336
337
0
  return ret;
338
0
out_fail:
339
0
  audio_formats_free(rdpsnd->ServerFormats, rdpsnd->NumberOfServerFormats);
340
0
  rdpsnd->ServerFormats = nullptr;
341
0
  rdpsnd->NumberOfServerFormats = 0;
342
0
  return ret;
343
0
}
344
345
/**
346
 * Function description
347
 *
348
 * @return 0 on success, otherwise a Win32 error code
349
 */
350
WINPR_ATTR_NODISCARD
351
static UINT rdpsnd_send_training_confirm_pdu(rdpsndPlugin* rdpsnd, UINT16 wTimeStamp,
352
                                             UINT16 wPackSize)
353
0
{
354
0
  wStream* pdu = nullptr;
355
0
  WINPR_ASSERT(rdpsnd);
356
0
  pdu = Stream_New(nullptr, 8);
357
358
0
  if (!pdu)
359
0
  {
360
0
    WLog_ERR(TAG, "%s Stream_New failed!", rdpsnd_is_dyn_str(rdpsnd->dynamic));
361
0
    return CHANNEL_RC_NO_MEMORY;
362
0
  }
363
364
0
  Stream_Write_UINT8(pdu, SNDC_TRAINING); /* msgType */
365
0
  Stream_Write_UINT8(pdu, 0);             /* bPad */
366
0
  Stream_Write_UINT16(pdu, 4);            /* BodySize */
367
0
  Stream_Write_UINT16(pdu, wTimeStamp);
368
0
  Stream_Write_UINT16(pdu, wPackSize);
369
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG,
370
0
             "%s Training Response: wTimeStamp: %" PRIu16 " wPackSize: %" PRIu16 "",
371
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic), wTimeStamp, wPackSize);
372
0
  return rdpsnd_virtual_channel_write(rdpsnd, pdu);
373
0
}
374
375
/**
376
 * Function description
377
 *
378
 * @return 0 on success, otherwise a Win32 error code
379
 */
380
WINPR_ATTR_NODISCARD
381
static UINT rdpsnd_recv_training_pdu(rdpsndPlugin* rdpsnd, wStream* s)
382
0
{
383
0
  UINT16 wTimeStamp = 0;
384
0
  UINT16 wPackSize = 0;
385
0
  WINPR_ASSERT(rdpsnd);
386
0
  WINPR_ASSERT(s);
387
388
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
389
0
    return ERROR_BAD_LENGTH;
390
391
0
  Stream_Read_UINT16(s, wTimeStamp);
392
0
  Stream_Read_UINT16(s, wPackSize);
393
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG,
394
0
             "%s Training Request: wTimeStamp: %" PRIu16 " wPackSize: %" PRIu16 "",
395
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic), wTimeStamp, wPackSize);
396
0
  return rdpsnd_send_training_confirm_pdu(rdpsnd, wTimeStamp, wPackSize);
397
0
}
398
399
WINPR_ATTR_NODISCARD
400
static BOOL rdpsnd_apply_volume(rdpsndPlugin* rdpsnd)
401
0
{
402
0
  WINPR_ASSERT(rdpsnd);
403
404
0
  if (rdpsnd->isOpen && rdpsnd->applyVolume && rdpsnd->device)
405
0
  {
406
0
    BOOL rc = IFCALLRESULT(TRUE, rdpsnd->device->SetVolume, rdpsnd->device, rdpsnd->volume);
407
0
    if (!rc)
408
0
      return FALSE;
409
0
    rdpsnd->applyVolume = FALSE;
410
0
  }
411
0
  return TRUE;
412
0
}
413
414
WINPR_ATTR_NODISCARD
415
static BOOL rdpsnd_ensure_device_is_open(rdpsndPlugin* rdpsnd, UINT16 wFormatNo,
416
                                         const AUDIO_FORMAT* format)
417
0
{
418
0
  if (!rdpsnd)
419
0
    return FALSE;
420
0
  WINPR_ASSERT(format);
421
422
0
  if (!rdpsnd->isOpen || (wFormatNo != rdpsnd->wCurrentFormatNo))
423
0
  {
424
0
    BOOL rc = 0;
425
0
    BOOL supported = 0;
426
0
    AUDIO_FORMAT deviceFormat = *format;
427
428
0
    IFCALL(rdpsnd->device->Close, rdpsnd->device);
429
0
    supported = IFCALLRESULT(FALSE, rdpsnd->device->FormatSupported, rdpsnd->device, format);
430
431
0
    if (!supported)
432
0
    {
433
0
      if (!IFCALLRESULT(FALSE, rdpsnd->device->DefaultFormat, rdpsnd->device, format,
434
0
                        &deviceFormat))
435
0
      {
436
0
        deviceFormat.wFormatTag = WAVE_FORMAT_PCM;
437
0
        deviceFormat.wBitsPerSample = 16;
438
0
        deviceFormat.cbSize = 0;
439
0
      }
440
0
    }
441
442
0
    WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s Opening device with format %s [backend %s]",
443
0
               rdpsnd_is_dyn_str(rdpsnd->dynamic),
444
0
               audio_format_get_tag_string(format->wFormatTag),
445
0
               audio_format_get_tag_string(deviceFormat.wFormatTag));
446
0
    rc = IFCALLRESULT(FALSE, rdpsnd->device->Open, rdpsnd->device, &deviceFormat,
447
0
                      rdpsnd->latency);
448
449
0
    if (!rc)
450
0
      return FALSE;
451
452
0
    if (!supported)
453
0
    {
454
0
      if (!freerdp_dsp_context_reset(rdpsnd->dsp_context, format, 0u))
455
0
        return FALSE;
456
0
    }
457
458
0
    rdpsnd->isOpen = TRUE;
459
0
    rdpsnd->wCurrentFormatNo = wFormatNo;
460
0
    rdpsnd->startPlayTime = 0;
461
0
    rdpsnd->totalPlaySize = 0;
462
0
  }
463
464
0
  return rdpsnd_apply_volume(rdpsnd);
465
0
}
466
467
/**
468
 * Function description
469
 *
470
 * @return 0 on success, otherwise a Win32 error code
471
 */
472
WINPR_ATTR_NODISCARD
473
static UINT rdpsnd_recv_wave_info_pdu(rdpsndPlugin* rdpsnd, wStream* s, UINT16 BodySize)
474
0
{
475
0
  UINT16 wFormatNo = 0;
476
0
  const AUDIO_FORMAT* format = nullptr;
477
0
  WINPR_ASSERT(rdpsnd);
478
0
  WINPR_ASSERT(s);
479
480
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 12) || (BodySize < 8))
481
0
    return ERROR_BAD_LENGTH;
482
483
0
  rdpsnd->wArrivalTime = GetTickCount64();
484
0
  Stream_Read_UINT16(s, rdpsnd->wTimeStamp);
485
0
  Stream_Read_UINT16(s, wFormatNo);
486
487
0
  if (wFormatNo >= rdpsnd->NumberOfClientFormats)
488
0
    return ERROR_INVALID_DATA;
489
490
0
  Stream_Read_UINT8(s, rdpsnd->cBlockNo);
491
0
  Stream_Seek(s, 3); /* bPad */
492
0
  Stream_Read(s, rdpsnd->waveData, 4);
493
0
  rdpsnd->waveDataSize = BodySize - 8;
494
0
  format = &rdpsnd->ClientFormats[wFormatNo];
495
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG,
496
0
             "%s WaveInfo: cBlockNo: %" PRIu8 " wFormatNo: %" PRIu16 " [%s]",
497
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic), rdpsnd->cBlockNo, wFormatNo,
498
0
             audio_format_get_tag_string(format->wFormatTag));
499
500
0
  if (!rdpsnd_ensure_device_is_open(rdpsnd, wFormatNo, format))
501
0
    return ERROR_INTERNAL_ERROR;
502
503
0
  rdpsnd->expectingWave = TRUE;
504
0
  return CHANNEL_RC_OK;
505
0
}
506
507
/**
508
 * Function description
509
 *
510
 * @return 0 on success, otherwise a Win32 error code
511
 */
512
WINPR_ATTR_NODISCARD
513
static UINT rdpsnd_send_wave_confirm_pdu(rdpsndPlugin* rdpsnd, UINT16 wTimeStamp,
514
                                         BYTE cConfirmedBlockNo)
515
0
{
516
0
  wStream* pdu = nullptr;
517
0
  WINPR_ASSERT(rdpsnd);
518
0
  pdu = Stream_New(nullptr, 8);
519
520
0
  if (!pdu)
521
0
  {
522
0
    WLog_ERR(TAG, "%s Stream_New failed!", rdpsnd_is_dyn_str(rdpsnd->dynamic));
523
0
    return CHANNEL_RC_NO_MEMORY;
524
0
  }
525
526
0
  Stream_Write_UINT8(pdu, SNDC_WAVECONFIRM);
527
0
  Stream_Write_UINT8(pdu, 0);
528
0
  Stream_Write_UINT16(pdu, 4);
529
0
  Stream_Write_UINT16(pdu, wTimeStamp);
530
0
  Stream_Write_UINT8(pdu, cConfirmedBlockNo); /* cConfirmedBlockNo */
531
0
  Stream_Write_UINT8(pdu, 0);                 /* bPad */
532
0
  return rdpsnd_virtual_channel_write(rdpsnd, pdu);
533
0
}
534
535
WINPR_ATTR_NODISCARD
536
static BOOL rdpsnd_detect_overrun(rdpsndPlugin* rdpsnd, const AUDIO_FORMAT* format, size_t size)
537
0
{
538
0
  UINT32 bpf = 0;
539
0
  UINT32 now = 0;
540
0
  UINT32 duration = 0;
541
0
  UINT32 totalDuration = 0;
542
0
  UINT32 remainingDuration = 0;
543
0
  UINT32 maxDuration = 0;
544
545
0
  if (!rdpsnd || !format)
546
0
    return FALSE;
547
548
  /* Older windows RDP servers do not limit the send buffer, which can
549
   * cause quite a large amount of sound data buffered client side.
550
   * If e.g. sound is paused server side the client will keep playing
551
   * for a long time instead of pausing playback.
552
   *
553
   * To avoid this we check:
554
   *
555
   * 1. Is the sound sample received from a known format these servers
556
   *    support
557
   * 2. If it is calculate the size of the client side sound buffer
558
   * 3. If the buffer is too large silently drop the sample which will
559
   *    trigger a retransmit later on.
560
   *
561
   * This check must only be applied to these known formats, because
562
   * with newer and other formats the sample size can not be calculated
563
   * without decompressing the sample first.
564
   */
565
0
  switch (format->wFormatTag)
566
0
  {
567
0
    case WAVE_FORMAT_PCM:
568
0
    case WAVE_FORMAT_DVI_ADPCM:
569
0
    case WAVE_FORMAT_ADPCM:
570
0
    case WAVE_FORMAT_ALAW:
571
0
    case WAVE_FORMAT_MULAW:
572
0
      break;
573
0
    case WAVE_FORMAT_MSG723:
574
0
    case WAVE_FORMAT_GSM610:
575
0
    case WAVE_FORMAT_AAC_MS:
576
0
    default:
577
0
      return FALSE;
578
0
  }
579
580
0
  audio_format_print(WLog_Get(TAG), WLOG_DEBUG, format);
581
0
  bpf = format->nChannels * format->wBitsPerSample * format->nSamplesPerSec / 8;
582
0
  if (bpf == 0)
583
0
    return FALSE;
584
585
0
  duration = (UINT32)(1000 * size / bpf);
586
0
  totalDuration = (UINT32)(1000 * rdpsnd->totalPlaySize / bpf);
587
0
  now = GetTickCountPrecise();
588
0
  if (rdpsnd->startPlayTime == 0)
589
0
  {
590
0
    rdpsnd->startPlayTime = now;
591
0
    rdpsnd->totalPlaySize = size;
592
0
    return FALSE;
593
0
  }
594
0
  else if (now - rdpsnd->startPlayTime > totalDuration + 10)
595
0
  {
596
    /* Buffer underrun */
597
0
    WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s Buffer underrun by %u ms",
598
0
               rdpsnd_is_dyn_str(rdpsnd->dynamic),
599
0
               (UINT)(now - rdpsnd->startPlayTime - totalDuration));
600
0
    rdpsnd->startPlayTime = now;
601
0
    rdpsnd->totalPlaySize = size;
602
0
    return FALSE;
603
0
  }
604
0
  else
605
0
  {
606
    /* Calculate remaining duration to be played */
607
0
    remainingDuration = totalDuration - (now - rdpsnd->startPlayTime);
608
609
    /* Maximum allow duration calculation */
610
0
    maxDuration = duration * 2 + rdpsnd->latency;
611
612
0
    if (remainingDuration + duration > maxDuration)
613
0
    {
614
0
      WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s Buffer overrun pending %u ms dropping %u ms",
615
0
                 rdpsnd_is_dyn_str(rdpsnd->dynamic), remainingDuration, duration);
616
0
      return TRUE;
617
0
    }
618
619
0
    rdpsnd->totalPlaySize += size;
620
0
    return FALSE;
621
0
  }
622
0
}
623
624
WINPR_ATTR_NODISCARD
625
static UINT rdpsnd_treat_wave(rdpsndPlugin* rdpsnd, wStream* s, size_t size)
626
0
{
627
0
  AUDIO_FORMAT* format = nullptr;
628
0
  UINT64 end = 0;
629
0
  UINT64 diffMS = 0;
630
0
  UINT64 ts = 0;
631
0
  UINT latency = 0;
632
0
  UINT error = 0;
633
634
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, size))
635
0
    return ERROR_BAD_LENGTH;
636
637
0
  if (rdpsnd->wCurrentFormatNo >= rdpsnd->NumberOfClientFormats)
638
0
    return ERROR_INTERNAL_ERROR;
639
640
  /*
641
   * Send the first WaveConfirm PDU. The server side uses this to determine the
642
   * network latency.
643
   * See also [MS-RDPEA] 2.2.3.8 Wave Confirm PDU
644
   */
645
0
  error = rdpsnd_send_wave_confirm_pdu(rdpsnd, rdpsnd->wTimeStamp, rdpsnd->cBlockNo);
646
0
  if (error)
647
0
    return error;
648
649
0
  const BYTE* data = Stream_ConstPointer(s);
650
0
  format = &rdpsnd->ClientFormats[rdpsnd->wCurrentFormatNo];
651
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG,
652
0
             "%s Wave: cBlockNo: %" PRIu8 " wTimeStamp: %" PRIu16 ", size: %" PRIuz,
653
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic), rdpsnd->cBlockNo, rdpsnd->wTimeStamp, size);
654
655
0
  if (rdpsnd->device && rdpsnd->attached && !rdpsnd_detect_overrun(rdpsnd, format, size))
656
0
  {
657
0
    UINT status = CHANNEL_RC_OK;
658
0
    wStream* pcmData = StreamPool_Take(rdpsnd->pool, 4096);
659
660
0
    if (rdpsnd->device->FormatSupported(rdpsnd->device, format))
661
0
    {
662
0
      if (rdpsnd->device->PlayEx)
663
0
        latency = rdpsnd->device->PlayEx(rdpsnd->device, format, data, size);
664
0
      else
665
0
        latency = IFCALLRESULT(0, rdpsnd->device->Play, rdpsnd->device, data, size);
666
0
    }
667
0
    else if (freerdp_dsp_decode(rdpsnd->dsp_context, format, data, size, pcmData))
668
0
    {
669
0
      Stream_SealLength(pcmData);
670
671
0
      if (rdpsnd->device->PlayEx)
672
0
        latency = rdpsnd->device->PlayEx(rdpsnd->device, format, Stream_Buffer(pcmData),
673
0
                                         Stream_Length(pcmData));
674
0
      else
675
0
        latency = IFCALLRESULT(0, rdpsnd->device->Play, rdpsnd->device,
676
0
                               Stream_Buffer(pcmData), Stream_Length(pcmData));
677
0
    }
678
0
    else
679
0
      status = ERROR_INTERNAL_ERROR;
680
681
0
    Stream_Release(pcmData);
682
683
0
    if (status != CHANNEL_RC_OK)
684
0
      return status;
685
0
  }
686
687
0
  end = GetTickCount64();
688
0
  diffMS = end - rdpsnd->wArrivalTime + latency;
689
0
  ts = (rdpsnd->wTimeStamp + diffMS) % UINT16_MAX;
690
691
  /*
692
   * Send the second WaveConfirm PDU. With the first WaveConfirm PDU,
693
   * the server side uses this second WaveConfirm PDU to determine the actual
694
   * render latency.
695
   */
696
0
  return rdpsnd_send_wave_confirm_pdu(rdpsnd, (UINT16)ts, rdpsnd->cBlockNo);
697
0
}
698
699
/**
700
 * Function description
701
 *
702
 * @return 0 on success, otherwise a Win32 error code
703
 */
704
WINPR_ATTR_NODISCARD
705
static UINT rdpsnd_recv_wave_pdu(rdpsndPlugin* rdpsnd, wStream* s)
706
0
{
707
0
  rdpsnd->expectingWave = FALSE;
708
709
  /**
710
   * The Wave PDU is a special case: it is always sent after a Wave Info PDU,
711
   * and we do not process its header. Instead, the header is pad that needs
712
   * to be filled with the first four bytes of the audio sample data sent as
713
   * part of the preceding Wave Info PDU.
714
   */
715
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
716
0
    return ERROR_INVALID_DATA;
717
718
0
  CopyMemory(Stream_Buffer(s), rdpsnd->waveData, 4);
719
0
  return rdpsnd_treat_wave(rdpsnd, s, rdpsnd->waveDataSize);
720
0
}
721
722
WINPR_ATTR_NODISCARD
723
static UINT rdpsnd_recv_wave2_pdu(rdpsndPlugin* rdpsnd, wStream* s, UINT16 BodySize)
724
0
{
725
0
  UINT16 wFormatNo = 0;
726
0
  AUDIO_FORMAT* format = nullptr;
727
0
  UINT32 dwAudioTimeStamp = 0;
728
729
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 12) || (BodySize < 12))
730
0
    return ERROR_BAD_LENGTH;
731
732
0
  Stream_Read_UINT16(s, rdpsnd->wTimeStamp);
733
0
  Stream_Read_UINT16(s, wFormatNo);
734
0
  Stream_Read_UINT8(s, rdpsnd->cBlockNo);
735
0
  Stream_Seek(s, 3); /* bPad */
736
0
  Stream_Read_UINT32(s, dwAudioTimeStamp);
737
0
  if (wFormatNo >= rdpsnd->NumberOfClientFormats)
738
0
    return ERROR_INVALID_DATA;
739
0
  format = &rdpsnd->ClientFormats[wFormatNo];
740
0
  rdpsnd->waveDataSize = BodySize - 12;
741
0
  rdpsnd->wArrivalTime = GetTickCount64();
742
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG,
743
0
             "%s Wave2PDU: cBlockNo: %" PRIu8 " wFormatNo: %" PRIu16
744
0
             " [%s] , align=%hu wTimeStamp=0x%04" PRIx16 ", dwAudioTimeStamp=0x%08" PRIx32,
745
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic), rdpsnd->cBlockNo, wFormatNo,
746
0
             audio_format_get_tag_string(format->wFormatTag), format->nBlockAlign,
747
0
             rdpsnd->wTimeStamp, dwAudioTimeStamp);
748
749
0
  if (!rdpsnd_ensure_device_is_open(rdpsnd, wFormatNo, format))
750
0
    return ERROR_INTERNAL_ERROR;
751
752
0
  return rdpsnd_treat_wave(rdpsnd, s, rdpsnd->waveDataSize);
753
0
}
754
755
static void rdpsnd_recv_close_pdu(rdpsndPlugin* rdpsnd)
756
0
{
757
0
  if (rdpsnd->isOpen)
758
0
  {
759
0
    WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s Closing device",
760
0
               rdpsnd_is_dyn_str(rdpsnd->dynamic));
761
0
  }
762
0
  else
763
0
    WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s Device already closed",
764
0
               rdpsnd_is_dyn_str(rdpsnd->dynamic));
765
0
}
766
767
/**
768
 * Function description
769
 *
770
 * @return 0 on success, otherwise a Win32 error code
771
 */
772
WINPR_ATTR_NODISCARD
773
static UINT rdpsnd_recv_volume_pdu(rdpsndPlugin* rdpsnd, wStream* s)
774
0
{
775
0
  BOOL rc = TRUE;
776
0
  UINT32 dwVolume = 0;
777
778
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
779
0
    return ERROR_BAD_LENGTH;
780
781
0
  Stream_Read_UINT32(s, dwVolume);
782
0
  WLog_Print(rdpsnd->log, WLOG_DEBUG, "%s Volume: 0x%08" PRIX32 "",
783
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic), dwVolume);
784
785
0
  rdpsnd->volume = dwVolume;
786
0
  rdpsnd->applyVolume = TRUE;
787
0
  rc = rdpsnd_apply_volume(rdpsnd);
788
789
0
  if (!rc)
790
0
  {
791
0
    WLog_ERR(TAG, "%s error setting volume", rdpsnd_is_dyn_str(rdpsnd->dynamic));
792
0
    return CHANNEL_RC_INITIALIZATION_ERROR;
793
0
  }
794
795
0
  return CHANNEL_RC_OK;
796
0
}
797
798
/**
799
 * Function description
800
 *
801
 * @return 0 on success, otherwise a Win32 error code
802
 */
803
WINPR_ATTR_NODISCARD
804
static UINT rdpsnd_recv_pdu(rdpsndPlugin* rdpsnd, wStream* s)
805
0
{
806
0
  BYTE msgType = 0;
807
0
  UINT16 BodySize = 0;
808
0
  UINT status = CHANNEL_RC_OK;
809
810
0
  if (rdpsnd->expectingWave)
811
0
  {
812
0
    status = rdpsnd_recv_wave_pdu(rdpsnd, s);
813
0
    goto out;
814
0
  }
815
816
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
817
0
  {
818
0
    status = ERROR_BAD_LENGTH;
819
0
    goto out;
820
0
  }
821
822
0
  Stream_Read_UINT8(s, msgType); /* msgType */
823
0
  Stream_Seek_UINT8(s);          /* bPad */
824
0
  Stream_Read_UINT16(s, BodySize);
825
826
0
  switch (msgType)
827
0
  {
828
0
    case SNDC_FORMATS:
829
0
      status = rdpsnd_recv_server_audio_formats_pdu(rdpsnd, s);
830
0
      break;
831
832
0
    case SNDC_TRAINING:
833
0
      status = rdpsnd_recv_training_pdu(rdpsnd, s);
834
0
      break;
835
836
0
    case SNDC_WAVE:
837
0
      status = rdpsnd_recv_wave_info_pdu(rdpsnd, s, BodySize);
838
0
      break;
839
840
0
    case SNDC_CLOSE:
841
0
      rdpsnd_recv_close_pdu(rdpsnd);
842
0
      break;
843
844
0
    case SNDC_SETVOLUME:
845
0
      status = rdpsnd_recv_volume_pdu(rdpsnd, s);
846
0
      break;
847
848
0
    case SNDC_WAVE2:
849
0
      status = rdpsnd_recv_wave2_pdu(rdpsnd, s, BodySize);
850
0
      break;
851
852
0
    default:
853
0
      WLog_ERR(TAG, "%s unknown msgType %" PRIu8 "", rdpsnd_is_dyn_str(rdpsnd->dynamic),
854
0
               msgType);
855
0
      break;
856
0
  }
857
858
0
out:
859
0
  Stream_Release(s);
860
0
  return status;
861
0
}
862
863
static void rdpsnd_register_device_plugin(rdpsndPlugin* rdpsnd, rdpsndDevicePlugin* device)
864
0
{
865
0
  if (rdpsnd->device)
866
0
  {
867
0
    WLog_ERR(TAG, "%s existing device, abort.", rdpsnd_is_dyn_str(FALSE));
868
0
    return;
869
0
  }
870
871
0
  rdpsnd->device = device;
872
0
  device->rdpsnd = rdpsnd;
873
0
}
874
875
/**
876
 * Function description
877
 *
878
 * @return 0 on success, otherwise a Win32 error code
879
 */
880
WINPR_ATTR_NODISCARD
881
static UINT rdpsnd_load_device_plugin(rdpsndPlugin* rdpsnd, const char* name,
882
                                      const ADDIN_ARGV* args)
883
0
{
884
0
  FREERDP_RDPSND_DEVICE_ENTRY_POINTS entryPoints = WINPR_C_ARRAY_INIT;
885
0
  UINT error = 0;
886
0
  DWORD flags = FREERDP_ADDIN_CHANNEL_STATIC | FREERDP_ADDIN_CHANNEL_ENTRYEX;
887
0
  if (rdpsnd->dynamic)
888
0
    flags = FREERDP_ADDIN_CHANNEL_DYNAMIC;
889
0
  PVIRTUALCHANNELENTRY pvce =
890
0
      freerdp_load_channel_addin_entry(RDPSND_CHANNEL_NAME, name, nullptr, flags);
891
0
  PFREERDP_RDPSND_DEVICE_ENTRY entry = WINPR_FUNC_PTR_CAST(pvce, PFREERDP_RDPSND_DEVICE_ENTRY);
892
893
0
  if (!entry)
894
0
    return ERROR_INTERNAL_ERROR;
895
896
0
  entryPoints.rdpsnd = rdpsnd;
897
0
  entryPoints.pRegisterRdpsndDevice = rdpsnd_register_device_plugin;
898
0
  entryPoints.args = args;
899
900
0
  error = entry(&entryPoints);
901
0
  if (error)
902
0
    WLog_WARN(TAG, "%s %s entry returns error %" PRIu32 "", rdpsnd_is_dyn_str(rdpsnd->dynamic),
903
0
              name, error);
904
0
  else
905
0
    WLog_INFO(TAG, "%s Loaded %s backend for rdpsnd", rdpsnd_is_dyn_str(rdpsnd->dynamic), name);
906
907
0
  return error;
908
0
}
909
910
WINPR_ATTR_NODISCARD
911
static BOOL rdpsnd_set_subsystem(rdpsndPlugin* rdpsnd, const char* subsystem)
912
0
{
913
0
  free(rdpsnd->subsystem);
914
0
  rdpsnd->subsystem = _strdup(subsystem);
915
0
  return (rdpsnd->subsystem != nullptr);
916
0
}
917
918
WINPR_ATTR_NODISCARD
919
static BOOL rdpsnd_set_device_name(rdpsndPlugin* rdpsnd, const char* device_name)
920
0
{
921
0
  free(rdpsnd->device_name);
922
0
  rdpsnd->device_name = _strdup(device_name);
923
0
  return (rdpsnd->device_name != nullptr);
924
0
}
925
926
/**
927
 * Function description
928
 *
929
 * @return 0 on success, otherwise a Win32 error code
930
 */
931
WINPR_ATTR_NODISCARD
932
static UINT rdpsnd_process_addin_args(rdpsndPlugin* rdpsnd, const ADDIN_ARGV* args)
933
0
{
934
0
  int status = 0;
935
0
  DWORD flags = 0;
936
0
  const COMMAND_LINE_ARGUMENT_A* arg = nullptr;
937
0
  COMMAND_LINE_ARGUMENT_A rdpsnd_args[] = {
938
0
    { "sys", COMMAND_LINE_VALUE_REQUIRED, "<subsystem>", nullptr, nullptr, -1, nullptr,
939
0
      "subsystem" },
940
0
    { "dev", COMMAND_LINE_VALUE_REQUIRED, "<device>", nullptr, nullptr, -1, nullptr, "device" },
941
0
    { "format", COMMAND_LINE_VALUE_REQUIRED, "<format>", nullptr, nullptr, -1, nullptr,
942
0
      "format" },
943
0
    { "rate", COMMAND_LINE_VALUE_REQUIRED, "<rate>", nullptr, nullptr, -1, nullptr, "rate" },
944
0
    { "channel", COMMAND_LINE_VALUE_REQUIRED, "<channel>", nullptr, nullptr, -1, nullptr,
945
0
      "channel" },
946
0
    { "latency", COMMAND_LINE_VALUE_REQUIRED, "<latency>", nullptr, nullptr, -1, nullptr,
947
0
      "latency" },
948
0
    { "quality", COMMAND_LINE_VALUE_REQUIRED, "<quality mode>", nullptr, nullptr, -1, nullptr,
949
0
      "quality mode" },
950
0
    { nullptr, 0, nullptr, nullptr, nullptr, -1, nullptr, nullptr }
951
0
  };
952
0
  rdpsnd->wQualityMode = HIGH_QUALITY; /* default quality mode */
953
954
0
  if (args->argc > 1)
955
0
  {
956
0
    flags = COMMAND_LINE_SIGIL_NONE | COMMAND_LINE_SEPARATOR_COLON;
957
0
    status = CommandLineParseArgumentsA(args->argc, args->argv, rdpsnd_args, flags, rdpsnd,
958
0
                                        nullptr, nullptr);
959
960
0
    if (status < 0)
961
0
      return CHANNEL_RC_INITIALIZATION_ERROR;
962
963
0
    arg = rdpsnd_args;
964
0
    errno = 0;
965
966
0
    do
967
0
    {
968
0
      if (!(arg->Flags & COMMAND_LINE_VALUE_PRESENT))
969
0
        continue;
970
971
0
      CommandLineSwitchStart(arg) CommandLineSwitchCase(arg, "sys")
972
0
      {
973
0
        if (!rdpsnd_set_subsystem(rdpsnd, arg->Value))
974
0
          return CHANNEL_RC_NO_MEMORY;
975
0
      }
976
0
      CommandLineSwitchCase(arg, "dev")
977
0
      {
978
0
        if (!rdpsnd_set_device_name(rdpsnd, arg->Value))
979
0
          return CHANNEL_RC_NO_MEMORY;
980
0
      }
981
0
      CommandLineSwitchCase(arg, "format")
982
0
      {
983
0
        unsigned long val = strtoul(arg->Value, nullptr, 0);
984
985
0
        if ((errno != 0) || (val > UINT16_MAX))
986
0
          return CHANNEL_RC_INITIALIZATION_ERROR;
987
988
0
        rdpsnd->fixed_format->wFormatTag = (UINT16)val;
989
0
      }
990
0
      CommandLineSwitchCase(arg, "rate")
991
0
      {
992
0
        unsigned long val = strtoul(arg->Value, nullptr, 0);
993
994
0
        if ((errno != 0) || (val > UINT32_MAX))
995
0
          return CHANNEL_RC_INITIALIZATION_ERROR;
996
997
0
        rdpsnd->fixed_format->nSamplesPerSec = (UINT32)val;
998
0
      }
999
0
      CommandLineSwitchCase(arg, "channel")
1000
0
      {
1001
0
        unsigned long val = strtoul(arg->Value, nullptr, 0);
1002
1003
0
        if ((errno != 0) || (val > UINT16_MAX))
1004
0
          return CHANNEL_RC_INITIALIZATION_ERROR;
1005
1006
0
        rdpsnd->fixed_format->nChannels = (UINT16)val;
1007
0
      }
1008
0
      CommandLineSwitchCase(arg, "latency")
1009
0
      {
1010
0
        unsigned long val = strtoul(arg->Value, nullptr, 0);
1011
1012
0
        if ((errno != 0) || (val > UINT32_MAX))
1013
0
          return CHANNEL_RC_INITIALIZATION_ERROR;
1014
1015
0
        rdpsnd->latency = (UINT32)val;
1016
0
      }
1017
0
      CommandLineSwitchCase(arg, "quality")
1018
0
      {
1019
0
        long wQualityMode = DYNAMIC_QUALITY;
1020
1021
0
        if (_stricmp(arg->Value, "dynamic") == 0)
1022
0
          wQualityMode = DYNAMIC_QUALITY;
1023
0
        else if (_stricmp(arg->Value, "medium") == 0)
1024
0
          wQualityMode = MEDIUM_QUALITY;
1025
0
        else if (_stricmp(arg->Value, "high") == 0)
1026
0
          wQualityMode = HIGH_QUALITY;
1027
0
        else
1028
0
        {
1029
0
          wQualityMode = strtol(arg->Value, nullptr, 0);
1030
1031
0
          if (errno != 0)
1032
0
            return CHANNEL_RC_INITIALIZATION_ERROR;
1033
0
        }
1034
1035
0
        if ((wQualityMode < 0) || (wQualityMode > 2))
1036
0
          wQualityMode = DYNAMIC_QUALITY;
1037
1038
0
        rdpsnd->wQualityMode = (UINT16)wQualityMode;
1039
0
      }
1040
0
      CommandLineSwitchDefault(arg)
1041
0
      {
1042
0
      }
1043
0
      CommandLineSwitchEnd(arg)
1044
0
    } while ((arg = CommandLineFindNextArgumentA(arg)) != nullptr);
1045
0
  }
1046
1047
0
  return CHANNEL_RC_OK;
1048
0
}
1049
1050
/**
1051
 * Function description
1052
 *
1053
 * @return 0 on success, otherwise a Win32 error code
1054
 */
1055
WINPR_ATTR_NODISCARD
1056
static UINT rdpsnd_process_connect(rdpsndPlugin* rdpsnd)
1057
0
{
1058
0
  const struct
1059
0
  {
1060
0
    const char* subsystem;
1061
0
    const char* device;
1062
0
  } backends[] = {
1063
#if defined(WITH_IOSAUDIO)
1064
    { "ios", "" },
1065
#endif
1066
#if defined(WITH_AAUDIO)
1067
    { "aaudio", "" },
1068
#endif
1069
#if defined(WITH_OPENSLES)
1070
    { "opensles", "" },
1071
#endif
1072
#if defined(WITH_PULSE)
1073
    { "pulse", "" },
1074
#endif
1075
#if defined(WITH_ALSA)
1076
    { "alsa", "default" },
1077
#endif
1078
#if defined(WITH_OSS)
1079
    { "oss", "" },
1080
#endif
1081
#if defined(WITH_MACAUDIO)
1082
    { "mac", "default" },
1083
#endif
1084
#if defined(WITH_WINMM)
1085
    { "winmm", "" },
1086
#endif
1087
#if defined(WITH_SNDIO)
1088
    { "sndio", "" },
1089
#endif
1090
0
    { "fake", "" }
1091
0
  };
1092
0
  const ADDIN_ARGV* args = nullptr;
1093
0
  UINT status = ERROR_INTERNAL_ERROR;
1094
0
  WINPR_ASSERT(rdpsnd);
1095
0
  rdpsnd->latency = 0;
1096
0
  args = (const ADDIN_ARGV*)rdpsnd->channelEntryPoints.pExtendedData;
1097
1098
0
  if (args)
1099
0
  {
1100
0
    status = rdpsnd_process_addin_args(rdpsnd, args);
1101
1102
0
    if (status != CHANNEL_RC_OK)
1103
0
      return status;
1104
0
  }
1105
1106
0
  if (rdpsnd->subsystem)
1107
0
  {
1108
0
    if ((status = rdpsnd_load_device_plugin(rdpsnd, rdpsnd->subsystem, args)))
1109
0
    {
1110
0
      WLog_ERR(TAG,
1111
0
               "%s Unable to load sound playback subsystem %s because of error %" PRIu32 "",
1112
0
               rdpsnd_is_dyn_str(rdpsnd->dynamic), rdpsnd->subsystem, status);
1113
0
      return status;
1114
0
    }
1115
0
  }
1116
0
  else
1117
0
  {
1118
0
    for (size_t x = 0; x < ARRAYSIZE(backends); x++)
1119
0
    {
1120
0
      const char* subsystem_name = backends[x].subsystem;
1121
0
      const char* device_name = backends[x].device;
1122
1123
0
      if ((status = rdpsnd_load_device_plugin(rdpsnd, subsystem_name, args)))
1124
0
        WLog_WARN(TAG,
1125
0
                  "%s Unable to load sound playback subsystem %s because of error %" PRIu32
1126
0
                  "",
1127
0
                  rdpsnd_is_dyn_str(rdpsnd->dynamic), subsystem_name, status);
1128
1129
0
      if (!rdpsnd->device)
1130
0
        continue;
1131
1132
0
      if (!rdpsnd_set_subsystem(rdpsnd, subsystem_name) ||
1133
0
          !rdpsnd_set_device_name(rdpsnd, device_name))
1134
0
        return CHANNEL_RC_NO_MEMORY;
1135
1136
0
      break;
1137
0
    }
1138
1139
0
    if (!rdpsnd->device || status)
1140
0
      return CHANNEL_RC_INITIALIZATION_ERROR;
1141
0
  }
1142
1143
0
  return CHANNEL_RC_OK;
1144
0
}
1145
1146
/**
1147
 * Function description
1148
 *
1149
 * @return 0 on success, otherwise a Win32 error code
1150
 */
1151
UINT rdpsnd_virtual_channel_write(rdpsndPlugin* rdpsnd, wStream* s)
1152
0
{
1153
0
  UINT status = CHANNEL_RC_BAD_INIT_HANDLE;
1154
1155
0
  if (rdpsnd)
1156
0
  {
1157
0
    if (rdpsnd->dynamic)
1158
0
    {
1159
0
      if (rdpsnd->listener_callback && rdpsnd->connected)
1160
0
      {
1161
0
        IWTSVirtualChannel* channel = rdpsnd->listener_callback->channel_callback->channel;
1162
0
        status =
1163
0
            channel->Write(channel, (UINT32)Stream_Length(s), Stream_Buffer(s), nullptr);
1164
0
      }
1165
0
      Stream_Free(s, TRUE);
1166
0
    }
1167
0
    else
1168
0
    {
1169
0
      status = rdpsnd->channelEntryPoints.pVirtualChannelWriteEx(
1170
0
          rdpsnd->InitHandle, rdpsnd->OpenHandle, Stream_Buffer(s),
1171
0
          (UINT32)Stream_GetPosition(s), s);
1172
1173
0
      if (status != CHANNEL_RC_OK)
1174
0
      {
1175
0
        Stream_Free(s, TRUE);
1176
0
        WLog_ERR(TAG, "%s pVirtualChannelWriteEx failed with %s [%08" PRIX32 "]",
1177
0
                 rdpsnd_is_dyn_str(FALSE), WTSErrorToString(status), status);
1178
0
      }
1179
0
    }
1180
0
  }
1181
1182
0
  return status;
1183
0
}
1184
1185
/**
1186
 * Function description
1187
 *
1188
 * @return 0 on success, otherwise a Win32 error code
1189
 */
1190
WINPR_ATTR_NODISCARD
1191
static UINT rdpsnd_virtual_channel_event_data_received(rdpsndPlugin* plugin, void* pData,
1192
                                                       UINT32 dataLength, UINT32 totalLength,
1193
                                                       UINT32 dataFlags)
1194
0
{
1195
0
  if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME))
1196
0
    return CHANNEL_RC_OK;
1197
1198
0
  if (dataFlags & CHANNEL_FLAG_FIRST)
1199
0
  {
1200
0
    if (plugin->firstFlagReceived)
1201
0
      return ERROR_INVALID_DATA;
1202
0
    plugin->firstFlagReceived = TRUE;
1203
1204
0
    if (!plugin->data_in)
1205
0
      plugin->data_in = StreamPool_Take(plugin->pool, dataLength);
1206
1207
0
    Stream_ResetPosition(plugin->data_in);
1208
0
    plugin->totalLength = totalLength;
1209
0
  }
1210
1211
0
  if (!plugin->data_in)
1212
0
    return ERROR_INVALID_DATA;
1213
1214
0
  if (!Stream_EnsureRemainingCapacity(plugin->data_in, dataLength))
1215
0
    return CHANNEL_RC_NO_MEMORY;
1216
1217
0
  Stream_Write(plugin->data_in, pData, dataLength);
1218
1219
0
  if ((Stream_GetPosition(plugin->data_in) > totalLength) || (totalLength != plugin->totalLength))
1220
0
    return ERROR_INVALID_DATA;
1221
1222
0
  if (dataFlags & CHANNEL_FLAG_LAST)
1223
0
  {
1224
0
    if (!plugin->firstFlagReceived)
1225
0
      return ERROR_INVALID_DATA;
1226
0
    if (Stream_GetPosition(plugin->data_in) != totalLength)
1227
0
      return ERROR_INVALID_DATA;
1228
0
    plugin->firstFlagReceived = FALSE;
1229
1230
0
    Stream_SealLength(plugin->data_in);
1231
0
    Stream_ResetPosition(plugin->data_in);
1232
0
    plugin->totalLength = 0;
1233
1234
0
    if (plugin->async)
1235
0
    {
1236
0
      if (!MessageQueue_Post(plugin->queue, nullptr, 0, plugin->data_in, nullptr))
1237
0
        return ERROR_INTERNAL_ERROR;
1238
0
      plugin->data_in = nullptr;
1239
0
    }
1240
0
    else
1241
0
    {
1242
0
      UINT error = rdpsnd_recv_pdu(plugin, plugin->data_in);
1243
0
      plugin->data_in = nullptr;
1244
0
      if (error)
1245
0
        return error;
1246
0
    }
1247
0
  }
1248
1249
0
  return CHANNEL_RC_OK;
1250
0
}
1251
1252
static VOID VCAPITYPE rdpsnd_virtual_channel_open_event_ex(LPVOID lpUserParam, DWORD openHandle,
1253
                                                           UINT event, LPVOID pData,
1254
                                                           UINT32 dataLength, UINT32 totalLength,
1255
                                                           UINT32 dataFlags)
1256
0
{
1257
0
  UINT error = CHANNEL_RC_OK;
1258
0
  rdpsndPlugin* rdpsnd = (rdpsndPlugin*)lpUserParam;
1259
0
  WINPR_ASSERT(rdpsnd);
1260
0
  WINPR_ASSERT(!rdpsnd->dynamic);
1261
1262
0
  switch (event)
1263
0
  {
1264
0
    case CHANNEL_EVENT_DATA_RECEIVED:
1265
0
      if (!rdpsnd)
1266
0
        return;
1267
1268
0
      if (rdpsnd->OpenHandle != openHandle)
1269
0
      {
1270
0
        WLog_ERR(TAG, "%s error no match", rdpsnd_is_dyn_str(rdpsnd->dynamic));
1271
0
        return;
1272
0
      }
1273
0
      if ((error = rdpsnd_virtual_channel_event_data_received(rdpsnd, pData, dataLength,
1274
0
                                                              totalLength, dataFlags)))
1275
0
        WLog_ERR(TAG,
1276
0
                 "%s rdpsnd_virtual_channel_event_data_received failed with error %" PRIu32
1277
0
                 "",
1278
0
                 rdpsnd_is_dyn_str(rdpsnd->dynamic), error);
1279
1280
0
      break;
1281
1282
0
    case CHANNEL_EVENT_WRITE_CANCELLED:
1283
0
    case CHANNEL_EVENT_WRITE_COMPLETE:
1284
0
    {
1285
0
      wStream* s = (wStream*)pData;
1286
0
      Stream_Free(s, TRUE);
1287
0
    }
1288
0
    break;
1289
1290
0
    case CHANNEL_EVENT_USER:
1291
0
      break;
1292
0
    default:
1293
0
      break;
1294
0
  }
1295
1296
0
  if (error && rdpsnd && rdpsnd->rdpcontext)
1297
0
  {
1298
0
    char buffer[8192];
1299
0
    (void)_snprintf(buffer, sizeof(buffer),
1300
0
                    "%s rdpsnd_virtual_channel_open_event_ex reported an error",
1301
0
                    rdpsnd_is_dyn_str(rdpsnd->dynamic));
1302
0
    setChannelError(rdpsnd->rdpcontext, error, buffer);
1303
0
  }
1304
0
}
1305
1306
/**
1307
 * Function description
1308
 *
1309
 * @return 0 on success, otherwise a Win32 error code
1310
 */
1311
WINPR_ATTR_NODISCARD
1312
static UINT rdpsnd_virtual_channel_event_connected(rdpsndPlugin* rdpsnd, LPVOID pData,
1313
                                                   UINT32 dataLength)
1314
0
{
1315
0
  UINT32 status = 0;
1316
0
  DWORD opened = 0;
1317
0
  WINPR_UNUSED(pData);
1318
0
  WINPR_UNUSED(dataLength);
1319
1320
0
  WINPR_ASSERT(rdpsnd);
1321
0
  WINPR_ASSERT(!rdpsnd->dynamic);
1322
1323
0
  status = rdpsnd->channelEntryPoints.pVirtualChannelOpenEx(
1324
0
      rdpsnd->InitHandle, &opened, rdpsnd->channelDef.name, rdpsnd_virtual_channel_open_event_ex);
1325
1326
0
  if (status != CHANNEL_RC_OK)
1327
0
  {
1328
0
    WLog_ERR(TAG, "%s pVirtualChannelOpenEx failed with %s [%08" PRIX32 "]",
1329
0
             rdpsnd_is_dyn_str(rdpsnd->dynamic), WTSErrorToString(status), status);
1330
0
    goto fail;
1331
0
  }
1332
1333
0
  if (rdpsnd_process_connect(rdpsnd) != CHANNEL_RC_OK)
1334
0
    goto fail;
1335
1336
0
  rdpsnd->OpenHandle = opened;
1337
0
  return CHANNEL_RC_OK;
1338
0
fail:
1339
0
  if (opened != 0)
1340
0
    rdpsnd->channelEntryPoints.pVirtualChannelCloseEx(rdpsnd->InitHandle, opened);
1341
0
  return CHANNEL_RC_NO_MEMORY;
1342
0
}
1343
1344
static void rdpsnd_terminate_thread(rdpsndPlugin* rdpsnd)
1345
0
{
1346
0
  WINPR_ASSERT(rdpsnd);
1347
0
  if (rdpsnd->async)
1348
0
  {
1349
0
    if (rdpsnd->queue)
1350
0
      MessageQueue_PostQuit(rdpsnd->queue, 0);
1351
1352
0
    if (rdpsnd->thread)
1353
0
    {
1354
0
      (void)WaitForSingleObject(rdpsnd->thread, INFINITE);
1355
0
      (void)CloseHandle(rdpsnd->thread);
1356
0
    }
1357
0
    DeleteCriticalSection(&rdpsnd->asyncLock);
1358
0
    MessageQueue_Free(rdpsnd->queue);
1359
0
  }
1360
0
  rdpsnd->thread = nullptr;
1361
0
  rdpsnd->queue = nullptr;
1362
0
}
1363
1364
static void cleanup_internals(rdpsndPlugin* rdpsnd)
1365
0
{
1366
0
  if (!rdpsnd)
1367
0
    return;
1368
1369
0
  if (rdpsnd->async)
1370
0
    EnterCriticalSection(&rdpsnd->asyncLock);
1371
1372
0
  if (rdpsnd->pool)
1373
0
    StreamPool_Return(rdpsnd->pool, rdpsnd->data_in);
1374
1375
0
  audio_formats_free(rdpsnd->ClientFormats, rdpsnd->NumberOfClientFormats);
1376
0
  audio_formats_free(rdpsnd->ServerFormats, rdpsnd->NumberOfServerFormats);
1377
1378
0
  rdpsnd->NumberOfClientFormats = 0;
1379
0
  rdpsnd->ClientFormats = nullptr;
1380
0
  rdpsnd->NumberOfServerFormats = 0;
1381
0
  rdpsnd->ServerFormats = nullptr;
1382
1383
0
  rdpsnd->data_in = nullptr;
1384
1385
0
  if (rdpsnd->async)
1386
0
    LeaveCriticalSection(&rdpsnd->asyncLock);
1387
0
}
1388
1389
/**
1390
 * Function description
1391
 *
1392
 * @return 0 on success, otherwise a Win32 error code
1393
 */
1394
WINPR_ATTR_NODISCARD
1395
static UINT rdpsnd_virtual_channel_event_disconnected(rdpsndPlugin* rdpsnd)
1396
0
{
1397
0
  UINT error = 0;
1398
1399
0
  WINPR_ASSERT(rdpsnd);
1400
0
  WINPR_ASSERT(!rdpsnd->dynamic);
1401
0
  if (rdpsnd->OpenHandle != 0)
1402
0
  {
1403
0
    DWORD opened = rdpsnd->OpenHandle;
1404
0
    rdpsnd->OpenHandle = 0;
1405
0
    if (rdpsnd->device)
1406
0
      IFCALL(rdpsnd->device->Close, rdpsnd->device);
1407
1408
0
    error = rdpsnd->channelEntryPoints.pVirtualChannelCloseEx(rdpsnd->InitHandle, opened);
1409
1410
0
    if (CHANNEL_RC_OK != error)
1411
0
    {
1412
0
      WLog_ERR(TAG, "%s pVirtualChannelCloseEx failed with %s [%08" PRIX32 "]",
1413
0
               rdpsnd_is_dyn_str(rdpsnd->dynamic), WTSErrorToString(error), error);
1414
0
      return error;
1415
0
    }
1416
0
  }
1417
1418
0
  cleanup_internals(rdpsnd);
1419
1420
0
  if (rdpsnd->device)
1421
0
  {
1422
0
    IFCALL(rdpsnd->device->Free, rdpsnd->device);
1423
0
    rdpsnd->device = nullptr;
1424
0
  }
1425
1426
0
  return CHANNEL_RC_OK;
1427
0
}
1428
1429
static void queue_free(void* obj)
1430
0
{
1431
0
  wMessage* msg = obj;
1432
0
  if (!msg)
1433
0
    return;
1434
0
  if (msg->id != 0)
1435
0
    return;
1436
0
  wStream* s = msg->wParam;
1437
0
  Stream_Release(s);
1438
0
}
1439
1440
static void free_internals(rdpsndPlugin* rdpsnd)
1441
0
{
1442
0
  if (!rdpsnd)
1443
0
    return;
1444
1445
0
  if (rdpsnd->references > 0)
1446
0
    rdpsnd->references--;
1447
1448
0
  if (rdpsnd->references > 0)
1449
0
    return;
1450
1451
0
  rdpsnd_terminate_thread(rdpsnd);
1452
0
  freerdp_dsp_context_free(rdpsnd->dsp_context);
1453
0
  StreamPool_Free(rdpsnd->pool);
1454
0
  rdpsnd->pool = nullptr;
1455
0
  rdpsnd->dsp_context = nullptr;
1456
0
}
1457
1458
WINPR_ATTR_NODISCARD
1459
static BOOL allocate_internals(rdpsndPlugin* rdpsnd)
1460
0
{
1461
0
  WINPR_ASSERT(rdpsnd);
1462
1463
0
  if (!rdpsnd->pool)
1464
0
  {
1465
0
    rdpsnd->pool = StreamPool_New(TRUE, 4096);
1466
0
    if (!rdpsnd->pool)
1467
0
      return FALSE;
1468
0
  }
1469
1470
0
  if (!rdpsnd->dsp_context)
1471
0
  {
1472
0
    rdpsnd->dsp_context = freerdp_dsp_context_new(FALSE);
1473
0
    if (!rdpsnd->dsp_context)
1474
0
      return FALSE;
1475
0
  }
1476
1477
0
  if (rdpsnd->async)
1478
0
  {
1479
0
    if (!rdpsnd->queue)
1480
0
    {
1481
0
      wObject obj = WINPR_C_ARRAY_INIT;
1482
1483
0
      obj.fnObjectFree = queue_free;
1484
0
      rdpsnd->queue = MessageQueue_New(&obj);
1485
0
      if (!rdpsnd->queue)
1486
0
        return CHANNEL_RC_NO_MEMORY;
1487
0
      InitializeCriticalSection(&rdpsnd->asyncLock);
1488
0
    }
1489
1490
0
    if (!rdpsnd->thread)
1491
0
    {
1492
0
      rdpsnd->thread = CreateThread(nullptr, 0, play_thread, rdpsnd, 0, nullptr);
1493
0
      if (!rdpsnd->thread)
1494
0
        return CHANNEL_RC_INITIALIZATION_ERROR;
1495
0
    }
1496
0
  }
1497
1498
0
  rdpsnd->references++;
1499
1500
0
  return TRUE;
1501
0
}
1502
1503
WINPR_ATTR_NODISCARD
1504
static DWORD WINAPI play_thread(LPVOID arg)
1505
0
{
1506
0
  UINT error = CHANNEL_RC_OK;
1507
0
  rdpsndPlugin* rdpsnd = arg;
1508
1509
0
  if (!rdpsnd || !rdpsnd->queue)
1510
0
    return ERROR_INVALID_PARAMETER;
1511
1512
0
  while (TRUE)
1513
0
  {
1514
0
    int rc = -1;
1515
0
    wMessage message = WINPR_C_ARRAY_INIT;
1516
0
    wStream* s = nullptr;
1517
0
    DWORD status = 0;
1518
0
    DWORD nCount = 0;
1519
0
    HANDLE handles[MAXIMUM_WAIT_OBJECTS] = WINPR_C_ARRAY_INIT;
1520
1521
0
    handles[nCount++] = MessageQueue_Event(rdpsnd->queue);
1522
0
    handles[nCount++] = freerdp_abort_event(rdpsnd->rdpcontext);
1523
0
    status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);
1524
0
    switch (status)
1525
0
    {
1526
0
      case WAIT_OBJECT_0:
1527
0
        break;
1528
0
      default:
1529
0
        return ERROR_TIMEOUT;
1530
0
    }
1531
1532
0
    rc = MessageQueue_Peek(rdpsnd->queue, &message, TRUE);
1533
0
    if (rc < 1)
1534
0
      continue;
1535
1536
0
    if (message.id == WMQ_QUIT)
1537
0
      break;
1538
1539
0
    if (rdpsnd->async)
1540
0
      EnterCriticalSection(&rdpsnd->asyncLock);
1541
1542
0
    s = message.wParam;
1543
0
    error = rdpsnd_recv_pdu(rdpsnd, s);
1544
1545
0
    if (rdpsnd->async)
1546
0
      LeaveCriticalSection(&rdpsnd->asyncLock);
1547
1548
0
    if (error)
1549
0
      return error;
1550
0
  }
1551
1552
0
  return CHANNEL_RC_OK;
1553
0
}
1554
1555
WINPR_ATTR_NODISCARD
1556
static UINT rdpsnd_virtual_channel_event_initialized(rdpsndPlugin* rdpsnd)
1557
0
{
1558
0
  if (!rdpsnd)
1559
0
    return ERROR_INVALID_PARAMETER;
1560
1561
0
  if (!allocate_internals(rdpsnd))
1562
0
    return CHANNEL_RC_NO_MEMORY;
1563
1564
0
  return CHANNEL_RC_OK;
1565
0
}
1566
1567
void rdpsnd_virtual_channel_event_terminated(rdpsndPlugin* rdpsnd)
1568
0
{
1569
0
  if (rdpsnd)
1570
0
  {
1571
0
    free_internals(rdpsnd);
1572
0
    audio_formats_free(rdpsnd->fixed_format, 1);
1573
0
    free(rdpsnd->subsystem);
1574
0
    free(rdpsnd->device_name);
1575
0
    rdpsnd->InitHandle = nullptr;
1576
0
  }
1577
1578
0
  free(rdpsnd);
1579
0
}
1580
1581
static VOID VCAPITYPE rdpsnd_virtual_channel_init_event_ex(LPVOID lpUserParam, LPVOID pInitHandle,
1582
                                                           UINT event, LPVOID pData,
1583
                                                           UINT dataLength)
1584
0
{
1585
0
  UINT error = CHANNEL_RC_OK;
1586
0
  rdpsndPlugin* plugin = (rdpsndPlugin*)lpUserParam;
1587
1588
0
  if (!plugin)
1589
0
    return;
1590
1591
0
  if (plugin->InitHandle != pInitHandle)
1592
0
  {
1593
0
    WLog_ERR(TAG, "%s error no match", rdpsnd_is_dyn_str(plugin->dynamic));
1594
0
    return;
1595
0
  }
1596
1597
0
  switch (event)
1598
0
  {
1599
0
    case CHANNEL_EVENT_INITIALIZED:
1600
0
      error = rdpsnd_virtual_channel_event_initialized(plugin);
1601
0
      break;
1602
1603
0
    case CHANNEL_EVENT_CONNECTED:
1604
0
      error = rdpsnd_virtual_channel_event_connected(plugin, pData, dataLength);
1605
0
      break;
1606
1607
0
    case CHANNEL_EVENT_DISCONNECTED:
1608
0
      error = rdpsnd_virtual_channel_event_disconnected(plugin);
1609
0
      break;
1610
1611
0
    case CHANNEL_EVENT_TERMINATED:
1612
0
      rdpsnd_virtual_channel_event_terminated(plugin);
1613
0
      plugin = nullptr;
1614
0
      break;
1615
1616
0
    case CHANNEL_EVENT_ATTACHED:
1617
0
      plugin->attached = TRUE;
1618
0
      break;
1619
1620
0
    case CHANNEL_EVENT_DETACHED:
1621
0
      plugin->attached = FALSE;
1622
0
      break;
1623
1624
0
    default:
1625
0
      break;
1626
0
  }
1627
1628
0
  if (error && plugin && plugin->rdpcontext)
1629
0
  {
1630
0
    char buffer[8192];
1631
0
    (void)_snprintf(buffer, sizeof(buffer), "%s reported an error",
1632
0
                    rdpsnd_is_dyn_str(plugin->dynamic));
1633
0
    setChannelError(plugin->rdpcontext, error, buffer);
1634
0
  }
1635
0
}
1636
1637
rdpContext* freerdp_rdpsnd_get_context(rdpsndPlugin* plugin)
1638
0
{
1639
0
  if (!plugin)
1640
0
    return nullptr;
1641
1642
0
  return plugin->rdpcontext;
1643
0
}
1644
1645
WINPR_ATTR_NODISCARD
1646
static rdpsndPlugin* allocatePlugin(void)
1647
0
{
1648
0
  rdpsndPlugin* rdpsnd = (rdpsndPlugin*)calloc(1, sizeof(rdpsndPlugin));
1649
0
  if (!rdpsnd)
1650
0
    goto fail;
1651
1652
0
  rdpsnd->fixed_format = audio_format_new();
1653
0
  if (!rdpsnd->fixed_format)
1654
0
    goto fail;
1655
0
  rdpsnd->log = WLog_Get("com.freerdp.channels.rdpsnd.client");
1656
0
  if (!rdpsnd->log)
1657
0
    goto fail;
1658
1659
0
  rdpsnd->attached = TRUE;
1660
0
  return rdpsnd;
1661
1662
0
fail:
1663
0
  if (rdpsnd)
1664
0
    audio_formats_free(rdpsnd->fixed_format, 1);
1665
0
  free(rdpsnd);
1666
0
  return nullptr;
1667
0
}
1668
/* rdpsnd is always built-in */
1669
FREERDP_ENTRY_POINT(BOOL VCAPITYPE rdpsnd_VirtualChannelEntryEx(
1670
    PCHANNEL_ENTRY_POINTS_EX pEntryPoints, PVOID pInitHandle))
1671
0
{
1672
0
  UINT rc = 0;
1673
0
  CHANNEL_ENTRY_POINTS_FREERDP_EX* pEntryPointsEx = nullptr;
1674
1675
0
  if (!pEntryPoints)
1676
0
    return FALSE;
1677
1678
0
  rdpsndPlugin* rdpsnd = allocatePlugin();
1679
1680
0
  if (!rdpsnd)
1681
0
    return FALSE;
1682
1683
0
  rdpsnd->channelDef.options = CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP;
1684
0
  (void)sprintf_s(rdpsnd->channelDef.name, ARRAYSIZE(rdpsnd->channelDef.name),
1685
0
                  RDPSND_CHANNEL_NAME);
1686
0
  pEntryPointsEx = (CHANNEL_ENTRY_POINTS_FREERDP_EX*)pEntryPoints;
1687
1688
0
  if ((pEntryPointsEx->cbSize >= sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX)) &&
1689
0
      (pEntryPointsEx->MagicNumber == FREERDP_CHANNEL_MAGIC_NUMBER))
1690
0
  {
1691
0
    rdpsnd->rdpcontext = pEntryPointsEx->context;
1692
0
    if (!freerdp_settings_get_bool(rdpsnd->rdpcontext->settings,
1693
0
                                   FreeRDP_SynchronousStaticChannels))
1694
0
      rdpsnd->async = TRUE;
1695
0
  }
1696
1697
0
  CopyMemory(&(rdpsnd->channelEntryPoints), pEntryPoints,
1698
0
             sizeof(CHANNEL_ENTRY_POINTS_FREERDP_EX));
1699
0
  rdpsnd->InitHandle = pInitHandle;
1700
1701
0
  WINPR_ASSERT(rdpsnd->channelEntryPoints.pVirtualChannelInitEx);
1702
0
  rc = rdpsnd->channelEntryPoints.pVirtualChannelInitEx(
1703
0
      rdpsnd, nullptr, pInitHandle, &rdpsnd->channelDef, 1, VIRTUAL_CHANNEL_VERSION_WIN2000,
1704
0
      rdpsnd_virtual_channel_init_event_ex);
1705
1706
0
  if (CHANNEL_RC_OK != rc)
1707
0
  {
1708
0
    WLog_ERR(TAG, "%s pVirtualChannelInitEx failed with %s [%08" PRIX32 "]",
1709
0
             rdpsnd_is_dyn_str(FALSE), WTSErrorToString(rc), rc);
1710
0
    rdpsnd_virtual_channel_event_terminated(rdpsnd);
1711
0
    return FALSE;
1712
0
  }
1713
1714
0
  return TRUE;
1715
0
}
1716
1717
WINPR_ATTR_NODISCARD
1718
static UINT rdpsnd_on_open(IWTSVirtualChannelCallback* pChannelCallback)
1719
0
{
1720
0
  GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback;
1721
0
  rdpsndPlugin* rdpsnd = nullptr;
1722
1723
0
  WINPR_ASSERT(callback);
1724
1725
0
  rdpsnd = (rdpsndPlugin*)callback->plugin;
1726
0
  WINPR_ASSERT(rdpsnd);
1727
1728
0
  if (rdpsnd->OnOpenCalled)
1729
0
    return CHANNEL_RC_OK;
1730
0
  rdpsnd->OnOpenCalled = TRUE;
1731
1732
0
  if (!allocate_internals(rdpsnd))
1733
0
    return ERROR_OUTOFMEMORY;
1734
1735
0
  return rdpsnd_process_connect(rdpsnd);
1736
0
}
1737
1738
WINPR_ATTR_NODISCARD
1739
static UINT rdpsnd_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data)
1740
0
{
1741
0
  GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback;
1742
0
  rdpsndPlugin* plugin = nullptr;
1743
0
  wStream* copy = nullptr;
1744
0
  size_t len = 0;
1745
1746
0
  len = Stream_GetRemainingLength(data);
1747
1748
0
  if (!callback || !callback->plugin)
1749
0
    return ERROR_INVALID_PARAMETER;
1750
0
  plugin = (rdpsndPlugin*)callback->plugin;
1751
0
  WINPR_ASSERT(plugin);
1752
1753
0
  copy = StreamPool_Take(plugin->pool, len);
1754
0
  if (!copy)
1755
0
    return ERROR_OUTOFMEMORY;
1756
0
  Stream_Copy(data, copy, len);
1757
0
  Stream_SealLength(copy);
1758
0
  Stream_ResetPosition(copy);
1759
1760
0
  if (plugin->async)
1761
0
  {
1762
0
    if (!MessageQueue_Post(plugin->queue, nullptr, 0, copy, nullptr))
1763
0
    {
1764
0
      Stream_Release(copy);
1765
0
      return ERROR_INTERNAL_ERROR;
1766
0
    }
1767
0
  }
1768
0
  else
1769
0
  {
1770
0
    UINT error = rdpsnd_recv_pdu(plugin, copy);
1771
0
    if (error)
1772
0
      return error;
1773
0
  }
1774
1775
0
  return CHANNEL_RC_OK;
1776
0
}
1777
1778
WINPR_ATTR_NODISCARD
1779
static UINT rdpsnd_on_close(IWTSVirtualChannelCallback* pChannelCallback)
1780
0
{
1781
0
  GENERIC_CHANNEL_CALLBACK* callback = (GENERIC_CHANNEL_CALLBACK*)pChannelCallback;
1782
1783
0
  WINPR_ASSERT(callback);
1784
1785
0
  rdpsndPlugin* rdpsnd = (rdpsndPlugin*)callback->plugin;
1786
0
  WINPR_ASSERT(rdpsnd);
1787
1788
0
  rdpsnd->OnOpenCalled = FALSE;
1789
0
  if (rdpsnd->device)
1790
0
    IFCALL(rdpsnd->device->Close, rdpsnd->device);
1791
1792
0
  cleanup_internals(rdpsnd);
1793
1794
0
  free_internals(rdpsnd);
1795
0
  if (rdpsnd->device)
1796
0
  {
1797
0
    IFCALL(rdpsnd->device->Free, rdpsnd->device);
1798
0
    rdpsnd->device = nullptr;
1799
0
  }
1800
1801
0
  free(pChannelCallback);
1802
0
  rdpsnd->connected = FALSE;
1803
0
  return CHANNEL_RC_OK;
1804
0
}
1805
1806
// NOLINTBEGIN(readability-non-const-parameter)
1807
WINPR_ATTR_NODISCARD
1808
static UINT rdpsnd_on_new_channel_connection(IWTSListenerCallback* pListenerCallback,
1809
                                             IWTSVirtualChannel* pChannel, BYTE* Data,
1810
                                             BOOL* pbAccept,
1811
                                             IWTSVirtualChannelCallback** ppCallback)
1812
// NOLINTEND(readability-non-const-parameter)
1813
0
{
1814
0
  GENERIC_LISTENER_CALLBACK* listener_callback = (GENERIC_LISTENER_CALLBACK*)pListenerCallback;
1815
0
  WINPR_ASSERT(listener_callback);
1816
0
  WINPR_ASSERT(pChannel);
1817
0
  WINPR_ASSERT(ppCallback);
1818
1819
0
  rdpsndPlugin* rdpsnd = (rdpsndPlugin*)listener_callback->plugin;
1820
0
  WINPR_ASSERT(rdpsnd);
1821
1822
0
  if (rdpsnd->connected)
1823
0
  {
1824
0
    WLog_Print(rdpsnd->log, WLOG_ERROR, "Channel already connected, terminating.");
1825
0
    return ERROR_DEVICE_ALREADY_ATTACHED;
1826
0
  }
1827
1828
0
  GENERIC_CHANNEL_CALLBACK* callback =
1829
0
      (GENERIC_CHANNEL_CALLBACK*)calloc(1, sizeof(GENERIC_CHANNEL_CALLBACK));
1830
1831
0
  WINPR_UNUSED(Data);
1832
0
  WINPR_UNUSED(pbAccept);
1833
1834
0
  if (!callback)
1835
0
  {
1836
0
    WLog_ERR(TAG, "%s calloc failed!", rdpsnd_is_dyn_str(TRUE));
1837
0
    return CHANNEL_RC_NO_MEMORY;
1838
0
  }
1839
1840
0
  callback->iface.OnOpen = rdpsnd_on_open;
1841
0
  callback->iface.OnDataReceived = rdpsnd_on_data_received;
1842
0
  callback->iface.OnClose = rdpsnd_on_close;
1843
0
  callback->plugin = listener_callback->plugin;
1844
0
  callback->channel_mgr = listener_callback->channel_mgr;
1845
0
  callback->channel = pChannel;
1846
0
  listener_callback->channel_callback = callback;
1847
0
  *ppCallback = &callback->iface;
1848
0
  rdpsnd->connected = TRUE;
1849
0
  return CHANNEL_RC_OK;
1850
0
}
1851
1852
WINPR_ATTR_NODISCARD
1853
static UINT rdpsnd_plugin_initialize(IWTSPlugin* pPlugin, IWTSVirtualChannelManager* pChannelMgr)
1854
0
{
1855
0
  UINT status = 0;
1856
0
  rdpsndPlugin* rdpsnd = (rdpsndPlugin*)pPlugin;
1857
0
  WINPR_ASSERT(rdpsnd);
1858
0
  WINPR_ASSERT(pChannelMgr);
1859
0
  if (rdpsnd->initialized)
1860
0
  {
1861
0
    WLog_ERR(TAG, "[%s] channel initialized twice, aborting", RDPSND_DVC_CHANNEL_NAME);
1862
0
    return ERROR_INVALID_DATA;
1863
0
  }
1864
0
  rdpsnd->listener_callback =
1865
0
      (GENERIC_LISTENER_CALLBACK*)calloc(1, sizeof(GENERIC_LISTENER_CALLBACK));
1866
1867
0
  if (!rdpsnd->listener_callback)
1868
0
  {
1869
0
    WLog_ERR(TAG, "%s calloc failed!", rdpsnd_is_dyn_str(TRUE));
1870
0
    return CHANNEL_RC_NO_MEMORY;
1871
0
  }
1872
1873
0
  rdpsnd->listener_callback->iface.OnNewChannelConnection = rdpsnd_on_new_channel_connection;
1874
0
  rdpsnd->listener_callback->plugin = pPlugin;
1875
0
  rdpsnd->listener_callback->channel_mgr = pChannelMgr;
1876
0
  status = pChannelMgr->CreateListener(pChannelMgr, RDPSND_DVC_CHANNEL_NAME, 0,
1877
0
                                       &rdpsnd->listener_callback->iface, &(rdpsnd->listener));
1878
0
  if (status != CHANNEL_RC_OK)
1879
0
  {
1880
0
    WLog_ERR(TAG, "%s CreateListener failed!", rdpsnd_is_dyn_str(TRUE));
1881
0
    return status;
1882
0
  }
1883
1884
0
  rdpsnd->listener->pInterface = rdpsnd->iface.pInterface;
1885
0
  status = rdpsnd_virtual_channel_event_initialized(rdpsnd);
1886
1887
0
  rdpsnd->initialized = status == CHANNEL_RC_OK;
1888
0
  return status;
1889
0
}
1890
1891
/**
1892
 * Function description
1893
 *
1894
 * @return 0 on success, otherwise a Win32 error code
1895
 */
1896
WINPR_ATTR_NODISCARD
1897
static UINT rdpsnd_plugin_terminated(IWTSPlugin* pPlugin)
1898
0
{
1899
0
  rdpsndPlugin* rdpsnd = (rdpsndPlugin*)pPlugin;
1900
0
  if (rdpsnd)
1901
0
  {
1902
0
    if (rdpsnd->listener_callback)
1903
0
    {
1904
0
      IWTSVirtualChannelManager* mgr = rdpsnd->listener_callback->channel_mgr;
1905
0
      if (mgr)
1906
0
        IFCALL(mgr->DestroyListener, mgr, rdpsnd->listener);
1907
0
    }
1908
0
    free(rdpsnd->listener_callback);
1909
0
    free(rdpsnd->iface.pInterface);
1910
0
  }
1911
0
  rdpsnd_virtual_channel_event_terminated(rdpsnd);
1912
0
  return CHANNEL_RC_OK;
1913
0
}
1914
1915
/**
1916
 * Function description
1917
 *
1918
 * @return 0 on success, otherwise a Win32 error code
1919
 */
1920
FREERDP_ENTRY_POINT(UINT VCAPITYPE rdpsnd_DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints))
1921
0
{
1922
0
  UINT error = CHANNEL_RC_OK;
1923
1924
0
  WINPR_ASSERT(pEntryPoints);
1925
0
  WINPR_ASSERT(pEntryPoints->GetPlugin);
1926
1927
0
  rdpsndPlugin* rdpsnd =
1928
0
      (rdpsndPlugin*)pEntryPoints->GetPlugin(pEntryPoints, RDPSND_CHANNEL_NAME);
1929
1930
0
  if (!rdpsnd)
1931
0
  {
1932
0
    IWTSPlugin* iface = nullptr;
1933
0
    union
1934
0
    {
1935
0
      const void* cev;
1936
0
      void* ev;
1937
0
    } cnv;
1938
1939
0
    rdpsnd = allocatePlugin();
1940
0
    if (!rdpsnd)
1941
0
    {
1942
0
      WLog_ERR(TAG, "%s calloc failed!", rdpsnd_is_dyn_str(TRUE));
1943
0
      return CHANNEL_RC_NO_MEMORY;
1944
0
    }
1945
1946
0
    iface = &rdpsnd->iface;
1947
0
    iface->Initialize = rdpsnd_plugin_initialize;
1948
0
    iface->Connected = nullptr;
1949
0
    iface->Disconnected = nullptr;
1950
0
    iface->Terminated = rdpsnd_plugin_terminated;
1951
1952
0
    rdpsnd->dynamic = TRUE;
1953
1954
0
    WINPR_ASSERT(pEntryPoints->GetRdpContext);
1955
0
    rdpsnd->rdpcontext = pEntryPoints->GetRdpContext(pEntryPoints);
1956
1957
0
    if (!freerdp_settings_get_bool(rdpsnd->rdpcontext->settings,
1958
0
                                   FreeRDP_SynchronousDynamicChannels))
1959
0
      rdpsnd->async = TRUE;
1960
1961
    /* user data pointer is not const, cast to avoid warning. */
1962
0
    cnv.cev = pEntryPoints->GetPluginData(pEntryPoints);
1963
0
    WINPR_ASSERT(pEntryPoints->GetPluginData);
1964
0
    rdpsnd->channelEntryPoints.pExtendedData = cnv.ev;
1965
1966
0
    error = pEntryPoints->RegisterPlugin(pEntryPoints, RDPSND_CHANNEL_NAME, iface);
1967
0
  }
1968
0
  else
1969
0
  {
1970
0
    WLog_ERR(TAG, "%s could not get rdpsnd Plugin.", rdpsnd_is_dyn_str(TRUE));
1971
0
    return CHANNEL_RC_BAD_CHANNEL;
1972
0
  }
1973
1974
0
  return error;
1975
0
}