Coverage Report

Created: 2026-07-16 07:14

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