Coverage Report

Created: 2026-03-04 06:17

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