VirtualBox

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

Last change on this file since 103530 was 103530, checked in by vboxsync, 13 months ago

Audio/VKAT: Logging nits.

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

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