VirtualBox

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

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