VirtualBox

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

Last change on this file since 106212 was 106061, checked in by vboxsync, 3 months ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 72.3 KB
Line 
1/* $Id: vkatCommon.cpp 106061 2024-09-16 14:03:52Z vboxsync $ */
2/** @file
3 * Validation Kit Audio Test (VKAT) - Common code.
4 */
5
6/*
7 * Copyright (C) 2021-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#define LOG_GROUP LOG_GROUP_AUDIO_TEST
42#include <iprt/log.h>
43
44#ifdef VBOX_WITH_AUDIO_ALSA
45# include "DrvHostAudioAlsaStubsMangling.h"
46# include <alsa/asoundlib.h>
47# include <alsa/control.h> /* For device enumeration. */
48# include <alsa/version.h>
49# include "DrvHostAudioAlsaStubs.h"
50#endif
51#ifdef VBOX_WITH_AUDIO_OSS
52# include <errno.h>
53# include <fcntl.h>
54# include <sys/ioctl.h>
55# include <sys/mman.h>
56# include <sys/soundcard.h>
57# include <unistd.h>
58#endif
59#ifdef RT_OS_WINDOWS
60# include <iprt/win/windows.h>
61# include <iprt/win/audioclient.h>
62# include <endpointvolume.h> /* For IAudioEndpointVolume. */
63# include <audiopolicy.h> /* For IAudioSessionManager. */
64# include <AudioSessionTypes.h>
65# include <Mmdeviceapi.h>
66#endif
67
68#include <iprt/circbuf.h>
69#include <iprt/ctype.h>
70#include <iprt/dir.h>
71#include <iprt/errcore.h>
72#include <iprt/getopt.h>
73#include <iprt/message.h>
74#include <iprt/rand.h>
75#include <iprt/test.h>
76
77#include "Audio/AudioHlp.h"
78#include "Audio/AudioTest.h"
79#include "Audio/AudioTestService.h"
80#include "Audio/AudioTestServiceClient.h"
81
82#include "vkatInternal.h"
83
84
85/*********************************************************************************************************************************
86* Defined Constants And Macros *
87*********************************************************************************************************************************/
88
89
90/*********************************************************************************************************************************
91* Internal Functions *
92*********************************************************************************************************************************/
93static int audioTestStreamInit(PAUDIOTESTDRVSTACK pDrvStack, PAUDIOTESTSTREAM pStream, PDMAUDIODIR enmDir, PAUDIOTESTIOOPTS pPlayOpt);
94static int audioTestStreamDestroy(PAUDIOTESTDRVSTACK pDrvStack, PAUDIOTESTSTREAM pStream);
95
96
97/*********************************************************************************************************************************
98* Volume handling. *
99*********************************************************************************************************************************/
100
101#ifdef VBOX_WITH_AUDIO_ALSA
102/**
103 * Sets the system's master volume via ALSA, if available.
104 *
105 * @returns VBox status code.
106 * @param uVolPercent Volume (in percent) to set.
107 */
108static int audioTestSetMasterVolumeALSA(unsigned uVolPercent)
109{
110 int rc = audioLoadAlsaLib();
111 if (RT_FAILURE(rc))
112 return rc;
113
114 int err;
115 snd_mixer_t *handle;
116
117# define ALSA_CHECK_RET(a_Exp, a_Text) \
118 if (!(a_Exp)) \
119 { \
120 AssertLogRelMsg(a_Exp, a_Text); \
121 if (handle) \
122 snd_mixer_close(handle); \
123 return VERR_GENERAL_FAILURE; \
124 }
125
126# define ALSA_CHECK_ERR_RET(a_Text) \
127 ALSA_CHECK_RET(err >= 0, a_Text)
128
129 err = snd_mixer_open(&handle, 0 /* Index */);
130 ALSA_CHECK_ERR_RET(("ALSA: Failed to open mixer: %s\n", snd_strerror(err)));
131 err = snd_mixer_attach(handle, "default");
132 ALSA_CHECK_ERR_RET(("ALSA: Failed to attach to default sink: %s\n", snd_strerror(err)));
133 err = snd_mixer_selem_register(handle, NULL, NULL);
134 ALSA_CHECK_ERR_RET(("ALSA: Failed to attach to default sink: %s\n", snd_strerror(err)));
135 err = snd_mixer_load(handle);
136 ALSA_CHECK_ERR_RET(("ALSA: Failed to load mixer: %s\n", snd_strerror(err)));
137
138 snd_mixer_selem_id_t *sid = NULL;
139 snd_mixer_selem_id_alloca(&sid);
140
141 snd_mixer_selem_id_set_index(sid, 0 /* Index */);
142 snd_mixer_selem_id_set_name(sid, "Master");
143
144 snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);
145 ALSA_CHECK_RET(elem != NULL, ("ALSA: Failed to find mixer element: %s\n", snd_strerror(err)));
146
147 long uVolMin, uVolMax;
148 snd_mixer_selem_get_playback_volume_range(elem, &uVolMin, &uVolMax);
149 ALSA_CHECK_ERR_RET(("ALSA: Failed to get playback volume range: %s\n", snd_strerror(err)));
150
151 long const uVol = RT_MIN(uVolPercent, 100) * uVolMax / 100;
152
153 err = snd_mixer_selem_set_playback_volume(elem, SND_MIXER_SCHN_FRONT_LEFT, uVol);
154 ALSA_CHECK_ERR_RET(("ALSA: Failed to set playback volume left: %s\n", snd_strerror(err)));
155 err = snd_mixer_selem_set_playback_volume(elem, SND_MIXER_SCHN_FRONT_RIGHT, uVol);
156 ALSA_CHECK_ERR_RET(("ALSA: Failed to set playback volume right: %s\n", snd_strerror(err)));
157
158 snd_mixer_close(handle);
159
160 return VINF_SUCCESS;
161
162# undef ALSA_CHECK_RET
163# undef ALSA_CHECK_ERR_RET
164}
165#endif /* VBOX_WITH_AUDIO_ALSA */
166
167#ifdef VBOX_WITH_AUDIO_OSS
168/**
169 * Sets the system's master volume via OSS, if available.
170 *
171 * @returns VBox status code.
172 * @param uVolPercent Volume (in percent) to set.
173 */
174static int audioTestSetMasterVolumeOSS(unsigned uVolPercent)
175{
176 int hFile = open("/dev/dsp", O_WRONLY | O_NONBLOCK, 0);
177 if (hFile == -1)
178 {
179 /* Try opening the mixing device instead. */
180 hFile = open("/dev/mixer", O_RDONLY | O_NONBLOCK, 0);
181 }
182
183 if (hFile != -1)
184 {
185 /* OSS maps 0 (muted) - 100 (max), so just use uVolPercent unmodified here. */
186 uint16_t uVol = RT_MAKE_U16(uVolPercent, uVolPercent);
187 AssertLogRelMsgReturnStmt(ioctl(hFile, SOUND_MIXER_PCM /* SNDCTL_DSP_SETPLAYVOL */, &uVol) >= 0,
188 ("OSS: Failed to set DSP playback volume: %s (%d)\n",
189 strerror(errno), errno), close(hFile), RTErrConvertFromErrno(errno));
190 return VINF_SUCCESS;
191 }
192
193 return VERR_NOT_SUPPORTED;
194}
195#endif /* VBOX_WITH_AUDIO_OSS */
196
197#ifdef RT_OS_WINDOWS
198static int audioTestSetMasterVolumeWASAPI(unsigned uVolPercent)
199{
200 HRESULT hr;
201
202# define WASAPI_CHECK_HR_RET(a_Text) \
203 if (FAILED(hr)) \
204 { \
205 AssertLogRelMsgFailed(a_Text); \
206 return VERR_GENERAL_FAILURE; \
207 }
208
209 hr = CoInitialize(NULL);
210 WASAPI_CHECK_HR_RET(("CoInitialize() failed, hr=%Rhrc", hr));
211 IMMDeviceEnumerator* pIEnumerator = NULL;
212 hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void **)&pIEnumerator);
213 WASAPI_CHECK_HR_RET(("WASAPI: Unable to create IMMDeviceEnumerator, hr=%Rhrc", hr));
214
215 IMMDevice *pIMMDevice = NULL;
216 hr = pIEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eConsole, &pIMMDevice);
217 WASAPI_CHECK_HR_RET(("WASAPI: Unable to get audio endpoint, hr=%Rhrc", hr));
218 pIEnumerator->Release();
219
220 IAudioEndpointVolume *pIAudioEndpointVolume = NULL;
221 hr = pIMMDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, (void **)&pIAudioEndpointVolume);
222 WASAPI_CHECK_HR_RET(("WASAPI: Unable to activate audio endpoint volume, hr=%Rhrc", hr));
223 pIMMDevice->Release();
224
225 float dbMin, dbMax, dbInc;
226 hr = pIAudioEndpointVolume->GetVolumeRange(&dbMin, &dbMax, &dbInc);
227 WASAPI_CHECK_HR_RET(("WASAPI: Unable to get volume range, hr=%Rhrc", hr));
228
229 float const dbSteps = (dbMax - dbMin) / dbInc;
230 float const dbStepsPerPercent = (dbSteps * dbInc) / 100;
231 float const dbVol = dbMin + (dbStepsPerPercent * (float(RT_MIN(uVolPercent, 100.0))));
232
233 hr = pIAudioEndpointVolume->SetMasterVolumeLevel(dbVol, NULL);
234 WASAPI_CHECK_HR_RET(("WASAPI: Unable to set master volume level, hr=%Rhrc", hr));
235 pIAudioEndpointVolume->Release();
236
237 return VINF_SUCCESS;
238
239# undef WASAPI_CHECK_HR_RET
240}
241#endif /* RT_OS_WINDOWS */
242
243/**
244 * Sets the system's master volume, if available.
245 *
246 * @returns VBox status code. VERR_NOT_SUPPORTED if not supported.
247 * @param uVolPercent Volume (in percent) to set.
248 */
249static int audioTestSetMasterVolume(unsigned uVolPercent)
250{
251 int rc = VINF_SUCCESS;
252
253#ifdef VBOX_WITH_AUDIO_ALSA
254 rc = audioTestSetMasterVolumeALSA(uVolPercent);
255 if (RT_SUCCESS(rc))
256 return rc;
257 /* else try OSS (if available) below. */
258#endif /* VBOX_WITH_AUDIO_ALSA */
259
260#ifdef VBOX_WITH_AUDIO_OSS
261 rc = audioTestSetMasterVolumeOSS(uVolPercent);
262 if (RT_SUCCESS(rc))
263 return rc;
264#endif /* VBOX_WITH_AUDIO_OSS */
265
266#ifdef RT_OS_WINDOWS
267 rc = audioTestSetMasterVolumeWASAPI(uVolPercent);
268 if (RT_SUCCESS(rc))
269 return rc;
270#endif
271
272 RT_NOREF(rc, uVolPercent);
273 /** @todo Port other platforms. */
274 return VERR_NOT_SUPPORTED;
275}
276
277
278/*********************************************************************************************************************************
279* Device enumeration + handling. *
280*********************************************************************************************************************************/
281
282/**
283 * Enumerates audio devices and optionally searches for a specific device.
284 *
285 * @returns VBox status code.
286 * @param pDrvStack Driver stack to use for enumeration.
287 * @param pszDev Device name to search for. Can be NULL if the default device shall be used.
288 * @param ppDev Where to return the pointer of the device enumeration of \a pTstEnv when a
289 * specific device was found.
290 */
291int audioTestDevicesEnumerateAndCheck(PAUDIOTESTDRVSTACK pDrvStack, const char *pszDev, PPDMAUDIOHOSTDEV *ppDev)
292{
293 RTTestSubF(g_hTest, "Enumerating audio devices and checking for device '%s'", pszDev && *pszDev ? pszDev : "[Default]");
294
295 if (!pDrvStack->pIHostAudio->pfnGetDevices)
296 {
297 RTTestSkipped(g_hTest, "Backend does not support device enumeration, skipping");
298 return VINF_NOT_SUPPORTED;
299 }
300
301 Assert(pszDev == NULL || ppDev);
302
303 if (ppDev)
304 *ppDev = NULL;
305
306 int rc = pDrvStack->pIHostAudio->pfnGetDevices(pDrvStack->pIHostAudio, &pDrvStack->DevEnum);
307 if (RT_SUCCESS(rc))
308 {
309 PPDMAUDIOHOSTDEV pDev;
310 RTListForEach(&pDrvStack->DevEnum.LstDevices, pDev, PDMAUDIOHOSTDEV, ListEntry)
311 {
312 char szFlags[PDMAUDIOHOSTDEV_MAX_FLAGS_STRING_LEN];
313 if (pDev->pszId)
314 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Device '%s' (ID '%s'):\n", pDev->pszName, pDev->pszId);
315 else
316 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Device '%s':\n", pDev->pszName);
317 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Usage = %s\n", PDMAudioDirGetName(pDev->enmUsage));
318 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Flags = %s\n", PDMAudioHostDevFlagsToString(szFlags, pDev->fFlags));
319 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Input channels = %RU8\n", pDev->cMaxInputChannels);
320 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enum: Output channels = %RU8\n", pDev->cMaxOutputChannels);
321
322 if ( (pszDev && *pszDev)
323 && !RTStrCmp(pDev->pszName, pszDev))
324 {
325 *ppDev = pDev;
326 }
327 }
328 }
329 else
330 RTTestFailed(g_hTest, "Enumerating audio devices failed with %Rrc", rc);
331
332 if (RT_SUCCESS(rc))
333 {
334 if ( (pszDev && *pszDev)
335 && *ppDev == NULL)
336 {
337 RTTestFailed(g_hTest, "Audio device '%s' not found", pszDev);
338 rc = VERR_NOT_FOUND;
339 }
340 }
341
342 RTTestSubDone(g_hTest);
343 return rc;
344}
345
346static int audioTestStreamInit(PAUDIOTESTDRVSTACK pDrvStack, PAUDIOTESTSTREAM pStream,
347 PDMAUDIODIR enmDir, PAUDIOTESTIOOPTS pIoOpts)
348{
349 int rc;
350
351 if (enmDir == PDMAUDIODIR_IN)
352 rc = audioTestDriverStackStreamCreateInput(pDrvStack, &pIoOpts->Props, pIoOpts->cMsBufferSize,
353 pIoOpts->cMsPreBuffer, pIoOpts->cMsSchedulingHint, &pStream->pStream, &pStream->Cfg);
354 else if (enmDir == PDMAUDIODIR_OUT)
355 rc = audioTestDriverStackStreamCreateOutput(pDrvStack, &pIoOpts->Props, pIoOpts->cMsBufferSize,
356 pIoOpts->cMsPreBuffer, pIoOpts->cMsSchedulingHint, &pStream->pStream, &pStream->Cfg);
357 else
358 rc = VERR_NOT_SUPPORTED;
359
360 if (RT_SUCCESS(rc))
361 {
362 if (!pDrvStack->pIAudioConnector)
363 {
364 pStream->pBackend = &((PAUDIOTESTDRVSTACKSTREAM)pStream->pStream)->Backend;
365 }
366 else
367 pStream->pBackend = NULL;
368
369 /*
370 * Automatically enable the mixer if the PCM properties don't match.
371 */
372 if ( !pIoOpts->fWithMixer
373 && !PDMAudioPropsAreEqual(&pIoOpts->Props, &pStream->Cfg.Props))
374 {
375 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Enabling stream mixer\n");
376 pIoOpts->fWithMixer = true;
377 }
378
379 rc = AudioTestMixStreamInit(&pStream->Mix, pDrvStack, pStream->pStream,
380 pIoOpts->fWithMixer ? &pIoOpts->Props : NULL, 100 /* ms */); /** @todo Configure mixer buffer? */
381 }
382
383 if (RT_FAILURE(rc))
384 RTTestFailed(g_hTest, "Initializing %s stream failed with %Rrc", enmDir == PDMAUDIODIR_IN ? "input" : "output", rc);
385
386 return rc;
387}
388
389/**
390 * Destroys an audio test stream.
391 *
392 * @returns VBox status code.
393 * @param pDrvStack Driver stack the stream belongs to.
394 * @param pStream Audio stream to destroy.
395 */
396static int audioTestStreamDestroy(PAUDIOTESTDRVSTACK pDrvStack, PAUDIOTESTSTREAM pStream)
397{
398 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
399
400 if (pStream->pStream)
401 {
402 /** @todo Anything else to do here, e.g. test if there are left over samples or some such? */
403
404 audioTestDriverStackStreamDestroy(pDrvStack, pStream->pStream);
405 pStream->pStream = NULL;
406 pStream->pBackend = NULL;
407 }
408
409 AudioTestMixStreamTerm(&pStream->Mix);
410
411 return VINF_SUCCESS;
412}
413
414
415/*********************************************************************************************************************************
416* Test Primitives *
417*********************************************************************************************************************************/
418
419/**
420 * Initializes test tone parameters (partly with random values).
421
422 * @param pToneParms Test tone parameters to initialize.
423 */
424void audioTestToneParmsInit(PAUDIOTESTTONEPARMS pToneParms)
425{
426 RT_BZERO(pToneParms, sizeof(AUDIOTESTTONEPARMS));
427
428 /**
429 * Set default (randomized) test tone parameters if not set explicitly.
430 */
431 pToneParms->dbFreqHz = AudioTestToneGetRandomFreq();
432 pToneParms->msDuration = RTRandU32Ex(200, RT_MS_30SEC);
433 pToneParms->uVolumePercent = 100; /* We always go with maximum volume for now. */
434
435 PDMAudioPropsInit(&pToneParms->Props,
436 2 /* 16-bit */, true /* fPcmSigned */, 2 /* cPcmChannels */, 44100 /* uPcmHz */);
437}
438
439/**
440 * Initializes I/O options with some sane default values.
441 *
442 * @param pIoOpts I/O options to initialize.
443 */
444void audioTestIoOptsInitDefaults(PAUDIOTESTIOOPTS pIoOpts)
445{
446 RT_BZERO(pIoOpts, sizeof(AUDIOTESTIOOPTS));
447
448 /* Initialize the PCM properties to some sane values. */
449 PDMAudioPropsInit(&pIoOpts->Props,
450 2 /* 16-bit */, true /* fPcmSigned */, 2 /* cPcmChannels */, 44100 /* uPcmHz */);
451
452 pIoOpts->cMsBufferSize = UINT32_MAX;
453 pIoOpts->cMsPreBuffer = UINT32_MAX;
454 pIoOpts->cMsSchedulingHint = UINT32_MAX;
455 pIoOpts->uVolumePercent = 100; /* Use maximum volume by default. */
456}
457
458#if 0 /* Unused */
459/**
460 * Returns a random scheduling hint (in ms).
461 */
462DECLINLINE(uint32_t) audioTestEnvGetRandomSchedulingHint(void)
463{
464 static const unsigned s_aSchedulingHintsMs[] =
465 {
466 10,
467 25,
468 50,
469 100,
470 200,
471 250
472 };
473
474 return s_aSchedulingHintsMs[RTRandU32Ex(0, RT_ELEMENTS(s_aSchedulingHintsMs) - 1)];
475}
476#endif
477
478/**
479 * Plays a test tone on a specific audio test stream.
480 *
481 * @returns VBox status code.
482 * @param pIoOpts I/O options to use.
483 * @param pTstEnv Test environment to use for running the test.
484 * Optional and can be NULL (for simple playback only).
485 * @param pStream Stream to use for playing the tone.
486 * @param pParms Tone parameters to use.
487 *
488 * @note Blocking function.
489 */
490int audioTestPlayTone(PAUDIOTESTIOOPTS pIoOpts, PAUDIOTESTENV pTstEnv, PAUDIOTESTSTREAM pStream, PAUDIOTESTTONEPARMS pParms)
491{
492 uint32_t const idxTest = (uint8_t)pParms->Hdr.idxTest;
493
494 AUDIOTESTTONE TstTone;
495 AudioTestToneInit(&TstTone, &pStream->Cfg.Props, pParms->dbFreqHz);
496
497 char const *pcszPathOut = NULL;
498 if (pTstEnv)
499 pcszPathOut = pTstEnv->Set.szPathAbs;
500
501 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Playing test tone (tone frequency is %RU16Hz, %RU32ms, %RU8%% volume)\n",
502 idxTest, (uint16_t)pParms->dbFreqHz, pParms->msDuration, pParms->uVolumePercent);
503 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Using %RU32ms stream scheduling hint\n",
504 idxTest, pStream->Cfg.Device.cMsSchedulingHint);
505 if (pcszPathOut)
506 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Writing to '%s'\n", idxTest, pcszPathOut);
507
508 int rc;
509
510 /** @todo Use .WAV here? */
511 AUDIOTESTOBJ Obj;
512 RT_ZERO(Obj); /* Shut up MSVC. */
513 if (pTstEnv)
514 {
515 rc = AudioTestSetObjCreateAndRegister(&pTstEnv->Set, "guest-tone-play.pcm", &Obj);
516 AssertRCReturn(rc, rc);
517 }
518
519 uint8_t const uVolPercent = pIoOpts->uVolumePercent;
520 int rc2 = audioTestSetMasterVolume(uVolPercent);
521 if (RT_FAILURE(rc2))
522 {
523 if (rc2 == VERR_NOT_SUPPORTED)
524 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Setting system's master volume is not supported on this platform, skipping\n");
525 else
526 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Setting system's master volume failed with %Rrc\n", rc2);
527 }
528 else
529 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Set system's master volume to %RU8%%\n", uVolPercent);
530
531 rc = AudioTestMixStreamEnable(&pStream->Mix);
532 if ( RT_SUCCESS(rc)
533 && AudioTestMixStreamIsOkay(&pStream->Mix))
534 {
535 uint32_t cbToWriteTotal = PDMAudioPropsMilliToBytes(&pStream->Cfg.Props, pParms->msDuration);
536 AssertStmt(cbToWriteTotal, rc = VERR_INVALID_PARAMETER);
537 uint32_t cbWrittenTotal = 0;
538
539 /* We play a pre + post beacon before + after the actual test tone.
540 * We always start with the pre beacon. */
541 AUDIOTESTTONEBEACON Beacon;
542 AudioTestBeaconInit(&Beacon, (uint8_t)pParms->Hdr.idxTest, AUDIOTESTTONEBEACONTYPE_PLAY_PRE, &pStream->Cfg.Props);
543
544 uint32_t const cbBeacon = AudioTestBeaconGetSize(&Beacon);
545 if (cbBeacon)
546 {
547 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Playing 2 x %RU32 bytes pre/post beacons\n",
548 idxTest, cbBeacon);
549
550 if (g_uVerbosity >= 2)
551 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Playing %s beacon ...\n",
552 idxTest, AudioTestBeaconTypeGetName(Beacon.enmType));
553 }
554
555 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Playing %RU32 bytes total (%RU32ms timeout)\n",
556 idxTest, cbToWriteTotal, pTstEnv->msTimeout);
557
558 /* Failsafe if invalid timeout is set. */
559 if ( pTstEnv->msTimeout == 0
560 || pTstEnv->msTimeout == UINT32_MAX)
561 {
562 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Warning! Invalid timeout set (%RU32ms), setting default\n",
563 idxTest, pTstEnv->msTimeout);
564 pTstEnv->msTimeout = AUDIOTEST_TIMEOUT_DEFAULT_MS;
565 }
566
567 AudioTestObjAddMetadataStr(Obj, "test_id=%04RU32\n", pParms->Hdr.idxTest);
568 AudioTestObjAddMetadataStr(Obj, "beacon_type=%RU32\n", (uint32_t)AudioTestBeaconGetType(&Beacon));
569 AudioTestObjAddMetadataStr(Obj, "beacon_pre_bytes=%RU32\n", cbBeacon);
570 AudioTestObjAddMetadataStr(Obj, "beacon_post_bytes=%RU32\n", cbBeacon);
571 AudioTestObjAddMetadataStr(Obj, "stream_to_write_total_bytes=%RU32\n", cbToWriteTotal);
572 AudioTestObjAddMetadataStr(Obj, "stream_period_size_frames=%RU32\n", pStream->Cfg.Backend.cFramesPeriod);
573 AudioTestObjAddMetadataStr(Obj, "stream_buffer_size_frames=%RU32\n", pStream->Cfg.Backend.cFramesBufferSize);
574 AudioTestObjAddMetadataStr(Obj, "stream_prebuf_size_frames=%RU32\n", pStream->Cfg.Backend.cFramesPreBuffering);
575 /* Note: This mostly is provided by backend (e.g. PulseAudio / ALSA / ++) and
576 * has nothing to do with the device emulation scheduling hint. */
577 AudioTestObjAddMetadataStr(Obj, "device_scheduling_hint_ms=%RU32\n", pStream->Cfg.Device.cMsSchedulingHint);
578
579 PAUDIOTESTDRVMIXSTREAM pMix = &pStream->Mix;
580
581 uint32_t const cbPreBuffer = PDMAudioPropsFramesToBytes(pMix->pProps, pStream->Cfg.Backend.cFramesPreBuffering);
582 uint64_t const nsStarted = RTTimeNanoTS();
583 uint64_t nsDonePreBuffering = 0;
584
585 uint64_t offStream = 0;
586 uint64_t nsTimeout = uint64_t(pTstEnv->msTimeout) * RT_NS_1MS_64;
587 uint64_t nsLastMsgCantWrite = 0; /* Timestamp (in ns) when the last message of an unwritable stream was shown. */
588 uint64_t nsLastWrite = 0;
589
590 AUDIOTESTSTATE enmState = AUDIOTESTSTATE_PRE;
591 uint8_t abBuf[_16K];
592
593 for (;;)
594 {
595 uint64_t const nsNow = RTTimeNanoTS();
596 if (!nsLastWrite)
597 nsLastWrite = nsNow;
598
599 /* Pace ourselves a little. */
600 if (offStream >= cbPreBuffer)
601 {
602 if (!nsDonePreBuffering)
603 nsDonePreBuffering = nsNow;
604 uint64_t const cNsWritten = PDMAudioPropsBytesToNano64(pMix->pProps, offStream - cbPreBuffer);
605 uint64_t const cNsElapsed = nsNow - nsStarted;
606 if (cNsWritten > cNsElapsed + RT_NS_10MS)
607 RTThreadSleep(uint32_t(cNsWritten - cNsElapsed - RT_NS_10MS / 2) / RT_NS_1MS);
608 }
609
610 uint32_t cbWritten = 0;
611 uint32_t const cbCanWrite = AudioTestMixStreamGetWritable(&pStream->Mix);
612 if (cbCanWrite)
613 {
614 if (g_uVerbosity >= 4)
615 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Stream is writable with %RU64ms (%RU32 bytes)\n",
616 idxTest, PDMAudioPropsBytesToMilli(pMix->pProps, cbCanWrite), cbCanWrite);
617
618 switch (enmState)
619 {
620 case AUDIOTESTSTATE_PRE:
621 RT_FALL_THROUGH();
622 case AUDIOTESTSTATE_POST:
623 {
624 if (g_uVerbosity >= 4)
625 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: %RU32 bytes (%RU64ms) beacon data remaining\n",
626 idxTest, AudioTestBeaconGetRemaining(&Beacon),
627 PDMAudioPropsBytesToMilli(&pStream->pStream->Cfg.Props, AudioTestBeaconGetRemaining(&Beacon)));
628
629 bool fGoToNextStage = false;
630
631 if ( AudioTestBeaconGetSize(&Beacon)
632 && !AudioTestBeaconIsComplete(&Beacon))
633 {
634 bool const fStarted = AudioTestBeaconGetRemaining(&Beacon) == AudioTestBeaconGetSize(&Beacon);
635
636 uint32_t const cbBeaconRemaining = AudioTestBeaconGetRemaining(&Beacon);
637 AssertBreakStmt(cbBeaconRemaining, rc = VERR_WRONG_ORDER);
638
639 /* Limit to exactly one beacon (pre or post). */
640 uint32_t const cbToWrite = RT_MIN(sizeof(abBuf), RT_MIN(cbCanWrite, cbBeaconRemaining));
641
642 rc = AudioTestBeaconWrite(&Beacon, abBuf, cbToWrite);
643 if (RT_SUCCESS(rc))
644 {
645 rc = AudioTestMixStreamPlay(&pStream->Mix, abBuf, cbToWrite, &cbWritten);
646 if ( RT_SUCCESS(rc)
647 && pTstEnv)
648 {
649 /* Also write the beacon data to the test object.
650 * Note: We use cbPlayed here instead of cbToPlay to know if the data actually was
651 * reported as being played by the audio stack. */
652 rc = AudioTestObjWrite(Obj, abBuf, cbWritten);
653 }
654 }
655
656 if ( fStarted
657 && g_uVerbosity >= 2)
658 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Writing %s beacon begin\n",
659 idxTest, AudioTestBeaconTypeGetName(Beacon.enmType));
660 if (AudioTestBeaconIsComplete(&Beacon))
661 {
662 if (g_uVerbosity >= 2)
663 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Writing %s beacon end\n",
664 idxTest, AudioTestBeaconTypeGetName(Beacon.enmType));
665 fGoToNextStage = true;
666 }
667 }
668 else
669 fGoToNextStage = true;
670
671 if (fGoToNextStage)
672 {
673 if (enmState == AUDIOTESTSTATE_PRE)
674 enmState = AUDIOTESTSTATE_RUN;
675 else if (enmState == AUDIOTESTSTATE_POST)
676 enmState = AUDIOTESTSTATE_DONE;
677 }
678 break;
679 }
680
681 case AUDIOTESTSTATE_RUN:
682 {
683 uint32_t cbToWrite = RT_MIN(sizeof(abBuf), cbCanWrite);
684 cbToWrite = RT_MIN(cbToWrite, cbToWriteTotal - cbWrittenTotal);
685
686 if (g_uVerbosity >= 4)
687 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS,
688 "Test #%RU32: Playing back %RU32 bytes\n", idxTest, cbToWrite);
689
690 if (cbToWrite)
691 {
692 rc = AudioTestToneGenerate(&TstTone, abBuf, cbToWrite, &cbToWrite);
693 if (RT_SUCCESS(rc))
694 {
695 if (pTstEnv)
696 {
697 /* Write stuff to disk before trying to play it. Helps analysis later. */
698 rc = AudioTestObjWrite(Obj, abBuf, cbToWrite);
699 }
700
701 if (RT_SUCCESS(rc))
702 {
703 rc = AudioTestMixStreamPlay(&pStream->Mix, abBuf, cbToWrite, &cbWritten);
704 if (RT_SUCCESS(rc))
705 {
706 AssertBreakStmt(cbWritten <= cbToWrite, rc = VERR_TOO_MUCH_DATA);
707
708 offStream += cbWritten;
709
710 if (cbWritten != cbToWrite)
711 RTTestFailed(g_hTest, "Test #%RU32: Only played %RU32/%RU32 bytes\n",
712 idxTest, cbWritten, cbToWrite);
713
714 if (cbWritten)
715 nsLastWrite = nsNow;
716
717 if (g_uVerbosity >= 4)
718 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS,
719 "Test #%RU32: Played back %RU32 bytes\n", idxTest, cbWritten);
720
721 cbWrittenTotal += cbWritten;
722 }
723 }
724 }
725 }
726
727 if (RT_SUCCESS(rc))
728 {
729 const bool fComplete = cbWrittenTotal >= cbToWriteTotal;
730 if (fComplete)
731 {
732 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Playing back audio data ended\n", idxTest);
733
734 enmState = AUDIOTESTSTATE_POST;
735
736 /* Re-use the beacon object, but this time it's the post beacon. */
737 AudioTestBeaconInit(&Beacon, (uint8_t)idxTest, AUDIOTESTTONEBEACONTYPE_PLAY_POST,
738 &pStream->Cfg.Props);
739 }
740 }
741 else
742 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Playing back failed with %Rrc\n", idxTest, rc);
743 break;
744 }
745
746 case AUDIOTESTSTATE_DONE:
747 {
748 /* Handled below. */
749 break;
750 }
751
752 default:
753 AssertFailed();
754 break;
755 }
756
757 if (RT_FAILURE(rc))
758 break;
759
760 if (enmState == AUDIOTESTSTATE_DONE)
761 break;
762
763 nsLastMsgCantWrite = 0;
764 }
765 else if (AudioTestMixStreamIsOkay(&pStream->Mix))
766 {
767 RTMSINTERVAL const msSleep = RT_MIN(RT_MAX(1, pStream->Cfg.Device.cMsSchedulingHint), 256);
768
769 if ( g_uVerbosity >= 3
770 && ( !nsLastMsgCantWrite
771 || (nsNow - nsLastMsgCantWrite) > RT_NS_10SEC)) /* Don't spam the output too much. */
772 {
773 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Waiting %RU32ms for stream to be writable again (last write %RU64ns ago) ...\n",
774 idxTest, msSleep, nsNow - nsLastWrite);
775 nsLastMsgCantWrite = nsNow;
776 }
777
778 RTThreadSleep(msSleep);
779 }
780 else
781 AssertFailedBreakStmt(rc = VERR_AUDIO_STREAM_NOT_READY);
782
783 /* Fail-safe in case something screwed up while playing back. */
784 uint64_t const cNsElapsed = nsNow - nsStarted;
785 if (cNsElapsed > nsTimeout)
786 {
787 RTTestFailed(g_hTest, "Test #%RU32: Playback took too long (running %RU64 vs. timeout %RU64), aborting\n",
788 idxTest, cNsElapsed, nsTimeout);
789 rc = VERR_TIMEOUT;
790 }
791
792 if (RT_FAILURE(rc))
793 break;
794 } /* for */
795
796 if (cbWrittenTotal != cbToWriteTotal)
797 {
798 RTTestFailed(g_hTest, "Test #%RU32: Playback ended unexpectedly (%RU32 played, expected %RU32)\n",
799 idxTest, cbWrittenTotal, cbToWriteTotal);
800 rc = cbWrittenTotal > cbToWriteTotal ? VERR_BUFFER_OVERFLOW : VERR_BUFFER_UNDERFLOW;
801 }
802
803 if (RT_SUCCESS(rc))
804 {
805 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Draining stream ...\n", idxTest);
806 rc = AudioTestMixStreamDrain(&pStream->Mix, true /*fSync*/);
807 }
808 }
809 else
810 rc = VERR_AUDIO_STREAM_NOT_READY;
811
812 if (pTstEnv)
813 {
814 rc2 = AudioTestObjClose(Obj);
815 if (RT_SUCCESS(rc))
816 rc = rc2;
817 }
818
819 if (RT_FAILURE(rc))
820 RTTestFailed(g_hTest, "Test #%RU32: Playing tone failed with %Rrc\n", idxTest, rc);
821
822 return rc;
823}
824
825/**
826 * Records a test tone from a specific audio test stream.
827 *
828 * @returns VBox status code.
829 * @param pIoOpts I/O options to use.
830 * @param pTstEnv Test environment to use for running the test.
831 * @param pStream Stream to use for recording the tone.
832 * @param pParms Tone parameters to use.
833 *
834 * @note Blocking function.
835 */
836static int audioTestRecordTone(PAUDIOTESTIOOPTS pIoOpts, PAUDIOTESTENV pTstEnv, PAUDIOTESTSTREAM pStream, PAUDIOTESTTONEPARMS pParms)
837{
838 uint32_t const idxTest = (uint8_t)pParms->Hdr.idxTest;
839
840 const char *pcszPathOut = pTstEnv->Set.szPathAbs;
841
842 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Recording test tone (tone frequency is %RU16Hz, %RU32ms)\n",
843 idxTest, (uint16_t)pParms->dbFreqHz, pParms->msDuration);
844 RTTestPrintf(g_hTest, RTTESTLVL_DEBUG, "Test #%RU32: Writing to '%s'\n", idxTest, pcszPathOut);
845
846 /** @todo Use .WAV here? */
847 AUDIOTESTOBJ Obj;
848 int rc = AudioTestSetObjCreateAndRegister(&pTstEnv->Set, "guest-tone-rec.pcm", &Obj);
849 AssertRCReturn(rc, rc);
850
851 PAUDIOTESTDRVMIXSTREAM pMix = &pStream->Mix;
852
853 rc = AudioTestMixStreamEnable(pMix);
854 if (RT_SUCCESS(rc))
855 {
856 size_t cbToReadTotal = PDMAudioPropsMilliToBytes(&pStream->Cfg.Props, pParms->msDuration);
857 AssertStmt(cbToReadTotal, rc = VERR_INVALID_PARAMETER);
858 size_t cbReadTotal = 0; /* Counts the read test tone data (w/o any beacons). */
859
860 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Recording %RU32 bytes total (%RU32ms timeout)\n",
861 idxTest, cbToReadTotal, pTstEnv->msTimeout);
862
863 /* Failsafe if invalid timeout is set. */
864 if ( pTstEnv->msTimeout == 0
865 || pTstEnv->msTimeout == UINT32_MAX)
866 {
867 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Warning! Invalid timeout set (%RU32ms), setting default\n",
868 idxTest, pTstEnv->msTimeout);
869 pTstEnv->msTimeout = AUDIOTEST_TIMEOUT_DEFAULT_MS;
870 }
871
872 /* We expect a pre + post beacon before + after the actual test tone.
873 * We always start with the pre beacon. */
874 AUDIOTESTTONEBEACON Beacon;
875 AudioTestBeaconInit(&Beacon, (uint8_t)pParms->Hdr.idxTest, AUDIOTESTTONEBEACONTYPE_PLAY_PRE, &pStream->Cfg.Props);
876
877 uint32_t const cbBeacon = AudioTestBeaconGetSize(&Beacon);
878 if (cbBeacon)
879 {
880 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Expecting 2 x %RU32 bytes pre/post beacons\n",
881 idxTest, cbBeacon);
882 if (g_uVerbosity >= 2)
883 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Waiting for %s beacon ...\n",
884 idxTest, AudioTestBeaconTypeGetName(Beacon.enmType));
885 }
886
887 AudioTestObjAddMetadataStr(Obj, "test_id=%04RU32\n", pParms->Hdr.idxTest);
888 AudioTestObjAddMetadataStr(Obj, "beacon_type=%RU32\n", (uint32_t)AudioTestBeaconGetType(&Beacon));
889 AudioTestObjAddMetadataStr(Obj, "beacon_pre_bytes=%RU32\n", cbBeacon);
890 AudioTestObjAddMetadataStr(Obj, "beacon_post_bytes=%RU32\n", cbBeacon);
891 AudioTestObjAddMetadataStr(Obj, "stream_to_record_bytes=%RU32\n", cbToReadTotal);
892 AudioTestObjAddMetadataStr(Obj, "stream_buffer_size_ms=%RU32\n", pIoOpts->cMsBufferSize);
893 AudioTestObjAddMetadataStr(Obj, "stream_prebuf_size_ms=%RU32\n", pIoOpts->cMsPreBuffer);
894 /* Note: This mostly is provided by backend (e.g. PulseAudio / ALSA / ++) and
895 * has nothing to do with the device emulation scheduling hint. */
896 AudioTestObjAddMetadataStr(Obj, "device_scheduling_hint_ms=%RU32\n", pIoOpts->cMsSchedulingHint);
897
898 PRTCIRCBUF pCircBuf;
899 rc = RTCircBufCreate(&pCircBuf, _64K);
900 AssertRCReturn(rc, rc);
901
902 uint64_t const nsStarted = RTTimeNanoTS();
903
904 uint64_t nsTimeout = uint64_t(pTstEnv->msTimeout) * RT_NS_1MS_64;
905 uint64_t nsLastMsgCantRead = 0; /* Timestamp (in ns) when the last message of an unreadable stream was shown. */
906
907 AUDIOTESTSTATE enmState = AUDIOTESTSTATE_PRE;
908
909 while (!g_fTerminate)
910 {
911 uint64_t const nsNow = RTTimeNanoTS();
912
913 void *pvBlock;
914 size_t cbBlock;
915
916 /*
917 * Anything we can capture from the stream?
918 */
919 uint32_t const cbCanRead = AudioTestMixStreamGetReadable(pMix);
920 if (cbCanRead)
921 {
922 RTCircBufAcquireWriteBlock(pCircBuf, cbCanRead, &pvBlock, &cbBlock);
923
924 uint32_t cbCaptured = 0;
925 if (cbBlock)
926 {
927 rc = AudioTestMixStreamCapture(pMix, pvBlock, (uint32_t)cbBlock, &cbCaptured);
928 if (RT_FAILURE(rc))
929 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Reading from stream failed with %Rrc\n", idxTest, rc);
930
931 if (g_uVerbosity >= 2)
932 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Stream is readable with %RU64ms (%RU32 bytes), captured %RU64ms (%RU32 bytes)\n",
933 idxTest,
934 PDMAudioPropsBytesToMilli(pMix->pProps, cbCanRead), cbCanRead,
935 PDMAudioPropsBytesToMilli(pMix->pProps, cbCaptured), cbCaptured);
936
937 if (RT_FAILURE(rc))
938 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Capturing failed with %Rrc\n",
939 idxTest, rc);
940 }
941
942 RTCircBufReleaseWriteBlock(pCircBuf, cbCaptured);
943 }
944 else if (AudioTestMixStreamIsOkay(pMix))
945 {
946 RTMSINTERVAL const msSleep = RT_MIN(RT_MAX(1, pStream->Cfg.Device.cMsSchedulingHint), 256);
947
948 if ( g_uVerbosity >= 3
949 && ( !nsLastMsgCantRead
950 || (nsNow - nsLastMsgCantRead) > RT_NS_10SEC)) /* Don't spam the output too much. */
951 {
952 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Waiting %RU32ms for stream to be readable again ...\n",
953 idxTest, msSleep);
954 nsLastMsgCantRead = nsNow;
955 }
956
957 RTThreadSleep(msSleep);
958 }
959
960 /*
961 * Process our buffer.
962 */
963 size_t cbBlockToAcq;
964 if (pTstEnv->fSelftest) /* For self-test mode we want to have a bit more randomness. */
965 {
966 size_t const u = (uint32_t)RTCircBufUsed(pCircBuf);
967 size_t const r = RTRandU32Ex(1, (uint32_t)RTCircBufSize(pCircBuf));
968 cbBlockToAcq = PDMAudioPropsFloorBytesToFrame(pMix->pProps, RT_MIN((uint32_t)u, (uint32_t)r));
969 }
970 else
971 cbBlockToAcq = PDMAudioPropsFloorBytesToFrame(pMix->pProps, (uint32_t)RTCircBufUsed(pCircBuf));
972
973 RTCircBufAcquireReadBlock(pCircBuf, cbBlockToAcq, &pvBlock, &cbBlock);
974 if (!cbBlock)
975 continue;
976
977 /* Flag indicating whether the whole block we've captured is silence or not. */
978 bool const fIsAllSilence = PDMAudioPropsIsBufferSilence(&pStream->pStream->Cfg.Props, pvBlock, cbBlock);
979 size_t cbRead = 0;
980
981 switch (enmState)
982 {
983 case AUDIOTESTSTATE_PRE:
984 RT_FALL_THROUGH();
985 case AUDIOTESTSTATE_POST:
986 {
987 bool fGoToNextStage = false;
988
989 if ( AudioTestBeaconGetSize(&Beacon)
990 && !AudioTestBeaconIsComplete(&Beacon))
991 {
992 bool const fStarted = AudioTestBeaconGetRemaining(&Beacon) == AudioTestBeaconGetSize(&Beacon);
993
994 size_t uOff;
995 int rc2 = AudioTestBeaconAddConsecutive(&Beacon, (uint8_t *)pvBlock, cbBlock, &uOff);
996 if ( RT_SUCCESS(rc2)
997 && uOff)
998 cbRead = uOff;
999
1000 if ( fStarted
1001 && g_uVerbosity >= 2)
1002 {
1003 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS,
1004 "Test #%RU32: Detection of %s beacon started (%RU64ms recorded so far)\n",
1005 idxTest, AudioTestBeaconTypeGetName(Beacon.enmType),
1006 PDMAudioPropsBytesToMilli(&pStream->pStream->Cfg.Props, (uint32_t)cbReadTotal));
1007 }
1008
1009 if (AudioTestBeaconIsComplete(&Beacon))
1010 {
1011 if (g_uVerbosity >= 2)
1012 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Detection of %s beacon complete\n",
1013 idxTest, AudioTestBeaconTypeGetName(Beacon.enmType));
1014 fGoToNextStage = true;
1015 }
1016 }
1017 else
1018 fGoToNextStage = true;
1019
1020 if (fGoToNextStage)
1021 {
1022 if (enmState == AUDIOTESTSTATE_PRE)
1023 enmState = AUDIOTESTSTATE_RUN;
1024 else if (enmState == AUDIOTESTSTATE_POST)
1025 enmState = AUDIOTESTSTATE_DONE;
1026 }
1027 break;
1028 }
1029
1030 case AUDIOTESTSTATE_RUN:
1031 {
1032 /* Whether we count all silence as recorded data or not.
1033 * Currently we don't, as otherwise consequtively played tones will be cut off in the end. */
1034 bool const fRecord = !fIsAllSilence;
1035 if (fRecord)
1036 {
1037 /* Don't read more than we're told to.
1038 * After the actual test tone data there might come a post beacon which also
1039 * needs to be handled in the AUDIOTESTSTATE_POST state then. */
1040 if (cbReadTotal + cbBlock > cbToReadTotal)
1041 {
1042 AssertBreakStmt(cbToReadTotal >= cbReadTotal, rc = VERR_INTERNAL_ERROR);
1043 cbRead = cbToReadTotal - cbReadTotal;
1044 }
1045 else
1046 cbRead = cbBlock;
1047
1048 cbReadTotal += cbRead;
1049 AssertBreakStmt(cbReadTotal <= cbToReadTotal, rc = VERR_INTERNAL_ERROR);
1050 }
1051
1052 /* Done recording the test tone? */
1053 if (cbReadTotal + cbRead == cbToReadTotal)
1054 {
1055 enmState = AUDIOTESTSTATE_POST;
1056
1057 if (g_uVerbosity >= 2)
1058 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Recording tone data done\n", idxTest);
1059
1060 if (AudioTestBeaconGetSize(&Beacon))
1061 {
1062 /* Re-use the beacon object, but this time it's the post beacon. */
1063 AudioTestBeaconInit(&Beacon, (uint8_t)pParms->Hdr.idxTest, AUDIOTESTTONEBEACONTYPE_PLAY_POST,
1064 &pStream->Cfg.Props);
1065 if (g_uVerbosity >= 2)
1066 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS,
1067 "Test #%RU32: Waiting for %s beacon ...\n",
1068 idxTest, AudioTestBeaconTypeGetName(Beacon.enmType));
1069 }
1070 }
1071 break;
1072 }
1073
1074 case AUDIOTESTSTATE_DONE:
1075 {
1076 /* Nothing to do here. */
1077 break;
1078 }
1079
1080 default:
1081 AssertFailed();
1082 break;
1083 }
1084
1085 if (cbRead)
1086 {
1087 if (g_uVerbosity >= 3)
1088 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Read data (%zu bytes):\n"
1089 "%.*Rhxd\n",
1090 idxTest, cbRead, cbRead, pvBlock);
1091
1092 /* Always write (record) everything, no matter if the current audio contains complete silence or not.
1093 * Might be also become handy later if we want to have a look at start/stop timings and so on. */
1094 rc = AudioTestObjWrite(Obj, pvBlock, cbRead);
1095 AssertRCBreak(rc);
1096 }
1097
1098 if (g_uVerbosity >= 2)
1099 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Processed %RU64ms (%zu bytes)\n",
1100 idxTest, PDMAudioPropsBytesToMilli(pMix->pProps, (uint32_t)cbRead), cbRead);
1101
1102 RTCircBufReleaseReadBlock(pCircBuf, cbRead);
1103
1104 if (enmState == AUDIOTESTSTATE_DONE) /* Bail out when in state "done". */
1105 break;
1106
1107 /* Fail-safe in case something screwed up while playing back. */
1108 uint64_t const cNsElapsed = nsNow - nsStarted;
1109 if (cNsElapsed > nsTimeout)
1110 {
1111 RTTestFailed(g_hTest, "Test #%RU32: Recording took too long (running %RU64 vs. timeout %RU64), aborting\n",
1112 idxTest, cNsElapsed, nsTimeout);
1113 rc = VERR_TIMEOUT;
1114 }
1115
1116 if (RT_FAILURE(rc))
1117 break;
1118 } /* while */
1119
1120 if (g_uVerbosity >= 2)
1121 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test #%RU32: Recorded %zu bytes total\n", idxTest, cbReadTotal);
1122 if (cbReadTotal != cbToReadTotal)
1123 {
1124 RTTestFailed(g_hTest, "Test #%RU32: Recording ended unexpectedly (%zu read, expected %zu)\n",
1125 idxTest, cbReadTotal, cbToReadTotal);
1126 int rc2 = cbReadTotal > cbToReadTotal ? VERR_BUFFER_OVERFLOW : VERR_BUFFER_UNDERFLOW;
1127 if (RT_SUCCESS(rc))
1128 rc = rc2;
1129 }
1130
1131 if (RT_FAILURE(rc))
1132 RTTestFailed(g_hTest, "Test #%RU32: Recording failed (state is '%s')\n", idxTest, AudioTestStateToStr(enmState));
1133
1134 int rc2 = AudioTestMixStreamDisable(pMix);
1135 if (RT_SUCCESS(rc))
1136 rc = rc2;
1137
1138 RTCircBufDestroy(pCircBuf);
1139 }
1140
1141 int rc2 = AudioTestObjClose(Obj);
1142 if (RT_SUCCESS(rc))
1143 rc = rc2;
1144
1145 if (RT_FAILURE(rc))
1146 RTTestFailed(g_hTest, "Test #%RU32: Recording tone done failed with %Rrc\n", idxTest, rc);
1147
1148 return rc;
1149}
1150
1151
1152/*********************************************************************************************************************************
1153* ATS Callback Implementations *
1154*********************************************************************************************************************************/
1155
1156/** @copydoc ATSCALLBACKS::pfnHowdy
1157 *
1158 * @note Runs as part of the guest ATS.
1159 */
1160static DECLCALLBACK(int) audioTestGstAtsHowdyCallback(void const *pvUser)
1161{
1162 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1163
1164 AssertReturn(pCtx->cClients <= UINT8_MAX - 1, VERR_BUFFER_OVERFLOW);
1165
1166 pCtx->cClients++;
1167
1168 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "New client connected, now %RU8 total\n", pCtx->cClients);
1169
1170 return VINF_SUCCESS;
1171}
1172
1173/** @copydoc ATSCALLBACKS::pfnBye
1174 *
1175 * @note Runs as part of the guest ATS.
1176 */
1177static DECLCALLBACK(int) audioTestGstAtsByeCallback(void const *pvUser)
1178{
1179 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1180
1181 AssertReturn(pCtx->cClients, VERR_WRONG_ORDER);
1182 pCtx->cClients--;
1183
1184 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Client wants to disconnect, %RU8 remaining\n", pCtx->cClients);
1185
1186 if (0 == pCtx->cClients) /* All clients disconnected? Tear things down. */
1187 {
1188 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Last client disconnected, terminating server ...\n");
1189 ASMAtomicWriteBool(&g_fTerminate, true);
1190 }
1191
1192 return VINF_SUCCESS;
1193}
1194
1195/** @copydoc ATSCALLBACKS::pfnTestSetBegin
1196 *
1197 * @note Runs as part of the guest ATS.
1198 */
1199static DECLCALLBACK(int) audioTestGstAtsTestSetBeginCallback(void const *pvUser, const char *pszTag)
1200{
1201 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1202 PAUDIOTESTENV pTstEnv = pCtx->pTstEnv;
1203
1204 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Got request for beginning test set '%s' in '%s'\n", pszTag, pTstEnv->szPathTemp);
1205
1206 return AudioTestSetCreate(&pTstEnv->Set, pTstEnv->szPathTemp, pszTag);
1207}
1208
1209/** @copydoc ATSCALLBACKS::pfnTestSetEnd
1210 *
1211 * @note Runs as part of the guest ATS.
1212 */
1213static DECLCALLBACK(int) audioTestGstAtsTestSetEndCallback(void const *pvUser, const char *pszTag)
1214{
1215 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1216 PAUDIOTESTENV pTstEnv = pCtx->pTstEnv;
1217
1218 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Got request for ending test set '%s'\n", pszTag);
1219
1220 /* Pack up everything to be ready for transmission. */
1221 return audioTestEnvPrologue(pTstEnv, true /* fPack */, pCtx->szTestSetArchive, sizeof(pCtx->szTestSetArchive));
1222}
1223
1224/** @copydoc ATSCALLBACKS::pfnTonePlay
1225 *
1226 * @note Runs as part of the guest ATS.
1227 */
1228static DECLCALLBACK(int) audioTestGstAtsTonePlayCallback(void const *pvUser, PAUDIOTESTTONEPARMS pToneParms)
1229{
1230 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1231 PAUDIOTESTENV pTstEnv = pCtx->pTstEnv;
1232 PAUDIOTESTIOOPTS pIoOpts = &pTstEnv->IoOpts;
1233
1234 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Got request for playing test tone #%RU32 (%RU16Hz, %RU32ms) ...\n",
1235 pToneParms->Hdr.idxTest, (uint16_t)pToneParms->dbFreqHz, pToneParms->msDuration);
1236
1237 char szTimeCreated[RTTIME_STR_LEN];
1238 RTTimeToString(&pToneParms->Hdr.tsCreated, szTimeCreated, sizeof(szTimeCreated));
1239 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test created (caller UTC): %s\n", szTimeCreated);
1240
1241 const PAUDIOTESTSTREAM pTstStream = &pTstEnv->aStreams[0]; /** @todo Make this dynamic. */
1242
1243 int rc = audioTestStreamInit(pTstEnv->pDrvStack, pTstStream, PDMAUDIODIR_OUT, pIoOpts);
1244 if (RT_SUCCESS(rc))
1245 {
1246 AUDIOTESTPARMS TstParms;
1247 RT_ZERO(TstParms);
1248 TstParms.enmType = AUDIOTESTTYPE_TESTTONE_PLAY;
1249 TstParms.enmDir = PDMAUDIODIR_OUT;
1250 TstParms.TestTone = *pToneParms;
1251
1252 PAUDIOTESTENTRY pTst;
1253 rc = AudioTestSetTestBegin(&pTstEnv->Set, "Playing test tone", &TstParms, &pTst);
1254 if (RT_SUCCESS(rc))
1255 {
1256 rc = audioTestPlayTone(&pTstEnv->IoOpts, pTstEnv, pTstStream, pToneParms);
1257 if (RT_SUCCESS(rc))
1258 {
1259 AudioTestSetTestDone(pTst);
1260 }
1261 else
1262 AudioTestSetTestFailed(pTst, rc, "Playing tone failed");
1263 }
1264
1265 int rc2 = audioTestStreamDestroy(pTstEnv->pDrvStack, pTstStream);
1266 if (RT_SUCCESS(rc))
1267 rc = rc2;
1268 }
1269 else
1270 RTTestFailed(g_hTest, "Error creating output stream, rc=%Rrc\n", rc);
1271
1272 return rc;
1273}
1274
1275/** @copydoc ATSCALLBACKS::pfnToneRecord */
1276static DECLCALLBACK(int) audioTestGstAtsToneRecordCallback(void const *pvUser, PAUDIOTESTTONEPARMS pToneParms)
1277{
1278 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1279 PAUDIOTESTENV pTstEnv = pCtx->pTstEnv;
1280 PAUDIOTESTIOOPTS pIoOpts = &pTstEnv->IoOpts;
1281
1282 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Got request for recording test tone #%RU32 (%RU32ms) ...\n",
1283 pToneParms->Hdr.idxTest, pToneParms->msDuration);
1284
1285 char szTimeCreated[RTTIME_STR_LEN];
1286 RTTimeToString(&pToneParms->Hdr.tsCreated, szTimeCreated, sizeof(szTimeCreated));
1287 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test created (caller UTC): %s\n", szTimeCreated);
1288
1289 const PAUDIOTESTSTREAM pTstStream = &pTstEnv->aStreams[0]; /** @todo Make this dynamic. */
1290
1291 int rc = audioTestStreamInit(pTstEnv->pDrvStack, pTstStream, PDMAUDIODIR_IN, pIoOpts);
1292 if (RT_SUCCESS(rc))
1293 {
1294 AUDIOTESTPARMS TstParms;
1295 RT_ZERO(TstParms);
1296 TstParms.enmType = AUDIOTESTTYPE_TESTTONE_RECORD;
1297 TstParms.enmDir = PDMAUDIODIR_IN;
1298 TstParms.TestTone = *pToneParms;
1299
1300 PAUDIOTESTENTRY pTst;
1301 rc = AudioTestSetTestBegin(&pTstEnv->Set, "Recording test tone from host", &TstParms, &pTst);
1302 if (RT_SUCCESS(rc))
1303 {
1304 rc = audioTestRecordTone(pIoOpts, pTstEnv, pTstStream, pToneParms);
1305 if (RT_SUCCESS(rc))
1306 {
1307 AudioTestSetTestDone(pTst);
1308 }
1309 else
1310 AudioTestSetTestFailed(pTst, rc, "Recording tone failed");
1311 }
1312
1313 int rc2 = audioTestStreamDestroy(pTstEnv->pDrvStack, pTstStream);
1314 if (RT_SUCCESS(rc))
1315 rc = rc2;
1316 }
1317 else
1318 RTTestFailed(g_hTest, "Error creating input stream, rc=%Rrc\n", rc);
1319
1320 return rc;
1321}
1322
1323/** @copydoc ATSCALLBACKS::pfnTestSetSendBegin */
1324static DECLCALLBACK(int) audioTestGstAtsTestSetSendBeginCallback(void const *pvUser, const char *pszTag)
1325{
1326 RT_NOREF(pszTag);
1327
1328 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1329
1330 if (!RTFileExists(pCtx->szTestSetArchive)) /* Has the archive successfully been created yet? */
1331 return VERR_WRONG_ORDER;
1332
1333 int rc = RTFileOpen(&pCtx->hTestSetArchive, pCtx->szTestSetArchive, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1334 if (RT_SUCCESS(rc))
1335 {
1336 uint64_t uSize;
1337 rc = RTFileQuerySize(pCtx->hTestSetArchive, &uSize);
1338 if (RT_SUCCESS(rc))
1339 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Sending test set '%s' (%zu bytes)\n", pCtx->szTestSetArchive, uSize);
1340 }
1341
1342 return rc;
1343}
1344
1345/** @copydoc ATSCALLBACKS::pfnTestSetSendRead */
1346static DECLCALLBACK(int) audioTestGstAtsTestSetSendReadCallback(void const *pvUser,
1347 const char *pszTag, void *pvBuf, size_t cbBuf, size_t *pcbRead)
1348{
1349 RT_NOREF(pszTag);
1350
1351 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1352
1353 return RTFileRead(pCtx->hTestSetArchive, pvBuf, cbBuf, pcbRead);
1354}
1355
1356/** @copydoc ATSCALLBACKS::pfnTestSetSendEnd */
1357static DECLCALLBACK(int) audioTestGstAtsTestSetSendEndCallback(void const *pvUser, const char *pszTag)
1358{
1359 RT_NOREF(pszTag);
1360
1361 PATSCALLBACKCTX pCtx = (PATSCALLBACKCTX)pvUser;
1362
1363 int rc = RTFileClose(pCtx->hTestSetArchive);
1364 if (RT_SUCCESS(rc))
1365 {
1366 pCtx->hTestSetArchive = NIL_RTFILE;
1367 }
1368
1369 return rc;
1370}
1371
1372
1373/*********************************************************************************************************************************
1374* Implementation of audio test environment handling *
1375*********************************************************************************************************************************/
1376
1377/**
1378 * Connects an ATS client via TCP/IP to a peer.
1379 *
1380 * @returns VBox status code.
1381 * @param pTstEnv Test environment to use.
1382 * @param pClient Client to connect.
1383 * @param pszWhat Hint of what to connect to where.
1384 * @param pTcpOpts Pointer to TCP options to use.
1385 */
1386static int audioTestEnvConnectViaTcp(PAUDIOTESTENV pTstEnv, PATSCLIENT pClient, const char *pszWhat, PAUDIOTESTENVTCPOPTS pTcpOpts)
1387{
1388 RT_NOREF(pTstEnv);
1389
1390 RTGETOPTUNION Val;
1391 RT_ZERO(Val);
1392
1393 Val.u32 = pTcpOpts->enmConnMode;
1394 int rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_CONN_MODE, &Val);
1395 AssertRCReturn(rc, rc);
1396
1397 if ( pTcpOpts->enmConnMode == ATSCONNMODE_BOTH
1398 || pTcpOpts->enmConnMode == ATSCONNMODE_SERVER)
1399 {
1400 Assert(pTcpOpts->uBindPort); /* Always set by the caller. */
1401 Val.u16 = pTcpOpts->uBindPort;
1402 rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_BIND_PORT, &Val);
1403 AssertRCReturn(rc, rc);
1404
1405 if (pTcpOpts->szBindAddr[0])
1406 {
1407 Val.psz = pTcpOpts->szBindAddr;
1408 rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_BIND_ADDRESS, &Val);
1409 AssertRCReturn(rc, rc);
1410 }
1411 else
1412 {
1413 RTTestFailed(g_hTest, "No bind address specified!\n");
1414 return VERR_INVALID_PARAMETER;
1415 }
1416
1417 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Connecting %s by listening as server at %s:%RU32 ...\n",
1418 pszWhat, pTcpOpts->szBindAddr, pTcpOpts->uBindPort);
1419 }
1420
1421
1422 if ( pTcpOpts->enmConnMode == ATSCONNMODE_BOTH
1423 || pTcpOpts->enmConnMode == ATSCONNMODE_CLIENT)
1424 {
1425 Assert(pTcpOpts->uConnectPort); /* Always set by the caller. */
1426 Val.u16 = pTcpOpts->uConnectPort;
1427 rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_CONNECT_PORT, &Val);
1428 AssertRCReturn(rc, rc);
1429
1430 if (pTcpOpts->szConnectAddr[0])
1431 {
1432 Val.psz = pTcpOpts->szConnectAddr;
1433 rc = AudioTestSvcClientHandleOption(pClient, ATSTCPOPT_CONNECT_ADDRESS, &Val);
1434 AssertRCReturn(rc, rc);
1435 }
1436 else
1437 {
1438 RTTestFailed(g_hTest, "No connect address specified!\n");
1439 return VERR_INVALID_PARAMETER;
1440 }
1441
1442 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Connecting %s by connecting as client to %s:%RU32 ...\n",
1443 pszWhat, pTcpOpts->szConnectAddr, pTcpOpts->uConnectPort);
1444 }
1445
1446 rc = AudioTestSvcClientConnect(pClient);
1447 if (RT_FAILURE(rc))
1448 {
1449 RTTestFailed(g_hTest, "Connecting %s failed with %Rrc\n", pszWhat, rc);
1450 return rc;
1451 }
1452
1453 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Successfully connected %s\n", pszWhat);
1454 return rc;
1455}
1456
1457/**
1458 * Configures and starts an ATS TCP/IP server.
1459 *
1460 * @returns VBox status code.
1461 * @param pSrv ATS server instance to configure and start.
1462 * @param pCallbacks ATS callback table to use.
1463 * @param pszDesc Hint of server type which is being started.
1464 * @param pTcpOpts TCP options to use.
1465 */
1466static int audioTestEnvConfigureAndStartTcpServer(PATSSERVER pSrv, PCATSCALLBACKS pCallbacks, const char *pszDesc,
1467 PAUDIOTESTENVTCPOPTS pTcpOpts)
1468{
1469 RTGETOPTUNION Val;
1470 RT_ZERO(Val);
1471
1472 int rc = AudioTestSvcInit(pSrv, pCallbacks);
1473 if (RT_FAILURE(rc))
1474 return rc;
1475
1476 Val.u32 = pTcpOpts->enmConnMode;
1477 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_CONN_MODE, &Val);
1478 AssertRCReturn(rc, rc);
1479
1480 if ( pTcpOpts->enmConnMode == ATSCONNMODE_BOTH
1481 || pTcpOpts->enmConnMode == ATSCONNMODE_SERVER)
1482 {
1483 Assert(pTcpOpts->uBindPort); /* Always set by the caller. */
1484 Val.u16 = pTcpOpts->uBindPort;
1485 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_BIND_PORT, &Val);
1486 AssertRCReturn(rc, rc);
1487
1488 if (pTcpOpts->szBindAddr[0])
1489 {
1490 Val.psz = pTcpOpts->szBindAddr;
1491 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_BIND_ADDRESS, &Val);
1492 AssertRCReturn(rc, rc);
1493 }
1494 else
1495 {
1496 RTTestFailed(g_hTest, "No bind address specified!\n");
1497 return VERR_INVALID_PARAMETER;
1498 }
1499
1500 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Starting server for %s at %s:%RU32 ...\n",
1501 pszDesc, pTcpOpts->szBindAddr, pTcpOpts->uBindPort);
1502 }
1503
1504
1505 if ( pTcpOpts->enmConnMode == ATSCONNMODE_BOTH
1506 || pTcpOpts->enmConnMode == ATSCONNMODE_CLIENT)
1507 {
1508 Assert(pTcpOpts->uConnectPort); /* Always set by the caller. */
1509 Val.u16 = pTcpOpts->uConnectPort;
1510 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_CONNECT_PORT, &Val);
1511 AssertRCReturn(rc, rc);
1512
1513 if (pTcpOpts->szConnectAddr[0])
1514 {
1515 Val.psz = pTcpOpts->szConnectAddr;
1516 rc = AudioTestSvcHandleOption(pSrv, ATSTCPOPT_CONNECT_ADDRESS, &Val);
1517 AssertRCReturn(rc, rc);
1518 }
1519 else
1520 {
1521 RTTestFailed(g_hTest, "No connect address specified!\n");
1522 return VERR_INVALID_PARAMETER;
1523 }
1524
1525 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Starting server for %s by connecting as client to %s:%RU32 ...\n",
1526 pszDesc, pTcpOpts->szConnectAddr, pTcpOpts->uConnectPort);
1527 }
1528
1529 if (RT_SUCCESS(rc))
1530 {
1531 rc = AudioTestSvcStart(pSrv);
1532 if (RT_FAILURE(rc))
1533 RTTestFailed(g_hTest, "Starting server for %s failed with %Rrc\n", pszDesc, rc);
1534 }
1535
1536 return rc;
1537}
1538
1539/**
1540 * Initializes an audio test environment.
1541 *
1542 * @param pTstEnv Audio test environment to initialize.
1543 */
1544void audioTestEnvInit(PAUDIOTESTENV pTstEnv)
1545{
1546 RT_BZERO(pTstEnv, sizeof(AUDIOTESTENV));
1547
1548 pTstEnv->msTimeout = AUDIOTEST_TIMEOUT_DEFAULT_MS;
1549
1550 audioTestIoOptsInitDefaults(&pTstEnv->IoOpts);
1551 audioTestToneParmsInit(&pTstEnv->ToneParms);
1552}
1553
1554/**
1555 * Creates an audio test environment.
1556 *
1557 * @returns VBox status code.
1558 * @param pTstEnv Audio test environment to create.
1559 * @param pDrvStack Driver stack to use.
1560 */
1561int audioTestEnvCreate(PAUDIOTESTENV pTstEnv, PAUDIOTESTDRVSTACK pDrvStack)
1562{
1563 AssertReturn(PDMAudioPropsAreValid(&pTstEnv->IoOpts.Props), VERR_WRONG_ORDER);
1564
1565 int rc = VINF_SUCCESS;
1566
1567 pTstEnv->pDrvStack = pDrvStack;
1568
1569 /*
1570 * Set sane defaults if not already set.
1571 */
1572 if (!RTStrNLen(pTstEnv->szTag, sizeof(pTstEnv->szTag)))
1573 rc = AudioTestGenTag(pTstEnv->szTag, sizeof(pTstEnv->szTag));
1574
1575 if (!RTStrNLen(pTstEnv->szPathTemp, sizeof(pTstEnv->szPathTemp)))
1576 {
1577 int rc2 = AudioTestPathGetTemp(pTstEnv->szPathTemp, sizeof(pTstEnv->szPathTemp));
1578 if (RT_SUCCESS(rc))
1579 rc = rc2;
1580 }
1581
1582 if (!RTStrNLen(pTstEnv->szPathOut, sizeof(pTstEnv->szPathOut)))
1583 {
1584 int rc2 = RTPathJoin(pTstEnv->szPathOut, sizeof(pTstEnv->szPathOut), pTstEnv->szPathTemp, "vkat-temp");
1585 if (RT_SUCCESS(rc))
1586 rc = rc2;
1587 }
1588
1589 char szPathTemp[RTPATH_MAX];
1590 if ( RT_SUCCESS(rc)
1591 && ( !strlen(pTstEnv->szPathTemp)
1592 || !strlen(pTstEnv->szPathOut)))
1593 rc = RTPathTemp(szPathTemp, sizeof(szPathTemp));
1594
1595 if ( RT_SUCCESS(rc)
1596 && !strlen(pTstEnv->szPathTemp))
1597 rc = RTPathJoin(pTstEnv->szPathTemp, sizeof(pTstEnv->szPathTemp), szPathTemp, "vkat-temp");
1598
1599 if (RT_SUCCESS(rc))
1600 {
1601 rc = RTDirCreate(pTstEnv->szPathTemp, RTFS_UNIX_IRWXU, 0 /* fFlags */);
1602 if (rc == VERR_ALREADY_EXISTS)
1603 rc = VINF_SUCCESS;
1604 }
1605
1606 if ( RT_SUCCESS(rc)
1607 && !strlen(pTstEnv->szPathOut))
1608 rc = RTPathJoin(pTstEnv->szPathOut, sizeof(pTstEnv->szPathOut), szPathTemp, "vkat");
1609
1610 if (RT_SUCCESS(rc))
1611 {
1612 rc = RTDirCreate(pTstEnv->szPathOut, RTFS_UNIX_IRWXU, 0 /* fFlags */);
1613 if (rc == VERR_ALREADY_EXISTS)
1614 rc = VINF_SUCCESS;
1615 }
1616
1617 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Initializing environment for mode '%s'\n", pTstEnv->enmMode == AUDIOTESTMODE_HOST ? "host" : "guest");
1618 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Using tag '%s'\n", pTstEnv->szTag);
1619 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Output directory is '%s'\n", pTstEnv->szPathOut);
1620 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Temp directory is '%s'\n", pTstEnv->szPathTemp);
1621
1622 if (RT_FAILURE(rc))
1623 {
1624 RTTestFailed(g_hTest, "Initializing test directories failed with %Rrc\n", rc);
1625 return rc;
1626 }
1627
1628 /**
1629 * For NAT'ed VMs we use (default):
1630 * - client mode (uConnectAddr / uConnectPort) on the guest.
1631 * - server mode (uBindAddr / uBindPort) on the host.
1632 */
1633 if ( !pTstEnv->TcpOpts.szConnectAddr[0]
1634 && !pTstEnv->TcpOpts.szBindAddr[0])
1635 RTStrCopy(pTstEnv->TcpOpts.szBindAddr, sizeof(pTstEnv->TcpOpts.szBindAddr), "0.0.0.0");
1636
1637 /*
1638 * Determine connection mode based on set variables.
1639 */
1640 if ( pTstEnv->TcpOpts.szBindAddr[0]
1641 && pTstEnv->TcpOpts.szConnectAddr[0])
1642 {
1643 pTstEnv->TcpOpts.enmConnMode = ATSCONNMODE_BOTH;
1644 }
1645 else if (pTstEnv->TcpOpts.szBindAddr[0])
1646 pTstEnv->TcpOpts.enmConnMode = ATSCONNMODE_SERVER;
1647 else /* "Reversed mode", i.e. used for NATed VMs. */
1648 pTstEnv->TcpOpts.enmConnMode = ATSCONNMODE_CLIENT;
1649
1650 /* Set a back reference to the test environment for the callback context. */
1651 pTstEnv->CallbackCtx.pTstEnv = pTstEnv;
1652
1653 ATSCALLBACKS Callbacks;
1654 RT_ZERO(Callbacks);
1655 Callbacks.pvUser = &pTstEnv->CallbackCtx;
1656
1657 if (pTstEnv->enmMode == AUDIOTESTMODE_GUEST)
1658 {
1659 Callbacks.pfnHowdy = audioTestGstAtsHowdyCallback;
1660 Callbacks.pfnBye = audioTestGstAtsByeCallback;
1661 Callbacks.pfnTestSetBegin = audioTestGstAtsTestSetBeginCallback;
1662 Callbacks.pfnTestSetEnd = audioTestGstAtsTestSetEndCallback;
1663 Callbacks.pfnTonePlay = audioTestGstAtsTonePlayCallback;
1664 Callbacks.pfnToneRecord = audioTestGstAtsToneRecordCallback;
1665 Callbacks.pfnTestSetSendBegin = audioTestGstAtsTestSetSendBeginCallback;
1666 Callbacks.pfnTestSetSendRead = audioTestGstAtsTestSetSendReadCallback;
1667 Callbacks.pfnTestSetSendEnd = audioTestGstAtsTestSetSendEndCallback;
1668
1669 if (!pTstEnv->TcpOpts.uBindPort)
1670 pTstEnv->TcpOpts.uBindPort = ATS_TCP_DEF_BIND_PORT_GUEST;
1671
1672 if (!pTstEnv->TcpOpts.uConnectPort)
1673 pTstEnv->TcpOpts.uConnectPort = ATS_TCP_DEF_CONNECT_PORT_GUEST;
1674
1675 pTstEnv->pSrv = (PATSSERVER)RTMemAlloc(sizeof(ATSSERVER));
1676 AssertPtrReturn(pTstEnv->pSrv, VERR_NO_MEMORY);
1677
1678 /*
1679 * Start the ATS (Audio Test Service) on the guest side.
1680 * That service then will perform playback and recording operations on the guest, triggered from the host.
1681 *
1682 * When running this in self-test mode, that service also can be run on the host if nothing else is specified.
1683 * Note that we have to bind to "0.0.0.0" by default so that the host can connect to it.
1684 */
1685 rc = audioTestEnvConfigureAndStartTcpServer(pTstEnv->pSrv, &Callbacks, "guest", &pTstEnv->TcpOpts);
1686 }
1687 else /* Host mode */
1688 {
1689 if (!pTstEnv->TcpOpts.uBindPort)
1690 pTstEnv->TcpOpts.uBindPort = ATS_TCP_DEF_BIND_PORT_HOST;
1691
1692 if (!pTstEnv->TcpOpts.uConnectPort)
1693 pTstEnv->TcpOpts.uConnectPort = ATS_TCP_DEF_CONNECT_PORT_HOST_PORT_FWD;
1694
1695 /**
1696 * Note: Don't set pTstEnv->TcpOpts.szTcpConnectAddr by default here, as this specifies what connection mode
1697 * (client / server / both) we use on the host.
1698 */
1699
1700 /* We need to start a server on the host so that VMs configured with NAT networking
1701 * can connect to it as well. */
1702 rc = AudioTestSvcClientCreate(&pTstEnv->u.Host.AtsClGuest);
1703 if (RT_SUCCESS(rc))
1704 rc = audioTestEnvConnectViaTcp(pTstEnv, &pTstEnv->u.Host.AtsClGuest,
1705 "host -> guest", &pTstEnv->TcpOpts);
1706 if (RT_SUCCESS(rc))
1707 {
1708 AUDIOTESTENVTCPOPTS ValKitTcpOpts;
1709 RT_ZERO(ValKitTcpOpts);
1710
1711 /* We only connect as client to the Validation Kit audio driver ATS. */
1712 ValKitTcpOpts.enmConnMode = ATSCONNMODE_CLIENT;
1713
1714 /* For now we ASSUME that the Validation Kit audio driver ATS runs on the same host as VKAT (this binary) runs on. */
1715 ValKitTcpOpts.uConnectPort = ATS_TCP_DEF_CONNECT_PORT_VALKIT; /** @todo Make this dynamic. */
1716 RTStrCopy(ValKitTcpOpts.szConnectAddr, sizeof(ValKitTcpOpts.szConnectAddr), ATS_TCP_DEF_CONNECT_HOST_ADDR_STR); /** @todo Ditto. */
1717
1718 rc = AudioTestSvcClientCreate(&pTstEnv->u.Host.AtsClValKit);
1719 if (RT_SUCCESS(rc))
1720 {
1721 rc = audioTestEnvConnectViaTcp(pTstEnv, &pTstEnv->u.Host.AtsClValKit,
1722 "host -> valkit", &ValKitTcpOpts);
1723 if (RT_FAILURE(rc))
1724 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Unable to connect to the Validation Kit audio driver!\n"
1725 "There could be multiple reasons:\n\n"
1726 " - Wrong host being used\n"
1727 " - VirtualBox host version is too old\n"
1728 " - Audio debug mode is not enabled\n"
1729 " - Support for Validation Kit audio driver is not included\n"
1730 " - Firewall / network configuration problem\n");
1731 }
1732 }
1733 }
1734
1735 return rc;
1736}
1737
1738/**
1739 * Destroys an audio test environment.
1740 *
1741 * @param pTstEnv Audio test environment to destroy.
1742 */
1743void audioTestEnvDestroy(PAUDIOTESTENV pTstEnv)
1744{
1745 if (!pTstEnv)
1746 return;
1747
1748 /* When in host mode, we need to destroy our ATS clients in order to also let
1749 * the ATS server(s) know we're going to quit. */
1750 if (pTstEnv->enmMode == AUDIOTESTMODE_HOST)
1751 {
1752 AudioTestSvcClientDestroy(&pTstEnv->u.Host.AtsClValKit);
1753 AudioTestSvcClientDestroy(&pTstEnv->u.Host.AtsClGuest);
1754 }
1755
1756 if (pTstEnv->pSrv)
1757 {
1758 int rc2 = AudioTestSvcDestroy(pTstEnv->pSrv);
1759 AssertRC(rc2);
1760
1761 RTMemFree(pTstEnv->pSrv);
1762 pTstEnv->pSrv = NULL;
1763 }
1764
1765 for (unsigned i = 0; i < RT_ELEMENTS(pTstEnv->aStreams); i++)
1766 {
1767 int rc2 = audioTestStreamDestroy(pTstEnv->pDrvStack, &pTstEnv->aStreams[i]);
1768 if (RT_FAILURE(rc2))
1769 RTTestFailed(g_hTest, "Stream destruction for stream #%u failed with %Rrc\n", i, rc2);
1770 }
1771
1772 /* Try cleaning up a bit. */
1773 RTDirRemove(pTstEnv->szPathTemp);
1774 RTDirRemove(pTstEnv->szPathOut);
1775
1776 pTstEnv->pDrvStack = NULL;
1777}
1778
1779/**
1780 * Closes, packs up and destroys a test environment.
1781 *
1782 * @returns VBox status code.
1783 * @param pTstEnv Test environment to handle.
1784 * @param fPack Whether to pack the test set up before destroying / wiping it.
1785 * @param pszPackFile Where to store the packed test set file on success. Can be NULL if \a fPack is \c false.
1786 * @param cbPackFile Size (in bytes) of \a pszPackFile. Can be 0 if \a fPack is \c false.
1787 */
1788int audioTestEnvPrologue(PAUDIOTESTENV pTstEnv, bool fPack, char *pszPackFile, size_t cbPackFile)
1789{
1790 /* Close the test set first. */
1791 AudioTestSetClose(&pTstEnv->Set);
1792
1793 int rc = VINF_SUCCESS;
1794
1795 if (fPack)
1796 {
1797 /* Before destroying the test environment, pack up the test set so
1798 * that it's ready for transmission. */
1799 rc = AudioTestSetPack(&pTstEnv->Set, pTstEnv->szPathOut, pszPackFile, cbPackFile);
1800 if (RT_SUCCESS(rc))
1801 RTTestPrintf(g_hTest, RTTESTLVL_ALWAYS, "Test set packed up to '%s'\n", pszPackFile);
1802 }
1803
1804 if (!g_fDrvAudioDebug) /* Don't wipe stuff when debugging. Can be useful for introspecting data. */
1805 /* ignore rc */ AudioTestSetWipe(&pTstEnv->Set);
1806
1807 AudioTestSetDestroy(&pTstEnv->Set);
1808
1809 if (RT_FAILURE(rc))
1810 RTTestFailed(g_hTest, "Test set prologue failed with %Rrc\n", rc);
1811
1812 return rc;
1813}
1814
1815/**
1816 * Initializes an audio test parameters set.
1817 *
1818 * @param pTstParms Test parameters set to initialize.
1819 */
1820void audioTestParmsInit(PAUDIOTESTPARMS pTstParms)
1821{
1822 RT_ZERO(*pTstParms);
1823}
1824
1825/**
1826 * Destroys an audio test parameters set.
1827 *
1828 * @param pTstParms Test parameters set to destroy.
1829 */
1830void audioTestParmsDestroy(PAUDIOTESTPARMS pTstParms)
1831{
1832 if (!pTstParms)
1833 return;
1834
1835 return;
1836}
1837
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