VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/utils/audio/vkatCommon.cpp@ 91603

Last change on this file since 91603 was 91603, checked in by vboxsync, 3 years ago

Audio/Validation Kit: Implemented setting the system's master volume to 100% on OSS. Untested [build fix]. ​​bugref:10008

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 54.5 KB
Line 
1/* $Id: vkatCommon.cpp 91603 2021-10-06 17:40:53Z vboxsync $ */
2/** @file
3 * Validation Kit Audio Test (VKAT) - Self test code.
4 */
5
6/*
7 * Copyright (C) 2021 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP LOG_GROUP_AUDIO_TEST
32#include <iprt/log.h>
33
34#ifdef VBOX_WITH_AUDIO_ALSA
35# include "DrvHostAudioAlsaStubsMangling.h"
36# include <alsa/asoundlib.h>
37# include <alsa/control.h> /* For device enumeration. */
38# include <alsa/version.h>
39# include "DrvHostAudioAlsaStubs.h"
40#endif
41#ifdef VBOX_WITH_AUDIO_OSS
42# include <errno.h>
43# include <fcntl.h>
44# include <sys/ioctl.h>
45# include <sys/mman.h>
46# include <sys/soundcard.h>
47# include <unistd.h>
48#endif
49#ifdef RT_OS_WINDOWS
50# include <iprt/win/windows.h>
51# include <iprt/win/audioclient.h>
52# include <endpointvolume.h> /* For IAudioEndpointVolume. */
53# include <audiopolicy.h> /* For IAudioSessionManager. */
54# include <AudioSessionTypes.h>
55# include <Mmdeviceapi.h>
56#endif
57
58#include <iprt/ctype.h>
59#include <iprt/dir.h>
60#include <iprt/errcore.h>
61#include <iprt/getopt.h>
62#include <iprt/message.h>
63#include <iprt/rand.h>
64#include <iprt/test.h>
65
66#include "Audio/AudioHlp.h"
67#include "Audio/AudioTest.h"
68#include "Audio/AudioTestService.h"
69#include "Audio/AudioTestServiceClient.h"
70
71#include "vkatInternal.h"
72
73
74/*********************************************************************************************************************************
75* Defined Constants And Macros *
76*********************************************************************************************************************************/
77
78
79/*********************************************************************************************************************************
80* Internal Functions *
81*********************************************************************************************************************************/
82static int audioTestStreamInit(PAUDIOTESTDRVSTACK pDrvStack, PAUDIOTESTSTREAM pStream, PDMAUDIODIR enmDir, PCPDMAUDIOPCMPROPS pProps, bool fWithMixer, uint32_t cMsBufferSize, uint32_t cMsPreBuffer, uint32_t cMsSchedulingHint);
83static int audioTestStreamDestroy(PAUDIOTESTENV pTstEnv, PAUDIOTESTSTREAM pStream);
84
85
86/*********************************************************************************************************************************
87* Volume handling. *
88*********************************************************************************************************************************/
89
90#ifdef VBOX_WITH_AUDIO_ALSA
91/**
92 * Sets the system's master volume via ALSA, if available.
93 *
94 * @returns VBox status code.
95 * @param uVolPercent Volume (in percent) to set.
96 */
97static int audioTestSetMasterVolumeALSA(unsigned uVolPercent)
98{
99 int rc = audioLoadAlsaLib();
100 if (RT_FAILURE(rc))
101 return rc;
102
103 int err;
104 snd_mixer_t *handle;
105
106# define ALSA_CHECK_RET(a_Exp, a_Text) \
107 if (!(a_Exp)) \
108 { \
109 AssertLogRelMsg(a_Exp, a_Text); \
110 if (handle) \
111 snd_mixer_close(handle); \
112 return VERR_GENERAL_FAILURE; \
113 }
114
115# define ALSA_CHECK_ERR_RET(a_Text) \
116 ALSA_CHECK_RET(err >= 0, a_Text)
117
118 err = snd_mixer_open(&handle, 0 /* Index */);
119 ALSA_CHECK_ERR_RET(("ALSA: Failed to open mixer: %s\n", snd_strerror(err)));
120 err = snd_mixer_attach(handle, "default");
121 ALSA_CHECK_ERR_RET(("ALSA: Failed to attach to default sink: %s\n", snd_strerror(err)));
122 err = snd_mixer_selem_register(handle, NULL, NULL);
123 ALSA_CHECK_ERR_RET(("ALSA: Failed to attach to default sink: %s\n", snd_strerror(err)));
124 err = snd_mixer_load(handle);
125 ALSA_CHECK_ERR_RET(("ALSA: Failed to load mixer: %s\n", snd_strerror(err)));
126
127 snd_mixer_selem_id_t *sid = NULL;
128 snd_mixer_selem_id_alloca(&sid);
129
130 snd_mixer_selem_id_set_index(sid, 0 /* Index */);
131 snd_mixer_selem_id_set_name(sid, "Master");
132
133 snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);
134 ALSA_CHECK_RET(elem != NULL, ("ALSA: Failed to find mixer element: %s\n", snd_strerror(err)));
135
136 long uVolMin, uVolMax;
137 snd_mixer_selem_get_playback_volume_range(elem, &uVolMin, &uVolMax);
138 ALSA_CHECK_ERR_RET(("ALSA: Failed to get playback volume range: %s\n", snd_strerror(err)));
139
140 long const uVol = RT_MIN(uVolPercent, 100) * uVolMax / 100;
141
142 err = snd_mixer_selem_set_playback_volume(elem, SND_MIXER_SCHN_FRONT_LEFT, uVol);
143 ALSA_CHECK_ERR_RET(("ALSA: Failed to set playback volume left: %s\n", snd_strerror(err)));
144 err = snd_mixer_selem_set_playback_volume(elem, SND_MIXER_SCHN_FRONT_RIGHT, uVol);
145 ALSA_CHECK_ERR_RET(("ALSA: Failed to set playback volume right: %s\n", snd_strerror(err)));
146
147 snd_mixer_close(handle);
148
149 return VINF_SUCCESS;
150
151# undef ALSA_CHECK_RET
152# undef ALSA_CHECK_ERR_RET
153}
154#endif /* VBOX_WITH_AUDIO_ALSA */
155
156#ifdef VBOX_WITH_AUDIO_OSS
157/**
158 * Sets the system's master volume via OSS, if available.
159 *
160 * @returns VBox status code.
161 * @param uVolPercent Volume (in percent) to set.
162 */
163static int audioTestSetMasterVolumeOSS(unsigned uVolPercent)
164{
165 int hFile = open("/dev/dsp", O_WRONLY | O_NONBLOCK, 0);
166 if (hFile == -1)
167 {
168 /* Try opening the mixing device instead. */
169 hFile = open("/dev/mixer", O_RDONLY | O_NONBLOCK, 0);
170 }
171
172 if (hFile != -1)
173 {
174 /* OSS maps 0 (muted) - 100 (max), so just use uVolPercent unmodified here. */
175 uint16_t uVol = RT_MAKE_U16(uVolPercent, uVolPercent);
176 AssertLogRelMsgReturnStmt(ioctl(hFile, SOUND_MIXER_PCM /* SNDCTL_DSP_SETPLAYVOL */, &uVol) >= 0,
177 ("OSS: Failed to set DSP playback volume: %s (%d)\n",
178 strerror(errno), errno), close(hFile), RTErrConvertFromErrno(errno));
179 return VINF_SUCCESS;
180 }
181
182 return VERR_NOT_SUPPORTED;
183}
184#endif /* VBOX_WITH_AUDIO_OSS */
185
186#ifdef RT_OS_WINDOWS
187static int audioTestSetMasterVolumeWASAPI(unsigned uVolPercent)
188{
189 HRESULT hr;
190
191# define WASAPI_CHECK_HR_RET(a_Text) \
192 if (FAILED(hr)) \
193 { \
194 AssertLogRelMsgFailed(a_Text); \
195 return VERR_GENERAL_FAILURE; \
196 }
197
198 hr = CoInitialize(NULL);
199 WASAPI_CHECK_HR_RET(("CoInitialize() failed, hr=%Rhrc", hr));
200 IMMDeviceEnumerator* pIEnumerator = NULL;
201 hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void **)&pIEnumerator);
202 WASAPI_CHECK_HR_RET(("WASAPI: Unable to create IMMDeviceEnumerator, hr=%Rhrc", hr));
203
204 IMMDevice *pIMMDevice = NULL;
205 hr = pIEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eConsole, &pIMMDevice);
206 WASAPI_CHECK_HR_RET(("WASAPI: Unable to get audio endpoint, hr=%Rhrc", hr));
207 pIEnumerator->Release();
208
209 IAudioEndpointVolume *pIAudioEndpointVolume = NULL;
210 hr = pIMMDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, (void **)&pIAudioEndpointVolume);
211 WASAPI_CHECK_HR_RET(("WASAPI: Unable to activate audio endpoint volume, hr=%Rhrc", hr));
212 pIMMDevice->Release();
213
214 float dbMin, dbMax, dbInc;
215 hr = pIAudioEndpointVolume->GetVolumeRange(&dbMin, &dbMax, &dbInc);
216 WASAPI_CHECK_HR_RET(("WASAPI: Unable to get volume range, hr=%Rhrc", hr));
217
218 float const dbSteps = (dbMax - dbMin) / dbInc;
219 float const dbStepsPerPercent = (dbSteps * dbInc) / 100;
220 float const dbVol = dbMin + (dbStepsPerPercent * (float(RT_MIN(uVolPercent, 100.0))));
221
222 hr = pIAudioEndpointVolume->SetMasterVolumeLevel(dbVol, NULL);
223 WASAPI_CHECK_HR_RET(("WASAPI: Unable to set master volume level, hr=%Rhrc", hr));
224 pIAudioEndpointVolume->Release();
225
226 return VINF_SUCCESS;
227
228# undef WASAPI_CHECK_HR_RET
229}
230#endif /* RT_OS_WINDOWS */
231
232/**
233 * Sets the system's master volume, if available.
234 *
235 * @returns VBox status code. VERR_NOT_SUPPORTED if not supported.
236 * @param uVolPercent Volume (in percent) to set.
237 */
238int audioTestSetMasterVolume(unsigned uVolPercent)
239{
240 int rc = VINF_SUCCESS;
241
242#ifdef VBOX_WITH_AUDIO_ALSA
243 rc = audioTestSetMasterVolumeALSA(uVolPercent);
244 if (RT_SUCCESS(rc))
245 return rc;
246 /* else try OSS (if available) below. */
247#endif /* VBOX_WITH_AUDIO_ALSA */
248
249#ifdef VBOX_WITH_AUDIO_OSS
250 rc = audioTestSetMasterVolumeOSS(uVolPercent);
251 if (RT_SUCCESS(rc))
252 return rc;
253#endif /* VBOX_WITH_AUDIO_OSS */
254
255#ifdef RT_OS_WINDOWS
256 rc = audioTestSetMasterVolumeWASAPI(uVolPercent);
257 if (RT_SUCCESS(rc))
258 return rc;
259#endif
260
261 RT_NOREF(rc, uVolPercent);
262 /** @todo Port other platforms. */
263 return VERR_NOT_SUPPORTED;
264}
265
266
267/*********************************************************************************************************************************
268* Device enumeration + handling. *
269*********************************************************************************************************************************/
270
271/**
272 * Enumerates audio devices and optionally searches for a specific device.
273 *
274 * @returns VBox status code.
275 * @param pDrvStack Driver stack to use for enumeration.
276 * @param pszDev Device name to search for. Can be NULL if the default device shall be used.
277 * @param ppDev Where to return the pointer of the device enumeration of \a pTstEnv when a
278 * specific device was found.
279 */
280int audioTestDevicesEnumerateAndCheck(PAUDIOTESTDRVSTACK pDrvStack, const char *pszDev, PPDMAUDIOHOSTDEV *ppDev)
281{
282 RTTestSubF(g_hTest, "Enumerating audio devices and checking for device '%s'", pszDev && *pszDev ? pszDev : "[Default]");
283
284 if (!pDrvStack->pIHostAudio->pfnGetDevices)
285 {
286 RTTestSkipped(g_hTest, "Backend does not support device enumeration, skipping");
287 return VINF_NOT_SUPPORTED;
288 }
289
290 Assert(pszDev == NULL || ppDev);
291
292 if (ppDev)
293 *ppDev = NULL;
294
295 int rc = pDrvStack->pIHostAudio->pfnGetDevices(pDrvStack->pIHostAudio, &pDrvStack->DevEnum);
296 if (RT_SUCCESS(rc))
297 {
298 PPDMAUDIOHOSTDEV pDev;
299 RTListForEach(&pDrvStack->DevEnum.LstDevices, pDev, PDMAUDIOHOSTDEV, ListEntry)
300 {
301 char szFlags[PDMAUDIOHOSTDEV_MAX_FLAGS_STRING_LEN];
302 if (pDev->pszId)
303 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Device '%s' (ID '%s'):\n", pDev->pszName, pDev->pszId);
304 else
305 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Device '%s':\n", pDev->pszName);
306 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Usage = %s\n", PDMAudioDirGetName(pDev->enmUsage));
307 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Flags = %s\n", PDMAudioHostDevFlagsToString(szFlags, pDev->fFlags));
308 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Input channels = %RU8\n", pDev->cMaxInputChannels);
309 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Output channels = %RU8\n", pDev->cMaxOutputChannels);
310
311 if ( (pszDev && *pszDev)
312 && !RTStrCmp(pDev->pszName, pszDev))
313 {
314 *ppDev = pDev;
315 }
316 }
317 }
318 else
319 RTTestFailed(g_hTest, "Enumerating audio devices failed with %Rrc", rc);
320
321 if (RT_SUCCESS(rc))
322 {
323 if ( (pszDev && *pszDev)
324 && *ppDev == NULL)
325 {
326 RTTestFailed(g_hTest, "Audio device '%s' not found", pszDev);
327 rc = VERR_NOT_FOUND;
328 }
329 }
330
331 RTTestSubDone(g_hTest);
332 return rc;
333}
334
335static int audioTestStreamInit(PAUDIOTESTDRVSTACK pDrvStack, PAUDIOTESTSTREAM pStream,
336 PDMAUDIODIR enmDir, PCPDMAUDIOPCMPROPS pProps, bool fWithMixer,
337 uint32_t cMsBufferSize, uint32_t cMsPreBuffer, uint32_t cMsSchedulingHint)
338{
339 int rc;
340
341 if (enmDir == PDMAUDIODIR_IN)
342 rc = audioTestDriverStackStreamCreateInput(pDrvStack, pProps, cMsBufferSize,
343 cMsPreBuffer, cMsSchedulingHint, &pStream->pStream, &pStream->Cfg);
344 else if (enmDir == PDMAUDIODIR_OUT)
345 rc = audioTestDriverStackStreamCreateOutput(pDrvStack, pProps, cMsBufferSize,
346 cMsPreBuffer, cMsSchedulingHint, &pStream->pStream, &pStream->Cfg);
347 else
348 rc = VERR_NOT_SUPPORTED;
349
350 if (RT_SUCCESS(rc))
351 {
352 if (!pDrvStack->pIAudioConnector)
353 {
354 pStream->pBackend = &((PAUDIOTESTDRVSTACKSTREAM)pStream->pStream)->Backend;
355 }
356 else
357 pStream->pBackend = NULL;
358
359 /*
360 * Automatically enable the mixer if the PCM properties don't match.
361 */
362 if ( !fWithMixer
363 && !PDMAudioPropsAreEqual(pProps, &pStream->Cfg.Props))
364 {
365 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enabling stream mixer\n");
366 fWithMixer = true;
367 }
368
369 rc = AudioTestMixStreamInit(&pStream->Mix, pDrvStack, pStream->pStream,
370 fWithMixer ? pProps : NULL, 100 /* ms */); /** @todo Configure mixer buffer? */
371 }
372
373 if (RT_FAILURE(rc))
374 RTTestFailed(g_hTest, "Initializing %s stream failed with %Rrc", enmDir == PDMAUDIODIR_IN ? "input" : "output", rc);
375
376 return rc;
377}
378
379/**
380 * Destroys an audio test stream.
381 *
382 * @returns VBox status code.
383 * @param pTstEnv Test environment the stream to destroy contains.
384 * @param pStream Audio stream to destroy.
385 */
386static int audioTestStreamDestroy(PAUDIOTESTENV pTstEnv, PAUDIOTESTSTREAM pStream)
387{
388 int rc = VINF_SUCCESS;
389 if (pStream && pStream->pStream)
390 {
391 /** @todo Anything else to do here, e.g. test if there are left over samples or some such? */
392
393 audioTestDriverStackStreamDestroy(pTstEnv->pDrvStack, pStream->pStream);
394 pStream->pStream = NULL;
395 pStream->pBackend = NULL;
396 }
397
398 AudioTestMixStreamTerm(&pStream->Mix);
399
400 return rc;
401}
402
403
404/*********************************************************************************************************************************
405* Test Primitives *
406*********************************************************************************************************************************/
407
408#if 0 /* Unused */
409/**
410 * Returns a random scheduling hint (in ms).
411 */
412DECLINLINE(uint32_t) audioTestEnvGetRandomSchedulingHint(void)
413{
414 static const unsigned s_aSchedulingHintsMs[] =
415 {
416 10,
417 25,
418 50,
419 100,
420 200,
421 250
422 };
423
424 return s_aSchedulingHintsMs[RTRandU32Ex(0, RT_ELEMENTS(s_aSchedulingHintsMs) - 1)];
425}
426#endif
427
428/**
429 * Plays a test tone on a specific audio test stream.
430 *
431 * @returns VBox status code.
432 * @param pTstEnv Test environment to use for running the test.
433 * Optional and can be NULL (for simple playback only).
434 * @param pStream Stream to use for playing the tone.
435 * @param pParms Tone parameters to use.
436 *
437 * @note Blocking function.
438 */
439int audioTestPlayTone(PAUDIOTESTENV pTstEnv, PAUDIOTESTSTREAM pStream, PAUDIOTESTTONEPARMS pParms)
440{
441 AUDIOTESTTONE TstTone;
442 AudioTestToneInit(&TstTone, &pStream->Cfg.Props, pParms->dbFreqHz);
443
444 char const *pcszPathOut = NULL;
445 if (pTstEnv)
446 pcszPathOut = pTstEnv->Set.szPathAbs;
447
448 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Playing test tone (tone frequency is %RU16Hz, %RU32ms)\n", (uint16_t)pParms->dbFreqHz, pParms->msDuration);
449 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Using %RU32ms stream scheduling hint\n", pStream->Cfg.Device.cMsSchedulingHint);
450 if (pcszPathOut)
451 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Writing to '%s'\n", pcszPathOut);
452
453 int rc;
454
455 /** @todo Use .WAV here? */
456 AUDIOTESTOBJ Obj;
457 RT_ZERO(Obj); /* Shut up MSVC. */
458 if (pTstEnv)
459 {
460 rc = AudioTestSetObjCreateAndRegister(&pTstEnv->Set, "guest-tone-play.pcm", &Obj);
461 AssertRCReturn(rc, rc);
462 }
463
464 /* Try to crank up the system's master volume up to 100% so that we (hopefully) play the test tone always at the same leve.
465 * Not supported on all platforms yet, therefore not critical for overall testing (yet). */
466 unsigned const uVolPercent = 100;
467 int rc2 = audioTestSetMasterVolume(uVolPercent);
468 if (RT_FAILURE(rc2))
469 {
470 if (rc2 == VERR_NOT_SUPPORTED)
471 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Setting system's master volume is not supported on this platform, skipping\n");
472 else
473 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Setting system's master volume failed with %Rrc\n", rc2);
474 }
475 else
476 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Set system's master volume to %RU8%%\n", uVolPercent);
477
478 rc = AudioTestMixStreamEnable(&pStream->Mix);
479 if ( RT_SUCCESS(rc)
480 && AudioTestMixStreamIsOkay(&pStream->Mix))
481 {
482 uint8_t abBuf[_4K];
483
484 uint32_t cbToPlayTotal = PDMAudioPropsMilliToBytes(&pStream->Cfg.Props, pParms->msDuration);
485 AssertStmt(cbToPlayTotal, rc = VERR_INVALID_PARAMETER);
486 uint32_t cbPlayedTotal = 0;
487
488 /* We play a pre + post beacon before + after the actual test tone with exactly 1024 audio frames. */
489 uint32_t const cbBeacon = PDMAudioPropsFramesToBytes(&pStream->Cfg.Props, 1024);
490 uint32_t cbBeaconToPlay = cbBeacon;
491 uint32_t cbBeaconPlayed = 0;
492
493 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Playing %RU32 bytes total\n", cbToPlayTotal);
494 if (cbBeaconToPlay)
495 {
496 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Playing 2 x %RU32 bytes pre/post beacons\n", cbBeaconToPlay);
497 cbToPlayTotal += cbBeacon * 2 /* Pre + post beacon */;
498 }
499
500 if (pTstEnv)
501 {
502 AudioTestObjAddMetadataStr(Obj, "stream_to_play_bytes=%RU32\n", cbToPlayTotal);
503 AudioTestObjAddMetadataStr(Obj, "stream_period_size_frames=%RU32\n", pStream->Cfg.Backend.cFramesPeriod);
504 AudioTestObjAddMetadataStr(Obj, "stream_buffer_size_frames=%RU32\n", pStream->Cfg.Backend.cFramesBufferSize);
505 AudioTestObjAddMetadataStr(Obj, "stream_prebuf_size_frames=%RU32\n", pStream->Cfg.Backend.cFramesPreBuffering);
506 /* Note: This mostly is provided by backend (e.g. PulseAudio / ALSA / ++) and
507 * has nothing to do with the device emulation scheduling hint. */
508 AudioTestObjAddMetadataStr(Obj, "device_scheduling_hint_ms=%RU32\n", pStream->Cfg.Device.cMsSchedulingHint);
509 }
510
511 PAUDIOTESTDRVMIXSTREAM pMix = &pStream->Mix;
512
513 uint32_t const cbPreBuffer = PDMAudioPropsFramesToBytes(pMix->pProps, pStream->Cfg.Backend.cFramesPreBuffering);
514 uint64_t const nsStarted = RTTimeNanoTS();
515 uint64_t nsDonePreBuffering = 0;
516
517 uint64_t offStream = 0;
518 uint64_t nsTimeout = RT_MS_5MIN_64 * RT_NS_1MS;
519 uint64_t nsLastMsgCantWrite = 0; /* Timestamp (in ns) when the last message of an unwritable stream was shown. */
520
521 while (cbPlayedTotal < cbToPlayTotal)
522 {
523 uint64_t const nsNow = RTTimeNanoTS();
524
525 /* Pace ourselves a little. */
526 if (offStream >= cbPreBuffer)
527 {
528 if (!nsDonePreBuffering)
529 nsDonePreBuffering = nsNow;
530 uint64_t const cNsWritten = PDMAudioPropsBytesToNano64(pMix->pProps, offStream - cbPreBuffer);
531 uint64_t const cNsElapsed = nsNow - nsStarted;
532 if (cNsWritten > cNsElapsed + RT_NS_10MS)
533 RTThreadSleep((cNsWritten - cNsElapsed - RT_NS_10MS / 2) / RT_NS_1MS);
534 }
535
536 uint32_t cbPlayed = 0;
537 uint32_t const cbCanWrite = AudioTestMixStreamGetWritable(&pStream->Mix);
538 if (cbCanWrite)
539 {
540 if (g_uVerbosity)
541 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Stream is writable with %RU32ms (%RU32 bytes)\n",
542 PDMAudioPropsBytesToMilli(pMix->pProps, cbCanWrite), cbCanWrite);
543
544 uint32_t cbToPlay;
545
546 /* Any beacon to play? */
547 if ( cbBeaconToPlay
548 && cbBeaconPlayed < cbBeaconToPlay)
549 {
550 /* Limit to exactly one beacon (pre or post). */
551 cbToPlay = RT_MIN(sizeof(abBuf), RT_MIN(cbCanWrite, cbBeaconToPlay - cbBeaconPlayed));
552 memset(abBuf, 0x42 /* Our actual beacon data, hopefully the answer to all ... */, cbToPlay);
553
554 rc = AudioTestMixStreamPlay(&pStream->Mix, abBuf, cbToPlay, &cbPlayed);
555 if (RT_FAILURE(rc))
556 break;
557
558 cbBeaconPlayed += cbPlayed;
559 cbPlayedTotal += cbPlayed;
560 continue;
561 }
562
563 /* Start playing the post beacon? */
564 if (cbPlayedTotal == cbToPlayTotal - cbBeaconToPlay)
565 {
566 cbBeaconPlayed = 0;
567 continue;
568 }
569
570 if (RT_FAILURE(rc))
571 break;
572
573 uint32_t const cbToGenerate = RT_MIN(RT_MIN(cbToPlayTotal - cbPlayedTotal - cbBeaconToPlay, sizeof(abBuf)),
574 cbCanWrite);
575 rc = AudioTestToneGenerate(&TstTone, abBuf, cbToGenerate, &cbToPlay);
576 if (RT_SUCCESS(rc))
577 {
578 if (pTstEnv)
579 {
580 /* Write stuff to disk before trying to play it. Help analysis later. */
581 rc = AudioTestObjWrite(Obj, abBuf, cbToPlay);
582 }
583 if (RT_SUCCESS(rc))
584 {
585 rc = AudioTestMixStreamPlay(&pStream->Mix, abBuf, cbToPlay, &cbPlayed);
586 if (RT_SUCCESS(rc))
587 {
588 AssertBreakStmt(cbPlayed <= cbToPlay, rc = VERR_TOO_MUCH_DATA);
589
590 offStream += cbPlayed;
591
592 if (cbPlayed != cbToPlay)
593 RTTestFailed(g_hTest, "Only played %RU32/%RU32 bytes", cbPlayed, cbToPlay);
594 }
595 }
596 }
597
598 if (RT_FAILURE(rc))
599 break;
600
601 nsLastMsgCantWrite = 0;
602 }
603 else if (AudioTestMixStreamIsOkay(&pStream->Mix))
604 {
605 RTMSINTERVAL const msSleep = RT_MIN(RT_MAX(1, pStream->Cfg.Device.cMsSchedulingHint), 256);
606
607 if (!nsLastMsgCantWrite || nsNow - nsLastMsgCantWrite > RT_NS_10SEC) /* Don't spam the output too much. */
608 {
609 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Waiting %RU32ms for stream to be writable again ...\n", msSleep);
610 nsLastMsgCantWrite = nsNow;
611 }
612
613 RTThreadSleep(msSleep);
614 }
615 else
616 AssertFailedBreakStmt(rc = VERR_AUDIO_STREAM_NOT_READY);
617
618 cbPlayedTotal += cbPlayed;
619 AssertBreakStmt(cbPlayedTotal <= cbToPlayTotal, VERR_BUFFER_OVERFLOW);
620
621 /* Fail-safe in case something screwed up while playing back. */
622 uint64_t const cNsElapsed = nsNow - nsStarted;
623 if (cNsElapsed > nsTimeout)
624 {
625 RTTestFailed(g_hTest, "Playback took too long (running %RU64 vs. timeout %RU64), aborting\n", cNsElapsed, nsTimeout);
626 rc = VERR_TIMEOUT;
627 }
628
629 if (RT_FAILURE(rc))
630 break;
631 }
632
633 if (cbPlayedTotal != cbToPlayTotal)
634 RTTestFailed(g_hTest, "Playback ended unexpectedly (%RU32/%RU32 played)\n", cbPlayedTotal, cbToPlayTotal);
635
636 if (RT_SUCCESS(rc))
637 {
638 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Draining stream ...\n");
639 rc = AudioTestMixStreamDrain(&pStream->Mix, true /*fSync*/);
640 }
641 }
642 else
643 rc = VERR_AUDIO_STREAM_NOT_READY;
644
645 if (pTstEnv)
646 {
647 rc2 = AudioTestObjClose(Obj);
648 if (RT_SUCCESS(rc))
649 rc = rc2;
650 }
651
652 if (RT_FAILURE(rc))
653 RTTestFailed(g_hTest, "Playing tone failed with %Rrc\n", rc);
654
655 return rc;
656}
657
658/**
659 * Records a test tone from a specific audio test stream.
660 *
661 * @returns VBox status code.
662 * @param pTstEnv Test environment to use for running the test.
663 * @param pStream Stream to use for recording the tone.
664 * @param pParms Tone parameters to use.
665 *
666 * @note Blocking function.
667 */
668static int audioTestRecordTone(PAUDIOTESTENV pTstEnv, PAUDIOTESTSTREAM pStream, PAUDIOTESTTONEPARMS pParms)
669{
670 const char *pcszPathOut = pTstEnv->Set.szPathAbs;
671
672 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Recording test tone (tone frequency is %RU16Hz, %RU32ms)\n", (uint16_t)pParms->dbFreqHz, pParms->msDuration);
673 RTTestPrintf(g_hTest, RTTESTLVL_DEBUG, "Writing to '%s'\n", pcszPathOut);
674
675 /** @todo Use .WAV here? */
676 AUDIOTESTOBJ Obj;
677 int rc = AudioTestSetObjCreateAndRegister(&pTstEnv->Set, "guest-tone-rec.pcm", &Obj);
678 AssertRCReturn(rc, rc);
679
680 PAUDIOTESTDRVMIXSTREAM pMix = &pStream->Mix;
681
682 rc = AudioTestMixStreamEnable(pMix);
683 if (RT_SUCCESS(rc))
684 {
685 uint64_t cbToRecTotal = PDMAudioPropsMilliToBytes(&pStream->Cfg.Props, pParms->msDuration);
686
687 RTTestPrintf(g_hTest, RTTESTLVL_DEBUG, "Recording %RU32 bytes total\n", cbToRecTotal);
688
689 AudioTestObjAddMetadataStr(Obj, "stream_to_record_bytes=%RU32\n", cbToRecTotal);
690 AudioTestObjAddMetadataStr(Obj, "stream_buffer_size_ms=%RU32\n", pTstEnv->cMsBufferSize);
691 AudioTestObjAddMetadataStr(Obj, "stream_prebuf_size_ms=%RU32\n", pTstEnv->cMsPreBuffer);
692 /* Note: This mostly is provided by backend (e.g. PulseAudio / ALSA / ++) and
693 * has nothing to do with the device emulation scheduling hint. */
694 AudioTestObjAddMetadataStr(Obj, "device_scheduling_hint_ms=%RU32\n", pTstEnv->cMsSchedulingHint);
695
696 uint8_t abSamples[16384];
697 uint32_t const cbSamplesAligned = PDMAudioPropsFloorBytesToFrame(pMix->pProps, sizeof(abSamples));
698 uint64_t cbRecTotal = 0;
699
700 uint64_t const nsStarted = RTTimeNanoTS();
701
702 uint64_t nsTimeout = RT_MS_5MIN_64 * RT_NS_1MS;
703 uint64_t nsLastMsgCantRead = 0; /* Timestamp (in ns) when the last message of an unreadable stream was shown. */
704
705 while (!g_fTerminate && cbRecTotal < cbToRecTotal)
706 {
707 uint64_t const nsNow = RTTimeNanoTS();
708
709 /*
710 * Anything we can read?
711 */
712 uint32_t const cbCanRead = AudioTestMixStreamGetReadable(pMix);
713 if (cbCanRead)
714 {
715 if (g_uVerbosity)
716 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Stream is readable with %RU32ms (%RU32 bytes)\n",
717 PDMAudioPropsBytesToMilli(pMix->pProps, cbCanRead), cbCanRead);
718
719 uint32_t const cbToRead = RT_MIN(cbCanRead, cbSamplesAligned);
720 uint32_t cbRecorded = 0;
721 rc = AudioTestMixStreamCapture(pMix, abSamples, cbToRead, &cbRecorded);
722 if (RT_SUCCESS(rc))
723 {
724 if (cbRecorded)
725 {
726 rc = AudioTestObjWrite(Obj, abSamples, cbRecorded);
727 if (RT_SUCCESS(rc))
728 {
729 cbRecTotal += cbRecorded;
730
731 /** @todo Clamp result? */
732 }
733 }
734 }
735 }
736 else if (AudioTestMixStreamIsOkay(pMix))
737 {
738 RTMSINTERVAL const msSleep = RT_MIN(RT_MAX(1, pStream->Cfg.Device.cMsSchedulingHint), 256);
739
740 if (!nsLastMsgCantRead || nsNow - nsLastMsgCantRead > RT_NS_10SEC) /* Don't spam the output too much. */
741 {
742 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Waiting %RU32ms for stream to be readable again ...\n", msSleep);
743 nsLastMsgCantRead = nsNow;
744 }
745
746 RTThreadSleep(msSleep);
747 }
748
749 /* Fail-safe in case something screwed up while playing back. */
750 uint64_t const cNsElapsed = nsNow - nsStarted;
751 if (cNsElapsed > nsTimeout)
752 {
753 RTTestFailed(g_hTest, "Recording took too long (running %RU64 vs. timeout %RU64), aborting\n", cNsElapsed, nsTimeout);
754 rc = VERR_TIMEOUT;
755 }
756
757 if (RT_FAILURE(rc))
758 break;
759 }
760
761 if (cbRecTotal != cbToRecTotal)
762 RTTestFailed(g_hTest, "Recording ended unexpectedly (%RU32/%RU32 recorded)\n", cbRecTotal, cbToRecTotal);
763
764 int rc2 = AudioTestMixStreamDisable(pMix);
765 if (RT_SUCCESS(rc))
766 rc = rc2;
767 }
768
769 int rc2 = AudioTestObjClose(Obj);
770 if (RT_SUCCESS(rc))
771 rc = rc2;
772
773 if (RT_FAILURE(rc))
774 RTTestFailed(g_hTest, "Recording tone done failed with %Rrc\n", rc);
775
776 return rc;
777}
778
779
780/*********************************************************************************************************************************
781* ATS Callback Implementations *
782*********************************************************************************************************************************/
783
784/** @copydoc ATSCALLBACKS::pfnHowdy
785 *
786 * @note Runs as part of the guest ATS.
787 */
788static DECLCALLBACK(int) audioTestGstAtsHowdyCallback(void const *pvUser)
789{
790 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
791
792 AssertReturn(pCtx->cClients <= UINT8_MAX - 1, VERR_BUFFER_OVERFLOW);
793
794 pCtx->cClients++;
795
796 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "New client connected, now %RU8 total\n", pCtx->cClients);
797
798 return VINF_SUCCESS;
799}
800
801/** @copydoc ATSCALLBACKS::pfnBye
802 *
803 * @note Runs as part of the guest ATS.
804 */
805static DECLCALLBACK(int) audioTestGstAtsByeCallback(void const *pvUser)
806{
807 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
808
809 AssertReturn(pCtx->cClients, VERR_WRONG_ORDER);
810 pCtx->cClients--;
811
812 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Client wants to disconnect, %RU8 remaining\n", pCtx->cClients);
813
814 if (0 == pCtx->cClients) /* All clients disconnected? Tear things down. */
815 {
816 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Last client disconnected, terminating server ...\n");
817 ASMAtomicWriteBool(&g_fTerminate, true);
818 }
819
820 return VINF_SUCCESS;
821}
822
823/** @copydoc ATSCALLBACKS::pfnTestSetBegin
824 *
825 * @note Runs as part of the guest ATS.
826 */
827static DECLCALLBACK(int) audioTestGstAtsTestSetBeginCallback(void const *pvUser, const char *pszTag)
828{
829 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
830 PAUDIOTESTENV pTstEnv = pCtx->pTstEnv;
831
832 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Got request for beginning test set '%s' in '%s'\n", pszTag, pTstEnv->szPathTemp);
833
834 return AudioTestSetCreate(&pTstEnv->Set, pTstEnv->szPathTemp, pszTag);
835}
836
837/** @copydoc ATSCALLBACKS::pfnTestSetEnd
838 *
839 * @note Runs as part of the guest ATS.
840 */
841static DECLCALLBACK(int) audioTestGstAtsTestSetEndCallback(void const *pvUser, const char *pszTag)
842{
843 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
844 PAUDIOTESTENV pTstEnv = pCtx->pTstEnv;
845
846 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Got request for ending test set '%s'\n", pszTag);
847
848 /* Pack up everything to be ready for transmission. */
849 return audioTestEnvPrologue(pTstEnv, true /* fPack */, pCtx->szTestSetArchive, sizeof(pCtx->szTestSetArchive));
850}
851
852/** @copydoc ATSCALLBACKS::pfnTonePlay
853 *
854 * @note Runs as part of the guest ATS.
855 */
856static DECLCALLBACK(int) audioTestGstAtsTonePlayCallback(void const *pvUser, PAUDIOTESTTONEPARMS pToneParms)
857{
858 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
859 PAUDIOTESTENV pTstEnv = pCtx->pTstEnv;
860
861 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Got request for playing test tone #%RU32 (%RU16Hz, %RU32ms) ...\n",
862 pToneParms->Hdr.idxSeq, (uint16_t)pToneParms->dbFreqHz, pToneParms->msDuration);
863
864 char szTimeCreated[RTTIME_STR_LEN];
865 RTTimeToString(&pToneParms->Hdr.tsCreated, szTimeCreated, sizeof(szTimeCreated));
866 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test created (caller UTC): %s\n", szTimeCreated);
867
868 const PAUDIOTESTSTREAM pTstStream = &pTstEnv->aStreams[0]; /** @todo Make this dynamic. */
869
870 int rc = audioTestStreamInit(pTstEnv->pDrvStack, pTstStream, PDMAUDIODIR_OUT, &pTstEnv->Props, false /* fWithMixer */,
871 pTstEnv->cMsBufferSize, pTstEnv->cMsPreBuffer, pTstEnv->cMsSchedulingHint);
872 if (RT_SUCCESS(rc))
873 {
874 AUDIOTESTPARMS TstParms;
875 RT_ZERO(TstParms);
876 TstParms.enmType = AUDIOTESTTYPE_TESTTONE_PLAY;
877 TstParms.enmDir = PDMAUDIODIR_OUT;
878 TstParms.TestTone = *pToneParms;
879
880 PAUDIOTESTENTRY pTst;
881 rc = AudioTestSetTestBegin(&pTstEnv->Set, "Playing test tone", &TstParms, &pTst);
882 if (RT_SUCCESS(rc))
883 {
884 rc = audioTestPlayTone(pTstEnv, pTstStream, pToneParms);
885 if (RT_SUCCESS(rc))
886 {
887 AudioTestSetTestDone(pTst);
888 }
889 else
890 AudioTestSetTestFailed(pTst, rc, "Playing tone failed");
891 }
892
893 int rc2 = audioTestStreamDestroy(pTstEnv, pTstStream);
894 if (RT_SUCCESS(rc))
895 rc = rc2;
896 }
897 else
898 RTTestFailed(g_hTest, "Error creating output stream, rc=%Rrc\n", rc);
899
900 return rc;
901}
902
903/** @copydoc ATSCALLBACKS::pfnToneRecord */
904static DECLCALLBACK(int) audioTestGstAtsToneRecordCallback(void const *pvUser, PAUDIOTESTTONEPARMS pToneParms)
905{
906 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
907 PAUDIOTESTENV pTstEnv = pCtx->pTstEnv;
908
909 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Got request for recording test tone #%RU32 (%RU32ms) ...\n",
910 pToneParms->Hdr.idxSeq, pToneParms->msDuration);
911
912 char szTimeCreated[RTTIME_STR_LEN];
913 RTTimeToString(&pToneParms->Hdr.tsCreated, szTimeCreated, sizeof(szTimeCreated));
914 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test created (caller UTC): %s\n", szTimeCreated);
915
916 const PAUDIOTESTSTREAM pTstStream = &pTstEnv->aStreams[0]; /** @todo Make this dynamic. */
917
918 int rc = audioTestStreamInit(pTstEnv->pDrvStack, pTstStream, PDMAUDIODIR_IN, &pTstEnv->Props, false /* fWithMixer */,
919 pTstEnv->cMsBufferSize, pTstEnv->cMsPreBuffer, pTstEnv->cMsSchedulingHint);
920 if (RT_SUCCESS(rc))
921 {
922 AUDIOTESTPARMS TstParms;
923 RT_ZERO(TstParms);
924 TstParms.enmType = AUDIOTESTTYPE_TESTTONE_RECORD;
925 TstParms.enmDir = PDMAUDIODIR_IN;
926 TstParms.Props = pToneParms->Props;
927 TstParms.TestTone = *pToneParms;
928
929 PAUDIOTESTENTRY pTst;
930 rc = AudioTestSetTestBegin(&pTstEnv->Set, "Recording test tone from host", &TstParms, &pTst);
931 if (RT_SUCCESS(rc))
932 {
933 rc = audioTestRecordTone(pTstEnv, pTstStream, pToneParms);
934 if (RT_SUCCESS(rc))
935 {
936 AudioTestSetTestDone(pTst);
937 }
938 else
939 AudioTestSetTestFailed(pTst, rc, "Recording tone failed");
940 }
941
942 int rc2 = audioTestStreamDestroy(pTstEnv, pTstStream);
943 if (RT_SUCCESS(rc))
944 rc = rc2;
945 }
946 else
947 RTTestFailed(g_hTest, "Error creating input stream, rc=%Rrc\n", rc);
948
949 return rc;
950}
951
952/** @copydoc ATSCALLBACKS::pfnTestSetSendBegin */
953static DECLCALLBACK(int) audioTestGstAtsTestSetSendBeginCallback(void const *pvUser, const char *pszTag)
954{
955 RT_NOREF(pszTag);
956
957 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
958
959 if (!RTFileExists(pCtx->szTestSetArchive)) /* Has the archive successfully been created yet? */
960 return VERR_WRONG_ORDER;
961
962 int rc = RTFileOpen(&pCtx->hTestSetArchive, pCtx->szTestSetArchive, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
963 if (RT_SUCCESS(rc))
964 {
965 uint64_t uSize;
966 rc = RTFileQuerySize(pCtx->hTestSetArchive, &uSize);
967 if (RT_SUCCESS(rc))
968 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Sending test set '%s' (%zu bytes)\n", pCtx->szTestSetArchive, uSize);
969 }
970
971 return rc;
972}
973
974/** @copydoc ATSCALLBACKS::pfnTestSetSendRead */
975static DECLCALLBACK(int) audioTestGstAtsTestSetSendReadCallback(void const *pvUser,
976 const char *pszTag, void *pvBuf, size_t cbBuf, size_t *pcbRead)
977{
978 RT_NOREF(pszTag);
979
980 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
981
982 return RTFileRead(pCtx->hTestSetArchive, pvBuf, cbBuf, pcbRead);
983}
984
985/** @copydoc ATSCALLBACKS::pfnTestSetSendEnd */
986static DECLCALLBACK(int) audioTestGstAtsTestSetSendEndCallback(void const *pvUser, const char *pszTag)
987{
988 RT_NOREF(pszTag);
989
990 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
991
992 int rc = RTFileClose(pCtx->hTestSetArchive);
993 if (RT_SUCCESS(rc))
994 {
995 pCtx->hTestSetArchive = NIL_RTFILE;
996 }
997
998 return rc;
999}
1000
1001
1002/*********************************************************************************************************************************
1003* Implementation of audio test environment handling *
1004*********************************************************************************************************************************/
1005
1006/**
1007 * Connects an ATS client via TCP/IP to a peer.
1008 *
1009 * @returns VBox status code.
1010 * @param pTstEnv Test environment to use.
1011 * @param pClient Client to connect.
1012 * @param pszWhat Hint of what to connect to where.
1013 * @param pTcpOpts Pointer to TCP options to use.
1014 */
1015int audioTestEnvConnectViaTcp(PAUDIOTESTENV pTstEnv, PATSCLIENT pClient, const char *pszWhat, PAUDIOTESTENVTCPOPTS pTcpOpts)
1016{
1017 RT_NOREF(pTstEnv);
1018
1019 RTGETOPTUNION Val;
1020 RT_ZERO(Val);
1021
1022 Val.u32 = pTcpOpts->enmConnMode;
1023 int rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_CONN_MODE, &Val);
1024 AssertRCReturn(rc, rc);
1025
1026 if ( pTcpOpts->enmConnMode == ATSCONNMODE_BOTH
1027 || pTcpOpts->enmConnMode == ATSCONNMODE_SERVER)
1028 {
1029 Assert(pTcpOpts->uBindPort); /* Always set by the caller. */
1030 Val.u16 = pTcpOpts->uBindPort;
1031 rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_BIND_PORT, &Val);
1032 AssertRCReturn(rc, rc);
1033
1034 if (pTcpOpts->szBindAddr[0])
1035 {
1036 Val.psz = pTcpOpts->szBindAddr;
1037 rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_BIND_ADDRESS, &Val);
1038 AssertRCReturn(rc, rc);
1039 }
1040 else
1041 {
1042 RTTestFailed(g_hTest, "No bind address specified!\n");
1043 return VERR_INVALID_PARAMETER;
1044 }
1045
1046 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Connecting %s by listening as server at %s:%RU32 ...\n",
1047 pszWhat, pTcpOpts->szBindAddr, pTcpOpts->uBindPort);
1048 }
1049
1050
1051 if ( pTcpOpts->enmConnMode == ATSCONNMODE_BOTH
1052 || pTcpOpts->enmConnMode == ATSCONNMODE_CLIENT)
1053 {
1054 Assert(pTcpOpts->uConnectPort); /* Always set by the caller. */
1055 Val.u16 = pTcpOpts->uConnectPort;
1056 rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_CONNECT_PORT, &Val);
1057 AssertRCReturn(rc, rc);
1058
1059 if (pTcpOpts->szConnectAddr[0])
1060 {
1061 Val.psz = pTcpOpts->szConnectAddr;
1062 rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_CONNECT_ADDRESS, &Val);
1063 AssertRCReturn(rc, rc);
1064 }
1065 else
1066 {
1067 RTTestFailed(g_hTest, "No connect address specified!\n");
1068 return VERR_INVALID_PARAMETER;
1069 }
1070
1071 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Connecting %s by connecting as client to %s:%RU32 ...\n",
1072 pszWhat, pTcpOpts->szConnectAddr, pTcpOpts->uConnectPort);
1073 }
1074
1075 rc = AudioTestSvcClientConnect(pClient);
1076 if (RT_FAILURE(rc))
1077 {
1078 RTTestFailed(g_hTest, "Connecting %s failed with %Rrc\n", pszWhat, rc);
1079 return rc;
1080 }
1081
1082 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Successfully connected %s\n", pszWhat);
1083 return rc;
1084}
1085
1086/**
1087 * Configures and starts an ATS TCP/IP server.
1088 *
1089 * @returns VBox status code.
1090 * @param pSrv ATS server instance to configure and start.
1091 * @param pCallbacks ATS callback table to use.
1092 * @param pszDesc Hint of server type which is being started.
1093 * @param pTcpOpts TCP options to use.
1094 */
1095int audioTestEnvConfigureAndStartTcpServer(PATSSERVER pSrv, PCATSCALLBACKS pCallbacks, const char *pszDesc,
1096 PAUDIOTESTENVTCPOPTS pTcpOpts)
1097{
1098 RTGETOPTUNION Val;
1099 RT_ZERO(Val);
1100
1101 int rc = AudioTestSvcInit(pSrv, pCallbacks);
1102 if (RT_FAILURE(rc))
1103 return rc;
1104
1105 Val.u32 = pTcpOpts->enmConnMode;
1106 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_CONN_MODE, &Val);
1107 AssertRCReturn(rc, rc);
1108
1109 if ( pTcpOpts->enmConnMode == ATSCONNMODE_BOTH
1110 || pTcpOpts->enmConnMode == ATSCONNMODE_SERVER)
1111 {
1112 Assert(pTcpOpts->uBindPort); /* Always set by the caller. */
1113 Val.u16 = pTcpOpts->uBindPort;
1114 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_BIND_PORT, &Val);
1115 AssertRCReturn(rc, rc);
1116
1117 if (pTcpOpts->szBindAddr[0])
1118 {
1119 Val.psz = pTcpOpts->szBindAddr;
1120 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_BIND_ADDRESS, &Val);
1121 AssertRCReturn(rc, rc);
1122 }
1123 else
1124 {
1125 RTTestFailed(g_hTest, "No bind address specified!\n");
1126 return VERR_INVALID_PARAMETER;
1127 }
1128
1129 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Starting server for %s at %s:%RU32 ...\n",
1130 pszDesc, pTcpOpts->szBindAddr, pTcpOpts->uBindPort);
1131 }
1132
1133
1134 if ( pTcpOpts->enmConnMode == ATSCONNMODE_BOTH
1135 || pTcpOpts->enmConnMode == ATSCONNMODE_CLIENT)
1136 {
1137 Assert(pTcpOpts->uConnectPort); /* Always set by the caller. */
1138 Val.u16 = pTcpOpts->uConnectPort;
1139 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_CONNECT_PORT, &Val);
1140 AssertRCReturn(rc, rc);
1141
1142 if (pTcpOpts->szConnectAddr[0])
1143 {
1144 Val.psz = pTcpOpts->szConnectAddr;
1145 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_CONNECT_ADDRESS, &Val);
1146 AssertRCReturn(rc, rc);
1147 }
1148 else
1149 {
1150 RTTestFailed(g_hTest, "No connect address specified!\n");
1151 return VERR_INVALID_PARAMETER;
1152 }
1153
1154 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Starting server for %s by connecting as client to %s:%RU32 ...\n",
1155 pszDesc, pTcpOpts->szConnectAddr, pTcpOpts->uConnectPort);
1156 }
1157
1158 if (RT_SUCCESS(rc))
1159 {
1160 rc = AudioTestSvcStart(pSrv);
1161 if (RT_FAILURE(rc))
1162 RTTestFailed(g_hTest, "Starting server for %s failed with %Rrc\n", pszDesc, rc);
1163 }
1164
1165 return rc;
1166}
1167
1168/**
1169 * Initializes an audio test environment.
1170 *
1171 * @returns VBox status code.
1172 * @param pTstEnv Audio test environment to initialize.
1173 * @param pDrvStack Driver stack to use.
1174 */
1175int audioTestEnvInit(PAUDIOTESTENV pTstEnv, PAUDIOTESTDRVSTACK pDrvStack)
1176{
1177 int rc = VINF_SUCCESS;
1178
1179 pTstEnv->pDrvStack = pDrvStack;
1180
1181 /*
1182 * Set sane defaults if not already set.
1183 */
1184 if (!RTStrNLen(pTstEnv->szTag, sizeof(pTstEnv->szTag)))
1185 {
1186 rc = AudioTestGenTag(pTstEnv->szTag, sizeof(pTstEnv->szTag));
1187 AssertRCReturn(rc, rc);
1188 }
1189
1190 if (!RTStrNLen(pTstEnv->szPathTemp, sizeof(pTstEnv->szPathTemp)))
1191 {
1192 rc = AudioTestPathGetTemp(pTstEnv->szPathTemp, sizeof(pTstEnv->szPathTemp));
1193 AssertRCReturn(rc, rc);
1194 }
1195
1196 if (!RTStrNLen(pTstEnv->szPathOut, sizeof(pTstEnv->szPathOut)))
1197 {
1198 rc = RTPathJoin(pTstEnv->szPathOut, sizeof(pTstEnv->szPathOut), pTstEnv->szPathTemp, "vkat-temp");
1199 AssertRCReturn(rc, rc);
1200 }
1201
1202 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Initializing environment for mode '%s'\n", pTstEnv->enmMode == AUDIOTESTMODE_HOST ? "host" : "guest");
1203 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Using tag '%s'\n", pTstEnv->szTag);
1204 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Output directory is '%s'\n", pTstEnv->szPathOut);
1205 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Temp directory is '%s'\n", pTstEnv->szPathTemp);
1206
1207 if (!pTstEnv->cMsBufferSize)
1208 pTstEnv->cMsBufferSize = UINT32_MAX;
1209 if (!pTstEnv->cMsPreBuffer)
1210 pTstEnv->cMsPreBuffer = UINT32_MAX;
1211 if (!pTstEnv->cMsSchedulingHint)
1212 pTstEnv->cMsSchedulingHint = UINT32_MAX;
1213
1214 char szPathTemp[RTPATH_MAX];
1215 if ( !strlen(pTstEnv->szPathTemp)
1216 || !strlen(pTstEnv->szPathOut))
1217 rc = RTPathTemp(szPathTemp, sizeof(szPathTemp));
1218
1219 if ( RT_SUCCESS(rc)
1220 && !strlen(pTstEnv->szPathTemp))
1221 rc = RTPathJoin(pTstEnv->szPathTemp, sizeof(pTstEnv->szPathTemp), szPathTemp, "vkat-temp");
1222
1223 if (RT_SUCCESS(rc))
1224 {
1225 rc = RTDirCreate(pTstEnv->szPathTemp, RTFS_UNIX_IRWXU, 0 /* fFlags */);
1226 if (rc == VERR_ALREADY_EXISTS)
1227 rc = VINF_SUCCESS;
1228 }
1229
1230 if ( RT_SUCCESS(rc)
1231 && !strlen(pTstEnv->szPathOut))
1232 rc = RTPathJoin(pTstEnv->szPathOut, sizeof(pTstEnv->szPathOut), szPathTemp, "vkat");
1233
1234 if (RT_SUCCESS(rc))
1235 {
1236 rc = RTDirCreate(pTstEnv->szPathOut, RTFS_UNIX_IRWXU, 0 /* fFlags */);
1237 if (rc == VERR_ALREADY_EXISTS)
1238 rc = VINF_SUCCESS;
1239 }
1240
1241 if (RT_FAILURE(rc))
1242 return rc;
1243
1244 /**
1245 * For NAT'ed VMs we use (default):
1246 * - client mode (uConnectAddr / uConnectPort) on the guest.
1247 * - server mode (uBindAddr / uBindPort) on the host.
1248 */
1249 if ( !pTstEnv->TcpOpts.szConnectAddr[0]
1250 && !pTstEnv->TcpOpts.szBindAddr[0])
1251 RTStrCopy(pTstEnv->TcpOpts.szBindAddr, sizeof(pTstEnv->TcpOpts.szBindAddr), "0.0.0.0");
1252
1253 /*
1254 * Determine connection mode based on set variables.
1255 */
1256 if ( pTstEnv->TcpOpts.szBindAddr[0]
1257 && pTstEnv->TcpOpts.szConnectAddr[0])
1258 {
1259 pTstEnv->TcpOpts.enmConnMode = ATSCONNMODE_BOTH;
1260 }
1261 else if (pTstEnv->TcpOpts.szBindAddr[0])
1262 pTstEnv->TcpOpts.enmConnMode = ATSCONNMODE_SERVER;
1263 else /* "Reversed mode", i.e. used for NATed VMs. */
1264 pTstEnv->TcpOpts.enmConnMode = ATSCONNMODE_CLIENT;
1265
1266 /* Set a back reference to the test environment for the callback context. */
1267 pTstEnv->CallbackCtx.pTstEnv = pTstEnv;
1268
1269 ATSCALLBACKS Callbacks;
1270 RT_ZERO(Callbacks);
1271 Callbacks.pvUser = &pTstEnv->CallbackCtx;
1272
1273 if (pTstEnv->enmMode == AUDIOTESTMODE_GUEST)
1274 {
1275 Callbacks.pfnHowdy = audioTestGstAtsHowdyCallback;
1276 Callbacks.pfnBye = audioTestGstAtsByeCallback;
1277 Callbacks.pfnTestSetBegin = audioTestGstAtsTestSetBeginCallback;
1278 Callbacks.pfnTestSetEnd = audioTestGstAtsTestSetEndCallback;
1279 Callbacks.pfnTonePlay = audioTestGstAtsTonePlayCallback;
1280 Callbacks.pfnToneRecord = audioTestGstAtsToneRecordCallback;
1281 Callbacks.pfnTestSetSendBegin = audioTestGstAtsTestSetSendBeginCallback;
1282 Callbacks.pfnTestSetSendRead = audioTestGstAtsTestSetSendReadCallback;
1283 Callbacks.pfnTestSetSendEnd = audioTestGstAtsTestSetSendEndCallback;
1284
1285 if (!pTstEnv->TcpOpts.uBindPort)
1286 pTstEnv->TcpOpts.uBindPort = ATS_TCP_DEF_BIND_PORT_GUEST;
1287
1288 if (!pTstEnv->TcpOpts.uConnectPort)
1289 pTstEnv->TcpOpts.uConnectPort = ATS_TCP_DEF_CONNECT_PORT_GUEST;
1290
1291 pTstEnv->pSrv = (PATSSERVER)RTMemAlloc(sizeof(ATSSERVER));
1292 AssertPtrReturn(pTstEnv->pSrv, VERR_NO_MEMORY);
1293
1294 /*
1295 * Start the ATS (Audio Test Service) on the guest side.
1296 * That service then will perform playback and recording operations on the guest, triggered from the host.
1297 *
1298 * When running this in self-test mode, that service also can be run on the host if nothing else is specified.
1299 * Note that we have to bind to "0.0.0.0" by default so that the host can connect to it.
1300 */
1301 rc = audioTestEnvConfigureAndStartTcpServer(pTstEnv->pSrv, &Callbacks, "guest", &pTstEnv->TcpOpts);
1302 }
1303 else /* Host mode */
1304 {
1305 if (!pTstEnv->TcpOpts.uBindPort)
1306 pTstEnv->TcpOpts.uBindPort = ATS_TCP_DEF_BIND_PORT_HOST;
1307
1308 if (!pTstEnv->TcpOpts.uConnectPort)
1309 pTstEnv->TcpOpts.uConnectPort = ATS_TCP_DEF_CONNECT_PORT_HOST_PORT_FWD;
1310
1311 /**
1312 * Note: Don't set pTstEnv->TcpOpts.szTcpConnectAddr by default here, as this specifies what connection mode
1313 * (client / server / both) we use on the host.
1314 */
1315
1316 /* We need to start a server on the host so that VMs configured with NAT networking
1317 * can connect to it as well. */
1318 rc = AudioTestSvcClientCreate(&pTstEnv->u.Host.AtsClGuest);
1319 if (RT_SUCCESS(rc))
1320 rc = audioTestEnvConnectViaTcp(pTstEnv, &pTstEnv->u.Host.AtsClGuest,
1321 "host -> guest", &pTstEnv->TcpOpts);
1322 if (RT_SUCCESS(rc))
1323 {
1324 AUDIOTESTENVTCPOPTS ValKitTcpOpts;
1325 RT_ZERO(ValKitTcpOpts);
1326
1327 /* We only connect as client to the Validation Kit audio driver ATS. */
1328 ValKitTcpOpts.enmConnMode = ATSCONNMODE_CLIENT;
1329
1330 /* For now we ASSUME that the Validation Kit audio driver ATS runs on the same host as VKAT (this binary) runs on. */
1331 ValKitTcpOpts.uConnectPort = ATS_TCP_DEF_CONNECT_PORT_VALKIT; /** @todo Make this dynamic. */
1332 RTStrCopy(ValKitTcpOpts.szConnectAddr, sizeof(ValKitTcpOpts.szConnectAddr), ATS_TCP_DEF_CONNECT_HOST_ADDR_STR); /** @todo Ditto. */
1333
1334 rc = AudioTestSvcClientCreate(&pTstEnv->u.Host.AtsClValKit);
1335 if (RT_SUCCESS(rc))
1336 {
1337 rc = audioTestEnvConnectViaTcp(pTstEnv, &pTstEnv->u.Host.AtsClValKit,
1338 "host -> valkit", &ValKitTcpOpts);
1339 if (RT_FAILURE(rc))
1340 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Unable to connect to the Validation Kit audio driver!\n"
1341 "There could be multiple reasons:\n\n"
1342 " - Wrong host being used\n"
1343 " - VirtualBox host version is too old\n"
1344 " - Audio debug mode is not enabled\n"
1345 " - Support for Validation Kit audio driver is not included\n"
1346 " - Firewall / network configuration problem\n");
1347 }
1348 }
1349 }
1350
1351 return rc;
1352}
1353
1354/**
1355 * Destroys an audio test environment.
1356 *
1357 * @param pTstEnv Audio test environment to destroy.
1358 */
1359void audioTestEnvDestroy(PAUDIOTESTENV pTstEnv)
1360{
1361 if (!pTstEnv)
1362 return;
1363
1364 /* When in host mode, we need to destroy our ATS clients in order to also let
1365 * the ATS server(s) know we're going to quit. */
1366 if (pTstEnv->enmMode == AUDIOTESTMODE_HOST)
1367 {
1368 AudioTestSvcClientDestroy(&pTstEnv->u.Host.AtsClValKit);
1369 AudioTestSvcClientDestroy(&pTstEnv->u.Host.AtsClGuest);
1370 }
1371
1372 if (pTstEnv->pSrv)
1373 {
1374 int rc2 = AudioTestSvcDestroy(pTstEnv->pSrv);
1375 AssertRC(rc2);
1376
1377 RTMemFree(pTstEnv->pSrv);
1378 pTstEnv->pSrv = NULL;
1379 }
1380
1381 for (unsigned i = 0; i < RT_ELEMENTS(pTstEnv->aStreams); i++)
1382 {
1383 int rc2 = audioTestStreamDestroy(pTstEnv, &pTstEnv->aStreams[i]);
1384 if (RT_FAILURE(rc2))
1385 RTTestFailed(g_hTest, "Stream destruction for stream #%u failed with %Rrc\n", i, rc2);
1386 }
1387
1388 /* Try cleaning up a bit. */
1389 RTDirRemove(pTstEnv->szPathTemp);
1390 RTDirRemove(pTstEnv->szPathOut);
1391
1392 pTstEnv->pDrvStack = NULL;
1393}
1394
1395/**
1396 * Closes, packs up and destroys a test environment.
1397 *
1398 * @returns VBox status code.
1399 * @param pTstEnv Test environment to handle.
1400 * @param fPack Whether to pack the test set up before destroying / wiping it.
1401 * @param pszPackFile Where to store the packed test set file on success. Can be NULL if \a fPack is \c false.
1402 * @param cbPackFile Size (in bytes) of \a pszPackFile. Can be 0 if \a fPack is \c false.
1403 */
1404int audioTestEnvPrologue(PAUDIOTESTENV pTstEnv, bool fPack, char *pszPackFile, size_t cbPackFile)
1405{
1406 /* Close the test set first. */
1407 AudioTestSetClose(&pTstEnv->Set);
1408
1409 int rc = VINF_SUCCESS;
1410
1411 if (fPack)
1412 {
1413 /* Before destroying the test environment, pack up the test set so
1414 * that it's ready for transmission. */
1415 rc = AudioTestSetPack(&pTstEnv->Set, pTstEnv->szPathOut, pszPackFile, cbPackFile);
1416 if (RT_SUCCESS(rc))
1417 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test set packed up to '%s'\n", pszPackFile);
1418 }
1419
1420 if (!g_fDrvAudioDebug) /* Don't wipe stuff when debugging. Can be useful for introspecting data. */
1421 /* ignore rc */ AudioTestSetWipe(&pTstEnv->Set);
1422
1423 AudioTestSetDestroy(&pTstEnv->Set);
1424
1425 if (RT_FAILURE(rc))
1426 RTTestFailed(g_hTest, "Test set prologue failed with %Rrc\n", rc);
1427
1428 return rc;
1429}
1430
1431/**
1432 * Initializes an audio test parameters set.
1433 *
1434 * @param pTstParms Test parameters set to initialize.
1435 */
1436void audioTestParmsInit(PAUDIOTESTPARMS pTstParms)
1437{
1438 RT_ZERO(*pTstParms);
1439}
1440
1441/**
1442 * Destroys an audio test parameters set.
1443 *
1444 * @param pTstParms Test parameters set to destroy.
1445 */
1446void audioTestParmsDestroy(PAUDIOTESTPARMS pTstParms)
1447{
1448 if (!pTstParms)
1449 return;
1450
1451 return;
1452}
1453
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette