VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/AudioTest.cpp@ 92348

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

Audio/Validation Kit: Adjust the size of the area to compare so that it's within the pre + post beacons. bugref:10008

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 123.5 KB
Line 
1/* $Id: AudioTest.cpp 92337 2021-11-10 18:50:53Z vboxsync $ */
2/** @file
3 * Audio testing routines.
4 *
5 * Common code which is being used by the ValidationKit and the
6 * debug / ValdikationKit audio driver(s).
7 */
8
9/*
10 * Copyright (C) 2021 Oracle Corporation
11 *
12 * This file is part of VirtualBox Open Source Edition (OSE), as
13 * available from http://www.virtualbox.org. This file is free software;
14 * you can redistribute it and/or modify it under the terms of the GNU
15 * General Public License (GPL) as published by the Free Software
16 * Foundation, in version 2 as it comes in the "COPYING" file of the
17 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
18 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
19 */
20
21
22/*********************************************************************************************************************************
23* Header Files *
24*********************************************************************************************************************************/
25#include <package-generated.h>
26#include "product-generated.h"
27
28#include <iprt/buildconfig.h>
29#include <iprt/cdefs.h>
30#include <iprt/dir.h>
31#include <iprt/env.h>
32#include <iprt/file.h>
33#include <iprt/formats/riff.h>
34#include <iprt/inifile.h>
35#include <iprt/list.h>
36#include <iprt/message.h> /** @todo Get rid of this once we have own log hooks. */
37#include <iprt/rand.h>
38#include <iprt/stream.h>
39#include <iprt/system.h>
40#include <iprt/uuid.h>
41#include <iprt/vfs.h>
42#include <iprt/zip.h>
43
44#define _USE_MATH_DEFINES
45#include <math.h> /* sin, M_PI */
46
47#define LOG_GROUP LOG_GROUP_AUDIO_TEST
48#include <VBox/log.h>
49
50#include <VBox/version.h>
51#include <VBox/vmm/pdmaudioifs.h>
52#include <VBox/vmm/pdmaudioinline.h>
53
54#include "AudioTest.h"
55
56
57/*********************************************************************************************************************************
58* Defines *
59*********************************************************************************************************************************/
60/** The test manifest file name. */
61#define AUDIOTEST_MANIFEST_FILE_STR "vkat_manifest.ini"
62/** The current test manifest version. */
63#define AUDIOTEST_MANIFEST_VER 1
64/** Audio test archive default suffix.
65 * According to IPRT terminology this always contains the dot. */
66#define AUDIOTEST_ARCHIVE_SUFF_STR ".tar.gz"
67
68/** Test manifest header name. */
69#define AUDIOTEST_SEC_HDR_STR "header"
70/** Maximum section name length (in UTF-8 characters). */
71#define AUDIOTEST_MAX_SEC_LEN 128
72/** Maximum object name length (in UTF-8 characters). */
73#define AUDIOTEST_MAX_OBJ_LEN 128
74
75
76/*********************************************************************************************************************************
77* Structures and Typedefs *
78*********************************************************************************************************************************/
79/**
80 * Enumeration for an audio test object type.
81 */
82typedef enum AUDIOTESTOBJTYPE
83{
84 /** Unknown / invalid, do not use. */
85 AUDIOTESTOBJTYPE_UNKNOWN = 0,
86 /** The test object is a file. */
87 AUDIOTESTOBJTYPE_FILE,
88 /** The usual 32-bit hack. */
89 AUDIOTESTOBJTYPE_32BIT_HACK = 0x7fffffff
90} AUDIOTESTOBJTYPE;
91
92/**
93 * Structure for keeping an audio test object file.
94 */
95typedef struct AUDIOTESTOBJFILE
96{
97 /** File handle. */
98 RTFILE hFile;
99 /** Total size (in bytes). */
100 size_t cbSize;
101} AUDIOTESTOBJFILE;
102/** Pointer to an audio test object file. */
103typedef AUDIOTESTOBJFILE *PAUDIOTESTOBJFILE;
104
105/**
106 * Enumeration for an audio test object meta data type.
107 */
108typedef enum AUDIOTESTOBJMETADATATYPE
109{
110 /** Unknown / invalid, do not use. */
111 AUDIOTESTOBJMETADATATYPE_INVALID = 0,
112 /** Meta data is an UTF-8 string. */
113 AUDIOTESTOBJMETADATATYPE_STRING,
114 /** The usual 32-bit hack. */
115 AUDIOTESTOBJMETADATATYPE_32BIT_HACK = 0x7fffffff
116} AUDIOTESTOBJMETADATATYPE;
117
118/**
119 * Structure for keeping a meta data block.
120 */
121typedef struct AUDIOTESTOBJMETA
122{
123 /** List node. */
124 RTLISTNODE Node;
125 /** Meta data type. */
126 AUDIOTESTOBJMETADATATYPE enmType;
127 /** Meta data block. */
128 void *pvMeta;
129 /** Size (in bytes) of \a pvMeta. */
130 size_t cbMeta;
131} AUDIOTESTOBJMETA;
132/** Pointer to an audio test object file. */
133typedef AUDIOTESTOBJMETA *PAUDIOTESTOBJMETA;
134
135/**
136 * Structure for keeping a single audio test object.
137 *
138 * A test object is data which is needed in order to perform and verify one or
139 * more audio test case(s).
140 */
141typedef struct AUDIOTESTOBJINT
142{
143 /** List node. */
144 RTLISTNODE Node;
145 /** Pointer to test set this handle is bound to. */
146 PAUDIOTESTSET pSet;
147 /** As we only support .INI-style files for now, this only has the object's section name in it. */
148 /** @todo Make this more generic (union, ++). */
149 char szSec[AUDIOTEST_MAX_SEC_LEN];
150 /** The UUID of the object.
151 * Used to identify an object within a test set. */
152 RTUUID Uuid;
153 /** Number of references to this test object. */
154 uint32_t cRefs;
155 /** Name of the test object.
156 * Must not contain a path and has to be able to serialize to disk. */
157 char szName[256];
158 /** The test type. */
159 AUDIOTESTTYPE enmTestType;
160 /** The object type. */
161 AUDIOTESTOBJTYPE enmType;
162 /** Meta data list. */
163 RTLISTANCHOR lstMeta;
164 /** Union for holding the object type-specific data. */
165 union
166 {
167 AUDIOTESTOBJFILE File;
168 };
169} AUDIOTESTOBJINT;
170/** Pointer to an audio test object. */
171typedef AUDIOTESTOBJINT *PAUDIOTESTOBJINT;
172
173/**
174 * Structure for keeping an audio test verification job.
175 */
176typedef struct AUDIOTESTVERIFYJOB
177{
178 /** Pointer to set A. */
179 PAUDIOTESTSET pSetA;
180 /** Pointer to set B. */
181 PAUDIOTESTSET pSetB;
182 /** Pointer to the error description to use. */
183 PAUDIOTESTERRORDESC pErr;
184 /** Zero-based index of current test being verified. */
185 uint32_t idxTest;
186 /** The verification options to use. */
187 AUDIOTESTVERIFYOPTS Opts;
188 /** PCM properties to use for verification. */
189 PDMAUDIOPCMPROPS PCMProps;
190} AUDIOTESTVERIFYJOB;
191/** Pointer to an audio test verification job. */
192typedef AUDIOTESTVERIFYJOB *PAUDIOTESTVERIFYJOB;
193
194
195/*********************************************************************************************************************************
196* Global Variables *
197*********************************************************************************************************************************/
198/** Well-known frequency selection test tones. */
199static const double s_aAudioTestToneFreqsHz[] =
200{
201 349.2282 /*F4*/,
202 440.0000 /*A4*/,
203 523.2511 /*C5*/,
204 698.4565 /*F5*/,
205 880.0000 /*A5*/,
206 1046.502 /*C6*/,
207 1174.659 /*D6*/,
208 1396.913 /*F6*/,
209 1760.0000 /*A6*/
210};
211
212
213/*********************************************************************************************************************************
214* Internal Functions *
215*********************************************************************************************************************************/
216static int audioTestObjClose(PAUDIOTESTOBJINT pObj);
217static void audioTestObjFinalize(PAUDIOTESTOBJINT pObj);
218static void audioTestObjInit(PAUDIOTESTOBJINT pObj);
219static bool audioTestObjIsOpen(PAUDIOTESTOBJINT pObj);
220
221
222/**
223 * Initializes a test tone with a specific frequency (in Hz).
224 *
225 * @returns Used tone frequency (in Hz).
226 * @param pTone Pointer to test tone to initialize.
227 * @param pProps PCM properties to use for the test tone.
228 * @param dbFreq Frequency (in Hz) to initialize tone with.
229 * When set to 0.0, a random frequency will be chosen.
230 */
231double AudioTestToneInit(PAUDIOTESTTONE pTone, PPDMAUDIOPCMPROPS pProps, double dbFreq)
232{
233 if (dbFreq == 0.0)
234 dbFreq = AudioTestToneGetRandomFreq();
235
236 pTone->rdFreqHz = dbFreq;
237 pTone->rdFixed = 2.0 * M_PI * pTone->rdFreqHz / PDMAudioPropsHz(pProps);
238 pTone->uSample = 0;
239
240 memcpy(&pTone->Props, pProps, sizeof(PDMAUDIOPCMPROPS));
241
242 pTone->enmType = AUDIOTESTTONETYPE_SINE; /* Only type implemented so far. */
243
244 return dbFreq;
245}
246
247/**
248 * Initializes a test tone by picking a random but well-known frequency (in Hz).
249 *
250 * @returns Randomly picked tone frequency (in Hz).
251 * @param pTone Pointer to test tone to initialize.
252 * @param pProps PCM properties to use for the test tone.
253 */
254double AudioTestToneInitRandom(PAUDIOTESTTONE pTone, PPDMAUDIOPCMPROPS pProps)
255{
256 return AudioTestToneInit(pTone, pProps,
257 /* Pick a frequency from our selection, so that every time a recording starts
258 * we'll hopfully generate a different note. */
259 0.0);
260}
261
262/**
263 * Writes (and iterates) a given test tone to an output buffer.
264 *
265 * @returns VBox status code.
266 * @param pTone Pointer to test tone to write.
267 * @param pvBuf Pointer to output buffer to write test tone to.
268 * @param cbBuf Size (in bytes) of output buffer.
269 * @param pcbWritten How many bytes were written on success.
270 */
271int AudioTestToneGenerate(PAUDIOTESTTONE pTone, void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
272{
273 /*
274 * Clear the buffer first so we don't need to think about additional channels.
275 */
276 uint32_t cFrames = PDMAudioPropsBytesToFrames(&pTone->Props, cbBuf);
277
278 /* Input cbBuf not necessarily is aligned to the frames, so re-calculate it. */
279 const uint32_t cbToWrite = PDMAudioPropsFramesToBytes(&pTone->Props, cFrames);
280
281 PDMAudioPropsClearBuffer(&pTone->Props, pvBuf, cbBuf, cFrames);
282
283 /*
284 * Generate the select sin wave in the first channel:
285 */
286 uint32_t const cbFrame = PDMAudioPropsFrameSize(&pTone->Props);
287 double const rdFixed = pTone->rdFixed;
288 uint64_t iSrcFrame = pTone->uSample;
289 switch (PDMAudioPropsSampleSize(&pTone->Props))
290 {
291 case 1:
292 /* untested */
293 if (PDMAudioPropsIsSigned(&pTone->Props))
294 {
295 int8_t *piSample = (int8_t *)pvBuf;
296 while (cFrames-- > 0)
297 {
298 *piSample = (int8_t)(126 /*Amplitude*/ * sin(rdFixed * iSrcFrame));
299 iSrcFrame++;
300 piSample += cbFrame;
301 }
302 }
303 else
304 {
305 /* untested */
306 uint8_t *pbSample = (uint8_t *)pvBuf;
307 while (cFrames-- > 0)
308 {
309 *pbSample = (uint8_t)(126 /*Amplitude*/ * sin(rdFixed * iSrcFrame) + 0x80);
310 iSrcFrame++;
311 pbSample += cbFrame;
312 }
313 }
314 break;
315
316 case 2:
317 if (PDMAudioPropsIsSigned(&pTone->Props))
318 {
319 int16_t *piSample = (int16_t *)pvBuf;
320 while (cFrames-- > 0)
321 {
322 *piSample = (int16_t)(32760 /*Amplitude*/ * sin(rdFixed * iSrcFrame));
323 iSrcFrame++;
324 piSample = (int16_t *)((uint8_t *)piSample + cbFrame);
325 }
326 }
327 else
328 {
329 /* untested */
330 uint16_t *puSample = (uint16_t *)pvBuf;
331 while (cFrames-- > 0)
332 {
333 *puSample = (uint16_t)(32760 /*Amplitude*/ * sin(rdFixed * iSrcFrame) + 0x8000);
334 iSrcFrame++;
335 puSample = (uint16_t *)((uint8_t *)puSample + cbFrame);
336 }
337 }
338 break;
339
340 case 4:
341 /* untested */
342 if (PDMAudioPropsIsSigned(&pTone->Props))
343 {
344 int32_t *piSample = (int32_t *)pvBuf;
345 while (cFrames-- > 0)
346 {
347 *piSample = (int32_t)((32760 << 16) /*Amplitude*/ * sin(rdFixed * iSrcFrame));
348 iSrcFrame++;
349 piSample = (int32_t *)((uint8_t *)piSample + cbFrame);
350 }
351 }
352 else
353 {
354 uint32_t *puSample = (uint32_t *)pvBuf;
355 while (cFrames-- > 0)
356 {
357 *puSample = (uint32_t)((32760 << 16) /*Amplitude*/ * sin(rdFixed * iSrcFrame) + UINT32_C(0x80000000));
358 iSrcFrame++;
359 puSample = (uint32_t *)((uint8_t *)puSample + cbFrame);
360 }
361 }
362 break;
363
364 default:
365 AssertFailedReturn(VERR_NOT_SUPPORTED);
366 }
367
368 pTone->uSample = iSrcFrame;
369
370 if (pcbWritten)
371 *pcbWritten = cbToWrite;
372
373 return VINF_SUCCESS;
374}
375
376/**
377 * Returns a random test tone frequency.
378 */
379double AudioTestToneGetRandomFreq(void)
380{
381 return s_aAudioTestToneFreqsHz[RTRandU32Ex(0, RT_ELEMENTS(s_aAudioTestToneFreqsHz) - 1)];
382}
383
384/**
385 * Finds the next audible *or* silent audio sample and returns its offset.
386 *
387 * @returns Offset (in bytes) of the next found sample, or \a cbMax if not found / invalid parameters.
388 * @param hFile File handle of file to search in.
389 * @param fFindSilence Whether to search for a silent sample or not (i.e. audible).
390 * What a silent sample is depends on \a pToneParms PCM parameters.
391 * @param uOff Absolute offset (in bytes) to start searching from.
392 * @param cbMax Maximum amount of bytes to process.
393 * @param pToneParms Tone parameters to use.
394 * @param cbWindow Search window size (in bytes).
395 */
396static uint64_t audioTestToneFileFind(RTFILE hFile, bool fFindSilence, uint64_t uOff, uint64_t cbMax,
397 PAUDIOTESTTONEPARMS pToneParms, size_t cbWindow)
398{
399 int rc = RTFileSeek(hFile, uOff, RTFILE_SEEK_BEGIN, NULL);
400 AssertRCReturn(rc, UINT64_MAX);
401
402 uint64_t offFound = 0;
403 uint8_t abBuf[_64K];
404
405 size_t const cbFrame = PDMAudioPropsFrameSize(&pToneParms->Props);
406 AssertReturn(cbFrame, UINT64_MAX);
407
408 AssertReturn(PDMAudioPropsIsSizeAligned(&pToneParms->Props, (uint32_t)cbWindow), UINT64_MAX);
409
410 size_t cbRead;
411 for (;;)
412 {
413 rc = RTFileRead(hFile, &abBuf, RT_MIN(cbWindow, sizeof(abBuf)), &cbRead);
414 if ( RT_FAILURE(rc)
415 || !cbRead)
416 break;
417
418 AssertReturn(PDMAudioPropsIsSizeAligned(&pToneParms->Props, (uint32_t)cbRead), UINT64_MAX);
419 AssertReturn(cbRead % cbFrame == 0, UINT64_MAX);
420
421 /** @todo Do we need to have a sliding window here? */
422
423 for (size_t i = 0; i < cbRead; i += cbWindow) /** @todo Slow as heck, but works for now. */
424 {
425 bool const fIsSilence = PDMAudioPropsIsBufferSilence(&pToneParms->Props, (const uint8_t *)abBuf + i, cbWindow);
426 if (fIsSilence != fFindSilence)
427 {
428 AssertReturn(PDMAudioPropsIsSizeAligned(&pToneParms->Props, offFound), 0);
429 return offFound;
430 }
431 offFound += cbWindow;
432 }
433 }
434
435 return cbMax;
436}
437
438/**
439 * Generates a tag.
440 *
441 * @returns VBox status code.
442 * @param pszTag The output buffer.
443 * @param cbTag The size of the output buffer.
444 * AUDIOTEST_TAG_MAX is a good size.
445 */
446int AudioTestGenTag(char *pszTag, size_t cbTag)
447{
448 RTUUID UUID;
449 int rc = RTUuidCreate(&UUID);
450 AssertRCReturn(rc, rc);
451 rc = RTUuidToStr(&UUID, pszTag, cbTag);
452 AssertRCReturn(rc, rc);
453 return rc;
454}
455
456/**
457 * Return the tag to use in the given buffer, generating one if needed.
458 *
459 * @returns VBox status code.
460 * @param pszTag The output buffer.
461 * @param cbTag The size of the output buffer.
462 * AUDIOTEST_TAG_MAX is a good size.
463 * @param pszTagUser User specified tag, optional.
464 */
465static int audioTestCopyOrGenTag(char *pszTag, size_t cbTag, const char *pszTagUser)
466{
467 if (pszTagUser && *pszTagUser)
468 return RTStrCopy(pszTag, cbTag, pszTagUser);
469 return AudioTestGenTag(pszTag, cbTag);
470}
471
472
473/**
474 * Creates a new path (directory) for a specific audio test set tag.
475 *
476 * @returns VBox status code.
477 * @param pszPath On input, specifies the absolute base path where to create the test set path.
478 * On output this specifies the absolute path created.
479 * @param cbPath Size (in bytes) of \a pszPath.
480 * @param pszTag Tag to use for path creation.
481 *
482 * @note Can be used multiple times with the same tag; a sub directory with an ISO time string will be used
483 * on each call.
484 */
485int AudioTestPathCreate(char *pszPath, size_t cbPath, const char *pszTag)
486{
487 char szTag[AUDIOTEST_TAG_MAX];
488 int rc = audioTestCopyOrGenTag(szTag, sizeof(szTag), pszTag);
489 AssertRCReturn(rc, rc);
490
491 char szName[RT_ELEMENTS(AUDIOTEST_PATH_PREFIX_STR) + AUDIOTEST_TAG_MAX + 4];
492 if (RTStrPrintf2(szName, sizeof(szName), "%s-%s", AUDIOTEST_PATH_PREFIX_STR, szTag) < 0)
493 AssertFailedReturn(VERR_BUFFER_OVERFLOW);
494
495 rc = RTPathAppend(pszPath, cbPath, szName);
496 AssertRCReturn(rc, rc);
497
498#ifndef DEBUG /* Makes debugging easier to have a deterministic directory. */
499 char szTime[64];
500 RTTIMESPEC time;
501 if (!RTTimeSpecToString(RTTimeNow(&time), szTime, sizeof(szTime)))
502 return VERR_BUFFER_UNDERFLOW;
503
504 /* Colons aren't allowed in windows filenames, so change to dashes. */
505 char *pszColon;
506 while ((pszColon = strchr(szTime, ':')) != NULL)
507 *pszColon = '-';
508
509 rc = RTPathAppend(pszPath, cbPath, szTime);
510 AssertRCReturn(rc, rc);
511#endif
512
513 return RTDirCreateFullPath(pszPath, RTFS_UNIX_IRWXU);
514}
515
516DECLINLINE(int) audioTestManifestWriteData(PAUDIOTESTSET pSet, const void *pvData, size_t cbData)
517{
518 /** @todo Use RTIniFileWrite once its implemented. */
519 return RTFileWrite(pSet->f.hFile, pvData, cbData, NULL);
520}
521
522/**
523 * Writes string data to a test set manifest.
524 *
525 * @returns VBox status code.
526 * @param pSet Test set to write manifest for.
527 * @param pszFormat Format string to write.
528 * @param args Variable arguments for \a pszFormat.
529 */
530static int audioTestManifestWriteV(PAUDIOTESTSET pSet, const char *pszFormat, va_list args)
531{
532 /** @todo r=bird: Use RTStrmOpen + RTStrmPrintf instead of this slow
533 * do-it-all-yourself stuff. */
534 char *psz = NULL;
535 if (RTStrAPrintfV(&psz, pszFormat, args) == -1)
536 return VERR_NO_MEMORY;
537 AssertPtrReturn(psz, VERR_NO_MEMORY);
538
539 int rc = audioTestManifestWriteData(pSet, psz, strlen(psz));
540 AssertRC(rc);
541
542 RTStrFree(psz);
543
544 return rc;
545}
546
547/**
548 * Writes a string to a test set manifest.
549 * Convenience function.
550 *
551 * @returns VBox status code.
552 * @param pSet Test set to write manifest for.
553 * @param pszFormat Format string to write.
554 * @param ... Variable arguments for \a pszFormat. Optional.
555 */
556static int audioTestManifestWrite(PAUDIOTESTSET pSet, const char *pszFormat, ...)
557{
558 va_list va;
559 va_start(va, pszFormat);
560
561 int rc = audioTestManifestWriteV(pSet, pszFormat, va);
562 AssertRC(rc);
563
564 va_end(va);
565
566 return rc;
567}
568
569/**
570 * Returns the current read/write offset (in bytes) of the opened manifest file.
571 *
572 * @returns Current read/write offset (in bytes).
573 * @param pSet Set to return offset for.
574 * Must have an opened manifest file.
575 */
576DECLINLINE(uint64_t) audioTestManifestGetOffsetAbs(PAUDIOTESTSET pSet)
577{
578 AssertReturn(RTFileIsValid(pSet->f.hFile), 0);
579 return RTFileTell(pSet->f.hFile);
580}
581
582/**
583 * Writes a section header to a test set manifest.
584 *
585 * @returns VBox status code.
586 * @param pSet Test set to write manifest for.
587 * @param pszSection Format string of section to write.
588 * @param ... Variable arguments for \a pszSection. Optional.
589 */
590static int audioTestManifestWriteSectionHdr(PAUDIOTESTSET pSet, const char *pszSection, ...)
591{
592 va_list va;
593 va_start(va, pszSection);
594
595 /** @todo Keep it as simple as possible for now. Improve this later. */
596 int rc = audioTestManifestWrite(pSet, "[%N]\n", pszSection, &va);
597
598 va_end(va);
599
600 return rc;
601}
602
603/**
604 * Initializes an audio test set, internal function.
605 *
606 * @param pSet Test set to initialize.
607 */
608static void audioTestSetInitInternal(PAUDIOTESTSET pSet)
609{
610 pSet->f.hFile = NIL_RTFILE;
611
612 RTListInit(&pSet->lstObj);
613 pSet->cObj = 0;
614
615 RTListInit(&pSet->lstTest);
616 pSet->cTests = 0;
617 pSet->cTestsRunning = 0;
618 pSet->offTestCount = 0;
619 pSet->pTestCur = NULL;
620 pSet->cObj = 0;
621 pSet->offObjCount = 0;
622 pSet->cTotalFailures = 0;
623}
624
625/**
626 * Returns whether a test set's manifest file is open (and thus ready) or not.
627 *
628 * @returns \c true if open (and ready), or \c false if not.
629 * @retval VERR_
630 * @param pSet Test set to return open status for.
631 */
632static bool audioTestManifestIsOpen(PAUDIOTESTSET pSet)
633{
634 if ( pSet->enmMode == AUDIOTESTSETMODE_TEST
635 && pSet->f.hFile != NIL_RTFILE)
636 return true;
637 else if ( pSet->enmMode == AUDIOTESTSETMODE_VERIFY
638 && pSet->f.hIniFile != NIL_RTINIFILE)
639 return true;
640
641 return false;
642}
643
644/**
645 * Initializes an audio test error description.
646 *
647 * @param pErr Test error description to initialize.
648 */
649static void audioTestErrorDescInit(PAUDIOTESTERRORDESC pErr)
650{
651 RTListInit(&pErr->List);
652 pErr->cErrors = 0;
653}
654
655/**
656 * Destroys an audio test error description.
657 *
658 * @param pErr Test error description to destroy.
659 */
660void AudioTestErrorDescDestroy(PAUDIOTESTERRORDESC pErr)
661{
662 if (!pErr)
663 return;
664
665 PAUDIOTESTERRORENTRY pErrEntry, pErrEntryNext;
666 RTListForEachSafe(&pErr->List, pErrEntry, pErrEntryNext, AUDIOTESTERRORENTRY, Node)
667 {
668 RTListNodeRemove(&pErrEntry->Node);
669
670 RTMemFree(pErrEntry);
671 }
672
673 pErr->cErrors = 0;
674}
675
676/**
677 * Returns the the number of errors of an audio test error description.
678 *
679 * @returns Error count.
680 * @param pErr Test error description to return error count for.
681 */
682uint32_t AudioTestErrorDescCount(PCAUDIOTESTERRORDESC pErr)
683{
684 return pErr->cErrors;
685}
686
687/**
688 * Returns if an audio test error description contains any errors or not.
689 *
690 * @returns \c true if it contains errors, or \c false if not.
691 * @param pErr Test error description to return error status for.
692 */
693bool AudioTestErrorDescFailed(PCAUDIOTESTERRORDESC pErr)
694{
695 if (pErr->cErrors)
696 {
697 Assert(!RTListIsEmpty(&pErr->List));
698 return true;
699 }
700
701 return false;
702}
703
704/**
705 * Adds a single error entry to an audio test error description, va_list version.
706 *
707 * @returns VBox status code.
708 * @param pErr Test error description to add entry for.
709 * @param idxTest Index of failing test (zero-based).
710 * @param rc Result code of entry to add.
711 * @param pszFormat Error description format string to add.
712 * @param va Optional format arguments of \a pszDesc to add.
713 */
714static int audioTestErrorDescAddV(PAUDIOTESTERRORDESC pErr, uint32_t idxTest, int rc, const char *pszFormat, va_list va)
715{
716 PAUDIOTESTERRORENTRY pEntry = (PAUDIOTESTERRORENTRY)RTMemAlloc(sizeof(AUDIOTESTERRORENTRY));
717 AssertPtrReturn(pEntry, VERR_NO_MEMORY);
718
719 char *pszDescTmp;
720 if (RTStrAPrintfV(&pszDescTmp, pszFormat, va) < 0)
721 AssertFailedReturn(VERR_NO_MEMORY);
722
723 const ssize_t cch = RTStrPrintf2(pEntry->szDesc, sizeof(pEntry->szDesc), "Test #%RU32 %s: %s",
724 idxTest, RT_FAILURE(rc) ? "failed" : "info", pszDescTmp);
725 RTStrFree(pszDescTmp);
726 AssertReturn(cch > 0, VERR_BUFFER_OVERFLOW);
727
728 pEntry->rc = rc;
729
730 RTListAppend(&pErr->List, &pEntry->Node);
731
732 if (RT_FAILURE(rc))
733 pErr->cErrors++;
734
735 return VINF_SUCCESS;
736}
737
738/**
739 * Adds a single error entry to an audio test error description.
740 *
741 * @returns VBox status code.
742 * @param pErr Test error description to add entry for.
743 * @param idxTest Index of failing test (zero-based).
744 * @param pszFormat Error description format string to add.
745 * @param ... Optional format arguments of \a pszDesc to add.
746 */
747static int audioTestErrorDescAddError(PAUDIOTESTERRORDESC pErr, uint32_t idxTest, const char *pszFormat, ...)
748{
749 va_list va;
750 va_start(va, pszFormat);
751
752 int rc = audioTestErrorDescAddV(pErr, idxTest, VERR_GENERAL_FAILURE /** @todo Fudge! */, pszFormat, va);
753
754 va_end(va);
755 return rc;
756}
757
758/**
759 * Adds a single info entry to an audio test error description, va_list version.
760 *
761 * @returns VBox status code.
762 * @param pErr Test error description to add entry for.
763 * @param idxTest Index of failing test (zero-based).
764 * @param pszFormat Error description format string to add.
765 * @param ... Optional format arguments of \a pszDesc to add.
766 */
767static int audioTestErrorDescAddInfo(PAUDIOTESTERRORDESC pErr, uint32_t idxTest, const char *pszFormat, ...)
768{
769 va_list va;
770 va_start(va, pszFormat);
771
772 int rc = audioTestErrorDescAddV(pErr, idxTest, VINF_SUCCESS, pszFormat, va);
773
774 va_end(va);
775 return rc;
776}
777
778#if 0
779static int audioTestErrorDescAddRc(PAUDIOTESTERRORDESC pErr, int rc, const char *pszFormat, ...)
780{
781 va_list va;
782 va_start(va, pszFormat);
783
784 int rc2 = audioTestErrorDescAddV(pErr, rc, pszFormat, va);
785
786 va_end(va);
787 return rc2;
788}
789#endif
790
791/**
792 * Retrieves the temporary directory.
793 *
794 * @returns VBox status code.
795 * @param pszPath Where to return the absolute path of the created directory on success.
796 * @param cbPath Size (in bytes) of \a pszPath.
797 */
798int AudioTestPathGetTemp(char *pszPath, size_t cbPath)
799{
800 int rc = RTEnvGetEx(RTENV_DEFAULT, "TESTBOX_PATH_SCRATCH", pszPath, cbPath, NULL);
801 if (RT_FAILURE(rc))
802 {
803 rc = RTPathTemp(pszPath, cbPath);
804 AssertRCReturn(rc, rc);
805 }
806
807 return rc;
808}
809
810/**
811 * Creates a new temporary directory with a specific (test) tag.
812 *
813 * @returns VBox status code.
814 * @param pszPath Where to return the absolute path of the created directory on success.
815 * @param cbPath Size (in bytes) of \a pszPath.
816 * @param pszTag Tag name to use for directory creation.
817 *
818 * @note Can be used multiple times with the same tag; a sub directory with an ISO time string will be used
819 * on each call.
820 */
821int AudioTestPathCreateTemp(char *pszPath, size_t cbPath, const char *pszTag)
822{
823 AssertReturn(pszTag && strlen(pszTag) <= AUDIOTEST_TAG_MAX, VERR_INVALID_PARAMETER);
824
825 char szTemp[RTPATH_MAX];
826 int rc = AudioTestPathGetTemp(szTemp, sizeof(szTemp));
827 AssertRCReturn(rc, rc);
828
829 rc = AudioTestPathCreate(szTemp, sizeof(szTemp), pszTag);
830 AssertRCReturn(rc, rc);
831
832 return RTStrCopy(pszPath, cbPath, szTemp);
833}
834
835/**
836 * Gets a value as string.
837 *
838 * @returns VBox status code.
839 * @param pObj Object handle to get value for.
840 * @param pszKey Key to get value from.
841 * @param pszVal Where to return the value on success.
842 * @param cbVal Size (in bytes) of \a pszVal.
843 */
844static int audioTestObjGetStr(PAUDIOTESTOBJINT pObj, const char *pszKey, char *pszVal, size_t cbVal)
845{
846 /** @todo For now we only support .INI-style files. */
847 AssertPtrReturn(pObj->pSet, VERR_WRONG_ORDER);
848 return RTIniFileQueryValue(pObj->pSet->f.hIniFile, pObj->szSec, pszKey, pszVal, cbVal, NULL);
849}
850
851/**
852 * Gets a value as boolean.
853 *
854 * @returns VBox status code.
855 * @param pObj Object handle to get value for.
856 * @param pszKey Key to get value from.
857 * @param pbVal Where to return the value on success.
858 */
859static int audioTestObjGetBool(PAUDIOTESTOBJINT pObj, const char *pszKey, bool *pbVal)
860{
861 char szVal[_1K];
862 int rc = audioTestObjGetStr(pObj, pszKey, szVal, sizeof(szVal));
863 if (RT_SUCCESS(rc))
864 *pbVal = (RTStrICmp(szVal, "true") == 0)
865 || (RTStrICmp(szVal, "1") == 0) ? true : false;
866
867 return rc;
868}
869
870/**
871 * Gets a value as uint8_t.
872 *
873 * @returns VBox status code.
874 * @param pObj Object handle to get value for.
875 * @param pszKey Key to get value from.
876 * @param puVal Where to return the value on success.
877 */
878static int audioTestObjGetUInt8(PAUDIOTESTOBJINT pObj, const char *pszKey, uint8_t *puVal)
879{
880 char szVal[_1K];
881 int rc = audioTestObjGetStr(pObj, pszKey, szVal, sizeof(szVal));
882 if (RT_SUCCESS(rc))
883 *puVal = RTStrToUInt8(szVal);
884
885 return rc;
886}
887
888/**
889 * Gets a value as uint32_t.
890 *
891 * @returns VBox status code.
892 * @param pObj Object handle to get value for.
893 * @param pszKey Key to get value from.
894 * @param puVal Where to return the value on success.
895 */
896static int audioTestObjGetUInt32(PAUDIOTESTOBJINT pObj, const char *pszKey, uint32_t *puVal)
897{
898 char szVal[_1K];
899 int rc = audioTestObjGetStr(pObj, pszKey, szVal, sizeof(szVal));
900 if (RT_SUCCESS(rc))
901 *puVal = RTStrToUInt32(szVal);
902
903 return rc;
904}
905
906/**
907 * Returns the absolute path of a given audio test set object.
908 *
909 * @returns VBox status code.
910 * @param pSet Test set the object contains.
911 * @param pszPathAbs Where to return the absolute path on success.
912 * @param cbPathAbs Size (in bytes) of \a pszPathAbs.
913 * @param pszObjName Name of the object to create absolute path for.
914 */
915DECLINLINE(int) audioTestSetGetObjPath(PAUDIOTESTSET pSet, char *pszPathAbs, size_t cbPathAbs, const char *pszObjName)
916{
917 return RTPathJoin(pszPathAbs, cbPathAbs, pSet->szPathAbs, pszObjName);
918}
919
920/**
921 * Returns the tag of a test set.
922 *
923 * @returns Test set tag.
924 * @param pSet Test set to return tag for.
925 */
926const char *AudioTestSetGetTag(PAUDIOTESTSET pSet)
927{
928 return pSet->szTag;
929}
930
931/**
932 * Returns the total number of registered tests.
933 *
934 * @returns Total number of registered tests.
935 * @param pSet Test set to return value for.
936 */
937uint32_t AudioTestSetGetTestsTotal(PAUDIOTESTSET pSet)
938{
939 return pSet->cTests;
940}
941
942/**
943 * Returns the total number of (still) running tests.
944 *
945 * @returns Total number of (still) running tests.
946 * @param pSet Test set to return value for.
947 */
948uint32_t AudioTestSetGetTestsRunning(PAUDIOTESTSET pSet)
949{
950 return pSet->cTestsRunning;
951}
952
953/**
954 * Returns the total number of test failures occurred.
955 *
956 * @returns Total number of test failures occurred.
957 * @param pSet Test set to return value for.
958 */
959uint32_t AudioTestSetGetTotalFailures(PAUDIOTESTSET pSet)
960{
961 return pSet->cTotalFailures;
962}
963
964/**
965 * Creates a new audio test set.
966 *
967 * @returns VBox status code.
968 * @param pSet Test set to create.
969 * @param pszPath Where to store the set set data. If NULL, the
970 * temporary directory will be used.
971 * @param pszTag Tag name to use for this test set.
972 */
973int AudioTestSetCreate(PAUDIOTESTSET pSet, const char *pszPath, const char *pszTag)
974{
975 audioTestSetInitInternal(pSet);
976
977 int rc = audioTestCopyOrGenTag(pSet->szTag, sizeof(pSet->szTag), pszTag);
978 AssertRCReturn(rc, rc);
979
980 /*
981 * Test set directory.
982 */
983 if (pszPath)
984 {
985 rc = RTPathAbs(pszPath, pSet->szPathAbs, sizeof(pSet->szPathAbs));
986 AssertRCReturn(rc, rc);
987
988 rc = AudioTestPathCreate(pSet->szPathAbs, sizeof(pSet->szPathAbs), pSet->szTag);
989 }
990 else
991 rc = AudioTestPathCreateTemp(pSet->szPathAbs, sizeof(pSet->szPathAbs), pSet->szTag);
992 AssertRCReturn(rc, rc);
993
994 /*
995 * Create the manifest file.
996 */
997 char szTmp[RTPATH_MAX];
998 rc = RTPathJoin(szTmp, sizeof(szTmp), pSet->szPathAbs, AUDIOTEST_MANIFEST_FILE_STR);
999 AssertRCReturn(rc, rc);
1000
1001 rc = RTFileOpen(&pSet->f.hFile, szTmp, RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
1002 AssertRCReturn(rc, rc);
1003
1004 rc = audioTestManifestWriteSectionHdr(pSet, "header");
1005 AssertRCReturn(rc, rc);
1006
1007 rc = audioTestManifestWrite(pSet, "magic=vkat_ini\n"); /* VKAT Manifest, .INI-style. */
1008 AssertRCReturn(rc, rc);
1009 rc = audioTestManifestWrite(pSet, "ver=%d\n", AUDIOTEST_MANIFEST_VER);
1010 AssertRCReturn(rc, rc);
1011 rc = audioTestManifestWrite(pSet, "tag=%s\n", pSet->szTag);
1012 AssertRCReturn(rc, rc);
1013
1014 AssertCompile(sizeof(szTmp) > RTTIME_STR_LEN);
1015 RTTIMESPEC Now;
1016 rc = audioTestManifestWrite(pSet, "date_created=%s\n", RTTimeSpecToString(RTTimeNow(&Now), szTmp, sizeof(szTmp)));
1017 AssertRCReturn(rc, rc);
1018
1019 RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp)); /* do NOT return on failure. */
1020 rc = audioTestManifestWrite(pSet, "os_product=%s\n", szTmp);
1021 AssertRCReturn(rc, rc);
1022
1023 RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp)); /* do NOT return on failure. */
1024 rc = audioTestManifestWrite(pSet, "os_rel=%s\n", szTmp);
1025 AssertRCReturn(rc, rc);
1026
1027 RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp)); /* do NOT return on failure. */
1028 rc = audioTestManifestWrite(pSet, "os_ver=%s\n", szTmp);
1029 AssertRCReturn(rc, rc);
1030
1031 rc = audioTestManifestWrite(pSet, "vbox_ver=%s r%u %s (%s %s)\n",
1032 VBOX_VERSION_STRING, RTBldCfgRevision(), RTBldCfgTargetDotArch(), __DATE__, __TIME__);
1033 AssertRCReturn(rc, rc);
1034
1035 rc = audioTestManifestWrite(pSet, "test_count=");
1036 AssertRCReturn(rc, rc);
1037 pSet->offTestCount = audioTestManifestGetOffsetAbs(pSet);
1038 rc = audioTestManifestWrite(pSet, "0000\n"); /* A bit messy, but does the trick for now. */
1039 AssertRCReturn(rc, rc);
1040
1041 rc = audioTestManifestWrite(pSet, "obj_count=");
1042 AssertRCReturn(rc, rc);
1043 pSet->offObjCount = audioTestManifestGetOffsetAbs(pSet);
1044 rc = audioTestManifestWrite(pSet, "0000\n"); /* A bit messy, but does the trick for now. */
1045 AssertRCReturn(rc, rc);
1046
1047 pSet->enmMode = AUDIOTESTSETMODE_TEST;
1048
1049 return rc;
1050}
1051
1052/**
1053 * Destroys a test set.
1054 *
1055 * @returns VBox status code.
1056 * @param pSet Test set to destroy.
1057 */
1058int AudioTestSetDestroy(PAUDIOTESTSET pSet)
1059{
1060 if (!pSet)
1061 return VINF_SUCCESS;
1062
1063 /* No more validation (no / still running tests) here -- just pack all stuff we got so far
1064 * and let the verification routine deal with it later. */
1065
1066 int rc = AudioTestSetClose(pSet);
1067 if (RT_FAILURE(rc))
1068 return rc;
1069
1070 PAUDIOTESTOBJINT pObj, pObjNext;
1071 RTListForEachSafe(&pSet->lstObj, pObj, pObjNext, AUDIOTESTOBJINT, Node)
1072 {
1073 rc = audioTestObjClose(pObj);
1074 if (RT_SUCCESS(rc))
1075 {
1076 PAUDIOTESTOBJMETA pMeta, pMetaNext;
1077 RTListForEachSafe(&pObj->lstMeta, pMeta, pMetaNext, AUDIOTESTOBJMETA, Node)
1078 {
1079 switch (pMeta->enmType)
1080 {
1081 case AUDIOTESTOBJMETADATATYPE_STRING:
1082 {
1083 RTStrFree((char *)pMeta->pvMeta);
1084 break;
1085 }
1086
1087 default:
1088 AssertFailed();
1089 break;
1090 }
1091
1092 RTListNodeRemove(&pMeta->Node);
1093 RTMemFree(pMeta);
1094 }
1095
1096 RTListNodeRemove(&pObj->Node);
1097 RTMemFree(pObj);
1098
1099 Assert(pSet->cObj);
1100 pSet->cObj--;
1101 }
1102 else
1103 break;
1104 }
1105
1106 if (RT_FAILURE(rc))
1107 return rc;
1108
1109 Assert(pSet->cObj == 0);
1110
1111 PAUDIOTESTENTRY pEntry, pEntryNext;
1112 RTListForEachSafe(&pSet->lstTest, pEntry, pEntryNext, AUDIOTESTENTRY, Node)
1113 {
1114 RTListNodeRemove(&pEntry->Node);
1115 RTMemFree(pEntry);
1116
1117 Assert(pSet->cTests);
1118 pSet->cTests--;
1119 }
1120
1121 if (RT_FAILURE(rc))
1122 return rc;
1123
1124 Assert(pSet->cTests == 0);
1125
1126 return rc;
1127}
1128
1129/**
1130 * Opens an existing audio test set.
1131 *
1132 * @returns VBox status code.
1133 * @param pSet Test set to open.
1134 * @param pszPath Absolute path of the test set to open.
1135 */
1136int AudioTestSetOpen(PAUDIOTESTSET pSet, const char *pszPath)
1137{
1138 audioTestSetInitInternal(pSet);
1139
1140 char szManifest[RTPATH_MAX];
1141 int rc = RTPathJoin(szManifest, sizeof(szManifest), pszPath, AUDIOTEST_MANIFEST_FILE_STR);
1142 AssertRCReturn(rc, rc);
1143
1144 RTVFSFILE hVfsFile;
1145 rc = RTVfsFileOpenNormal(szManifest, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE, &hVfsFile);
1146 if (RT_FAILURE(rc))
1147 return rc;
1148
1149 rc = RTIniFileCreateFromVfsFile(&pSet->f.hIniFile, hVfsFile, RTINIFILE_F_READONLY);
1150 RTVfsFileRelease(hVfsFile);
1151 AssertRCReturn(rc, rc);
1152
1153 rc = RTStrCopy(pSet->szPathAbs, sizeof(pSet->szPathAbs), pszPath);
1154 AssertRCReturn(rc, rc);
1155
1156 pSet->enmMode = AUDIOTESTSETMODE_VERIFY;
1157
1158 return rc;
1159}
1160
1161/**
1162 * Closes an opened audio test set.
1163 *
1164 * @returns VBox status code.
1165 * @param pSet Test set to close.
1166 */
1167int AudioTestSetClose(PAUDIOTESTSET pSet)
1168{
1169 AssertPtrReturn(pSet, VERR_INVALID_POINTER);
1170
1171 if (!audioTestManifestIsOpen(pSet))
1172 return VINF_SUCCESS;
1173
1174 int rc;
1175
1176 if (pSet->enmMode == AUDIOTESTSETMODE_TEST)
1177 {
1178 /* Update number of bound test objects. */
1179 PAUDIOTESTENTRY pTest;
1180 uint32_t cTests = 0;
1181 RTListForEach(&pSet->lstTest, pTest, AUDIOTESTENTRY, Node)
1182 {
1183 rc = RTFileSeek(pSet->f.hFile, pTest->offObjCount, RTFILE_SEEK_BEGIN, NULL);
1184 AssertRCReturn(rc, rc);
1185 rc = audioTestManifestWrite(pSet, "%04RU32", pTest->cObj);
1186 AssertRCReturn(rc, rc);
1187 cTests++; /* Sanity checking. */
1188 }
1189
1190 AssertMsgReturn(pSet->cTests == cTests, ("Test count and list don't match"), VERR_INTERNAL_ERROR);
1191
1192 /*
1193 * Update number of total objects.
1194 */
1195 rc = RTFileSeek(pSet->f.hFile, pSet->offObjCount, RTFILE_SEEK_BEGIN, NULL);
1196 AssertRCReturn(rc, rc);
1197 rc = audioTestManifestWrite(pSet, "%04RU32", pSet->cObj);
1198 AssertRCReturn(rc, rc);
1199
1200 /*
1201 * Update number of total tests.
1202 */
1203 rc = RTFileSeek(pSet->f.hFile, pSet->offTestCount, RTFILE_SEEK_BEGIN, NULL);
1204 AssertRCReturn(rc, rc);
1205 rc = audioTestManifestWrite(pSet, "%04RU32", pSet->cTests);
1206 AssertRCReturn(rc, rc);
1207
1208 /*
1209 * Serialize all registered test objects.
1210 */
1211 rc = RTFileSeek(pSet->f.hFile, 0, RTFILE_SEEK_END, NULL);
1212 AssertRCReturn(rc, rc);
1213
1214 PAUDIOTESTOBJINT pObj;
1215 uint32_t cObj = 0;
1216 RTListForEach(&pSet->lstObj, pObj, AUDIOTESTOBJINT, Node)
1217 {
1218 /* First, close the object.
1219 * This also does some needed finalization. */
1220 rc = AudioTestObjClose(pObj);
1221 AssertRCReturn(rc, rc);
1222 rc = audioTestManifestWrite(pSet, "\n");
1223 AssertRCReturn(rc, rc);
1224 char szUuid[AUDIOTEST_MAX_SEC_LEN];
1225 rc = RTUuidToStr(&pObj->Uuid, szUuid, sizeof(szUuid));
1226 AssertRCReturn(rc, rc);
1227 rc = audioTestManifestWriteSectionHdr(pSet, "obj_%s", szUuid);
1228 AssertRCReturn(rc, rc);
1229 rc = audioTestManifestWrite(pSet, "obj_type=%RU32\n", pObj->enmType);
1230 AssertRCReturn(rc, rc);
1231 rc = audioTestManifestWrite(pSet, "obj_name=%s\n", pObj->szName);
1232 AssertRCReturn(rc, rc);
1233
1234 switch (pObj->enmType)
1235 {
1236 case AUDIOTESTOBJTYPE_FILE:
1237 {
1238 rc = audioTestManifestWrite(pSet, "obj_size=%RU64\n", pObj->File.cbSize);
1239 AssertRCReturn(rc, rc);
1240 break;
1241 }
1242
1243 default:
1244 AssertFailed();
1245 break;
1246 }
1247
1248 /*
1249 * Write all meta data.
1250 */
1251 PAUDIOTESTOBJMETA pMeta;
1252 RTListForEach(&pObj->lstMeta, pMeta, AUDIOTESTOBJMETA, Node)
1253 {
1254 switch (pMeta->enmType)
1255 {
1256 case AUDIOTESTOBJMETADATATYPE_STRING:
1257 {
1258 rc = audioTestManifestWrite(pSet, (const char *)pMeta->pvMeta);
1259 AssertRCReturn(rc, rc);
1260 break;
1261 }
1262
1263 default:
1264 AssertFailed();
1265 break;
1266 }
1267 }
1268
1269 cObj++; /* Sanity checking. */
1270 }
1271
1272 AssertMsgReturn(pSet->cObj == cObj, ("Object count and list don't match"), VERR_INTERNAL_ERROR);
1273
1274 int rc2 = RTFileClose(pSet->f.hFile);
1275 if (RT_SUCCESS(rc2))
1276 pSet->f.hFile = NIL_RTFILE;
1277
1278 if (RT_SUCCESS(rc))
1279 rc = rc2;
1280 }
1281 else if (pSet->enmMode == AUDIOTESTSETMODE_VERIFY)
1282 {
1283 RTIniFileRelease(pSet->f.hIniFile);
1284 pSet->f.hIniFile = NIL_RTINIFILE;
1285
1286 rc = VINF_SUCCESS;
1287 }
1288 else
1289 AssertFailedStmt(rc = VERR_NOT_SUPPORTED);
1290
1291 return rc;
1292}
1293
1294/**
1295 * Physically wipes all related test set files off the disk.
1296 *
1297 * @returns VBox status code.
1298 * @param pSet Test set to wipe.
1299 */
1300int AudioTestSetWipe(PAUDIOTESTSET pSet)
1301{
1302 AssertPtrReturn(pSet, VERR_INVALID_POINTER);
1303
1304 int rc = VINF_SUCCESS;
1305 char szFilePath[RTPATH_MAX];
1306
1307 PAUDIOTESTOBJINT pObj;
1308 RTListForEach(&pSet->lstObj, pObj, AUDIOTESTOBJINT, Node)
1309 {
1310 int rc2 = audioTestObjClose(pObj);
1311 if (RT_SUCCESS(rc2))
1312 {
1313 rc2 = audioTestSetGetObjPath(pSet, szFilePath, sizeof(szFilePath), pObj->szName);
1314 if (RT_SUCCESS(rc2))
1315 rc2 = RTFileDelete(szFilePath);
1316 }
1317
1318 if (RT_SUCCESS(rc))
1319 rc = rc2;
1320 /* Keep going. */
1321 }
1322
1323 if (RT_SUCCESS(rc))
1324 {
1325 rc = RTPathJoin(szFilePath, sizeof(szFilePath), pSet->szPathAbs, AUDIOTEST_MANIFEST_FILE_STR);
1326 if (RT_SUCCESS(rc))
1327 rc = RTFileDelete(szFilePath);
1328 }
1329
1330 /* Remove the (hopefully now empty) directory. Otherwise let this fail. */
1331 if (RT_SUCCESS(rc))
1332 rc = RTDirRemove(pSet->szPathAbs);
1333
1334 return rc;
1335}
1336
1337/**
1338 * Creates and registers a new audio test object to the current running test.
1339 *
1340 * @returns VBox status code.
1341 * @param pSet Test set to create and register new object for.
1342 * @param pszName Name of new object to create.
1343 * @param pObj Where to return the pointer to the newly created object on success.
1344 */
1345int AudioTestSetObjCreateAndRegister(PAUDIOTESTSET pSet, const char *pszName, PAUDIOTESTOBJ pObj)
1346{
1347 AssertReturn(pSet->cTestsRunning == 1, VERR_WRONG_ORDER); /* No test nesting allowed. */
1348
1349 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
1350
1351 PAUDIOTESTOBJINT pThis = (PAUDIOTESTOBJINT)RTMemAlloc(sizeof(AUDIOTESTOBJINT));
1352 AssertPtrReturn(pThis, VERR_NO_MEMORY);
1353
1354 audioTestObjInit(pThis);
1355
1356 if (RTStrPrintf2(pThis->szName, sizeof(pThis->szName), "%04RU32-%s", pSet->cObj, pszName) <= 0)
1357 AssertFailedReturn(VERR_BUFFER_OVERFLOW);
1358
1359 /** @todo Generalize this function more once we have more object types. */
1360
1361 char szObjPathAbs[RTPATH_MAX];
1362 int rc = audioTestSetGetObjPath(pSet, szObjPathAbs, sizeof(szObjPathAbs), pThis->szName);
1363 if (RT_SUCCESS(rc))
1364 {
1365 rc = RTFileOpen(&pThis->File.hFile, szObjPathAbs, RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
1366 if (RT_SUCCESS(rc))
1367 {
1368 pThis->enmType = AUDIOTESTOBJTYPE_FILE;
1369 pThis->cRefs = 1; /* Currently only 1:1 mapping. */
1370
1371 RTListAppend(&pSet->lstObj, &pThis->Node);
1372 pSet->cObj++;
1373
1374 /* Generate + set an UUID for the object and assign it to the current test. */
1375 rc = RTUuidCreate(&pThis->Uuid);
1376 AssertRCReturn(rc, rc);
1377 char szUuid[AUDIOTEST_MAX_OBJ_LEN];
1378 rc = RTUuidToStr(&pThis->Uuid, szUuid, sizeof(szUuid));
1379 AssertRCReturn(rc, rc);
1380
1381 rc = audioTestManifestWrite(pSet, "obj%RU32_uuid=%s\n", pSet->pTestCur->cObj, szUuid);
1382 AssertRCReturn(rc, rc);
1383
1384 AssertPtr(pSet->pTestCur);
1385 pSet->pTestCur->cObj++;
1386
1387 *pObj = pThis;
1388 }
1389 }
1390
1391 if (RT_FAILURE(rc))
1392 RTMemFree(pThis);
1393
1394 return rc;
1395}
1396
1397/**
1398 * Writes to a created audio test object.
1399 *
1400 * @returns VBox status code.
1401 * @param hObj Handle to the audio test object to write to.
1402 * @param pvBuf Pointer to data to write.
1403 * @param cbBuf Size (in bytes) of \a pvBuf to write.
1404 */
1405int AudioTestObjWrite(AUDIOTESTOBJ hObj, const void *pvBuf, size_t cbBuf)
1406{
1407 AUDIOTESTOBJINT *pThis = hObj;
1408
1409 /** @todo Generalize this function more once we have more object types. */
1410 AssertReturn(pThis->enmType == AUDIOTESTOBJTYPE_FILE, VERR_INVALID_PARAMETER);
1411
1412 return RTFileWrite(pThis->File.hFile, pvBuf, cbBuf, NULL);
1413}
1414
1415/**
1416 * Adds meta data to a test object as a string, va_list version.
1417 *
1418 * @returns VBox status code.
1419 * @param pObj Test object to add meta data for.
1420 * @param pszFormat Format string to add.
1421 * @param va Variable arguments list to use for the format string.
1422 */
1423static int audioTestObjAddMetadataStrV(PAUDIOTESTOBJINT pObj, const char *pszFormat, va_list va)
1424{
1425 PAUDIOTESTOBJMETA pMeta = (PAUDIOTESTOBJMETA)RTMemAlloc(sizeof(AUDIOTESTOBJMETA));
1426 AssertPtrReturn(pMeta, VERR_NO_MEMORY);
1427
1428 pMeta->pvMeta = RTStrAPrintf2V(pszFormat, va);
1429 AssertPtrReturn(pMeta->pvMeta, VERR_BUFFER_OVERFLOW);
1430 pMeta->cbMeta = RTStrNLen((const char *)pMeta->pvMeta, RTSTR_MAX);
1431
1432 pMeta->enmType = AUDIOTESTOBJMETADATATYPE_STRING;
1433
1434 RTListAppend(&pObj->lstMeta, &pMeta->Node);
1435
1436 return VINF_SUCCESS;
1437}
1438
1439/**
1440 * Adds meta data to a test object as a string.
1441 *
1442 * @returns VBox status code.
1443 * @param hObj Handle to the test object to add meta data for.
1444 * @param pszFormat Format string to add.
1445 * @param ... Variable arguments for the format string.
1446 */
1447int AudioTestObjAddMetadataStr(AUDIOTESTOBJ hObj, const char *pszFormat, ...)
1448{
1449 AUDIOTESTOBJINT *pThis = hObj;
1450
1451 va_list va;
1452
1453 va_start(va, pszFormat);
1454 int rc = audioTestObjAddMetadataStrV(pThis, pszFormat, va);
1455 va_end(va);
1456
1457 return rc;
1458}
1459
1460/**
1461 * Closes an opened audio test object.
1462 *
1463 * @returns VBox status code.
1464 * @param hObj Handle to the audio test object to close.
1465 */
1466int AudioTestObjClose(AUDIOTESTOBJ hObj)
1467{
1468 AUDIOTESTOBJINT *pThis = hObj;
1469
1470 if (!pThis)
1471 return VINF_SUCCESS;
1472
1473 audioTestObjFinalize(pThis);
1474
1475 return audioTestObjClose(pThis);
1476}
1477
1478/**
1479 * Begins a new test of a test set.
1480 *
1481 * @returns VBox status code.
1482 * @param pSet Test set to begin new test for.
1483 * @param pszDesc Test description.
1484 * @param pParms Test parameters to use.
1485 * @param ppEntry Where to return the new test
1486 */
1487int AudioTestSetTestBegin(PAUDIOTESTSET pSet, const char *pszDesc, PAUDIOTESTPARMS pParms, PAUDIOTESTENTRY *ppEntry)
1488{
1489 AssertReturn(pSet->cTestsRunning == 0, VERR_WRONG_ORDER); /* No test nesting allowed. */
1490
1491 PAUDIOTESTENTRY pEntry = (PAUDIOTESTENTRY)RTMemAllocZ(sizeof(AUDIOTESTENTRY));
1492 AssertPtrReturn(pEntry, VERR_NO_MEMORY);
1493
1494 int rc = RTStrCopy(pEntry->szDesc, sizeof(pEntry->szDesc), pszDesc);
1495 AssertRCReturn(rc, rc);
1496
1497 memcpy(&pEntry->Parms, pParms, sizeof(AUDIOTESTPARMS));
1498
1499 pEntry->pParent = pSet;
1500 pEntry->rc = VERR_IPE_UNINITIALIZED_STATUS;
1501
1502 rc = audioTestManifestWrite(pSet, "\n");
1503 AssertRCReturn(rc, rc);
1504
1505 rc = audioTestManifestWriteSectionHdr(pSet, "test_%04RU32", pSet->cTests);
1506 AssertRCReturn(rc, rc);
1507 rc = audioTestManifestWrite(pSet, "test_desc=%s\n", pszDesc);
1508 AssertRCReturn(rc, rc);
1509 rc = audioTestManifestWrite(pSet, "test_type=%RU32\n", pParms->enmType);
1510 AssertRCReturn(rc, rc);
1511 rc = audioTestManifestWrite(pSet, "test_delay_ms=%RU32\n", pParms->msDelay);
1512 AssertRCReturn(rc, rc);
1513 rc = audioTestManifestWrite(pSet, "audio_direction=%s\n", PDMAudioDirGetName(pParms->enmDir));
1514 AssertRCReturn(rc, rc);
1515
1516 rc = audioTestManifestWrite(pSet, "obj_count=");
1517 AssertRCReturn(rc, rc);
1518 pEntry->offObjCount = audioTestManifestGetOffsetAbs(pSet);
1519 rc = audioTestManifestWrite(pSet, "0000\n"); /* A bit messy, but does the trick for now. */
1520 AssertRCReturn(rc, rc);
1521
1522 switch (pParms->enmType)
1523 {
1524 case AUDIOTESTTYPE_TESTTONE_PLAY:
1525 RT_FALL_THROUGH();
1526 case AUDIOTESTTYPE_TESTTONE_RECORD:
1527 {
1528 rc = audioTestManifestWrite(pSet, "tone_freq_hz=%RU16\n", (uint16_t)pParms->TestTone.dbFreqHz);
1529 AssertRCReturn(rc, rc);
1530 rc = audioTestManifestWrite(pSet, "tone_prequel_ms=%RU32\n", pParms->TestTone.msPrequel);
1531 AssertRCReturn(rc, rc);
1532 rc = audioTestManifestWrite(pSet, "tone_duration_ms=%RU32\n", pParms->TestTone.msDuration);
1533 AssertRCReturn(rc, rc);
1534 rc = audioTestManifestWrite(pSet, "tone_sequel_ms=%RU32\n", pParms->TestTone.msSequel);
1535 AssertRCReturn(rc, rc);
1536 rc = audioTestManifestWrite(pSet, "tone_volume_percent=%RU32\n", pParms->TestTone.uVolumePercent);
1537 AssertRCReturn(rc, rc);
1538 rc = audioTestManifestWrite(pSet, "tone_pcm_hz=%RU32\n", PDMAudioPropsHz(&pParms->TestTone.Props));
1539 AssertRCReturn(rc, rc);
1540 rc = audioTestManifestWrite(pSet, "tone_pcm_channels=%RU8\n", PDMAudioPropsChannels(&pParms->TestTone.Props));
1541 AssertRCReturn(rc, rc);
1542 rc = audioTestManifestWrite(pSet, "tone_pcm_bits=%RU8\n", PDMAudioPropsSampleBits(&pParms->TestTone.Props));
1543 AssertRCReturn(rc, rc);
1544 rc = audioTestManifestWrite(pSet, "tone_pcm_is_signed=%RTbool\n", PDMAudioPropsIsSigned(&pParms->TestTone.Props));
1545 AssertRCReturn(rc, rc);
1546 break;
1547 }
1548
1549 default:
1550 AssertFailed();
1551 break;
1552 }
1553
1554 RTListAppend(&pSet->lstTest, &pEntry->Node);
1555
1556 pSet->cTests++;
1557 pSet->cTestsRunning++;
1558 pSet->pTestCur = pEntry;
1559
1560 *ppEntry = pEntry;
1561
1562 return rc;
1563}
1564
1565/**
1566 * Marks a running test as failed.
1567 *
1568 * @returns VBox status code.
1569 * @param pEntry Test to mark.
1570 * @param rc Error code.
1571 * @param pszErr Error description.
1572 */
1573int AudioTestSetTestFailed(PAUDIOTESTENTRY pEntry, int rc, const char *pszErr)
1574{
1575 AssertReturn(pEntry->pParent->cTestsRunning == 1, VERR_WRONG_ORDER); /* No test nesting allowed. */
1576 AssertReturn(pEntry->rc == VERR_IPE_UNINITIALIZED_STATUS, VERR_WRONG_ORDER);
1577
1578 pEntry->rc = rc;
1579
1580 int rc2 = audioTestManifestWrite(pEntry->pParent, "error_rc=%RI32\n", rc);
1581 AssertRCReturn(rc2, rc2);
1582 rc2 = audioTestManifestWrite(pEntry->pParent, "error_desc=%s\n", pszErr);
1583 AssertRCReturn(rc2, rc2);
1584
1585 pEntry->pParent->cTestsRunning--;
1586 pEntry->pParent->pTestCur = NULL;
1587
1588 return rc2;
1589}
1590
1591/**
1592 * Marks a running test as successfully done.
1593 *
1594 * @returns VBox status code.
1595 * @param pEntry Test to mark.
1596 */
1597int AudioTestSetTestDone(PAUDIOTESTENTRY pEntry)
1598{
1599 AssertReturn(pEntry->pParent->cTestsRunning == 1, VERR_WRONG_ORDER); /* No test nesting allowed. */
1600 AssertReturn(pEntry->rc == VERR_IPE_UNINITIALIZED_STATUS, VERR_WRONG_ORDER);
1601
1602 pEntry->rc = VINF_SUCCESS;
1603
1604 int rc2 = audioTestManifestWrite(pEntry->pParent, "error_rc=%RI32\n", VINF_SUCCESS);
1605 AssertRCReturn(rc2, rc2);
1606
1607 pEntry->pParent->cTestsRunning--;
1608 pEntry->pParent->pTestCur = NULL;
1609
1610 return rc2;
1611}
1612
1613/**
1614 * Returns whether a test is still running or not.
1615 *
1616 * @returns \c true if test is still running, or \c false if not.
1617 * @param pEntry Test to get running status for.
1618 */
1619bool AudioTestSetTestIsRunning(PAUDIOTESTENTRY pEntry)
1620{
1621 return (pEntry->rc == VERR_IPE_UNINITIALIZED_STATUS);
1622}
1623
1624/**
1625 * Packs a closed audio test so that it's ready for transmission.
1626 *
1627 * @returns VBox status code.
1628 * @param pSet Test set to pack.
1629 * @param pszOutDir Directory where to store the packed test set.
1630 * @param pszFileName Where to return the final name of the packed test set. Optional and can be NULL.
1631 * @param cbFileName Size (in bytes) of \a pszFileName.
1632 */
1633int AudioTestSetPack(PAUDIOTESTSET pSet, const char *pszOutDir, char *pszFileName, size_t cbFileName)
1634{
1635 AssertPtrReturn(pSet, VERR_INVALID_POINTER);
1636 AssertReturn(!pszFileName || cbFileName, VERR_INVALID_PARAMETER);
1637 AssertReturn(!audioTestManifestIsOpen(pSet), VERR_WRONG_ORDER);
1638
1639 /* No more validation (no / still running tests) here -- just pack all stuff we got so far
1640 * and let the verification routine deal with it later. */
1641
1642 /** @todo Check and deny if \a pszOutDir is part of the set's path. */
1643
1644 int rc = RTDirCreateFullPath(pszOutDir, 0755);
1645 if (RT_FAILURE(rc))
1646 return rc;
1647
1648 char szOutName[RT_ELEMENTS(AUDIOTEST_PATH_PREFIX_STR) + AUDIOTEST_TAG_MAX + 16];
1649 if (RTStrPrintf2(szOutName, sizeof(szOutName), "%s-%s%s",
1650 AUDIOTEST_PATH_PREFIX_STR, pSet->szTag, AUDIOTEST_ARCHIVE_SUFF_STR) <= 0)
1651 AssertFailedReturn(VERR_BUFFER_OVERFLOW);
1652
1653 char szOutPath[RTPATH_MAX];
1654 rc = RTPathJoin(szOutPath, sizeof(szOutPath), pszOutDir, szOutName);
1655 AssertRCReturn(rc, rc);
1656
1657 const char *apszArgs[10];
1658 unsigned cArgs = 0;
1659
1660 apszArgs[cArgs++] = "vkat";
1661 apszArgs[cArgs++] = "--create";
1662 apszArgs[cArgs++] = "--gzip";
1663 apszArgs[cArgs++] = "--directory";
1664 apszArgs[cArgs++] = pSet->szPathAbs;
1665 apszArgs[cArgs++] = "--file";
1666 apszArgs[cArgs++] = szOutPath;
1667 apszArgs[cArgs++] = ".";
1668
1669 RTEXITCODE rcExit = RTZipTarCmd(cArgs, (char **)apszArgs);
1670 if (rcExit != RTEXITCODE_SUCCESS)
1671 rc = VERR_GENERAL_FAILURE; /** @todo Fudge! */
1672
1673 if (RT_SUCCESS(rc))
1674 {
1675 if (pszFileName)
1676 rc = RTStrCopy(pszFileName, cbFileName, szOutPath);
1677 }
1678
1679 return rc;
1680}
1681
1682/**
1683 * Returns whether a test set archive is packed (as .tar.gz by default) or
1684 * a plain directory.
1685 *
1686 * @returns \c true if packed (as .tar.gz), or \c false if not (directory).
1687 * @param pszPath Path to return packed staus for.
1688 */
1689bool AudioTestSetIsPacked(const char *pszPath)
1690{
1691 /** @todo Improve this, good enough for now. */
1692 return (RTStrIStr(pszPath, AUDIOTEST_ARCHIVE_SUFF_STR) != NULL);
1693}
1694
1695/**
1696 * Returns whether a test set has running (active) tests or not.
1697 *
1698 * @returns \c true if it has running tests, or \c false if not.
1699 * @param pSet Test set to return status for.
1700 */
1701bool AudioTestSetIsRunning(PAUDIOTESTSET pSet)
1702{
1703 return (pSet->cTestsRunning > 0);
1704}
1705
1706/**
1707 * Unpacks a formerly packed audio test set.
1708 *
1709 * @returns VBox status code.
1710 * @param pszFile Test set file to unpack. Must contain the absolute path.
1711 * @param pszOutDir Directory where to unpack the test set into.
1712 * If the directory does not exist it will be created.
1713 */
1714int AudioTestSetUnpack(const char *pszFile, const char *pszOutDir)
1715{
1716 AssertReturn(pszFile && pszOutDir, VERR_INVALID_PARAMETER);
1717
1718 int rc = VINF_SUCCESS;
1719
1720 if (!RTDirExists(pszOutDir))
1721 {
1722 rc = RTDirCreateFullPath(pszOutDir, 0755);
1723 if (RT_FAILURE(rc))
1724 return rc;
1725 }
1726
1727 const char *apszArgs[8];
1728 unsigned cArgs = 0;
1729
1730 apszArgs[cArgs++] = "vkat";
1731 apszArgs[cArgs++] = "--extract";
1732 apszArgs[cArgs++] = "--gunzip";
1733 apszArgs[cArgs++] = "--directory";
1734 apszArgs[cArgs++] = pszOutDir;
1735 apszArgs[cArgs++] = "--file";
1736 apszArgs[cArgs++] = pszFile;
1737
1738 RTEXITCODE rcExit = RTZipTarCmd(cArgs, (char **)apszArgs);
1739 if (rcExit != RTEXITCODE_SUCCESS)
1740 rc = VERR_GENERAL_FAILURE; /** @todo Fudge! */
1741
1742 return rc;
1743}
1744
1745/**
1746 * Retrieves an object handle of a specific test set section.
1747 *
1748 * @returns VBox status code.
1749 * @param pSet Test set the section contains.
1750 * @param pszSec Name of section to retrieve object handle for.
1751 * @param phSec Where to store the object handle on success.
1752 */
1753static int audioTestSetGetSection(PAUDIOTESTSET pSet, const char *pszSec, PAUDIOTESTOBJINT phSec)
1754{
1755 int rc = RTStrCopy(phSec->szSec, sizeof(phSec->szSec), pszSec);
1756 if (RT_FAILURE(rc))
1757 return rc;
1758
1759 phSec->pSet = pSet;
1760
1761 /** @todo Check for section existence. */
1762 RT_NOREF(pSet);
1763
1764 return VINF_SUCCESS;
1765}
1766
1767/**
1768 * Retrieves an object handle of a specific test.
1769 *
1770 * @returns VBox status code.
1771 * @param pSet Test set the test contains.
1772 * @param idxTst Index of test to retrieve the object handle for.
1773 * @param phTst Where to store the object handle on success.
1774 */
1775static int audioTestSetGetTest(PAUDIOTESTSET pSet, uint32_t idxTst, PAUDIOTESTOBJINT phTst)
1776{
1777 char szSec[AUDIOTEST_MAX_SEC_LEN];
1778 if (RTStrPrintf2(szSec, sizeof(szSec), "test_%04RU32", idxTst) <= 0)
1779 return VERR_BUFFER_OVERFLOW;
1780
1781 return audioTestSetGetSection(pSet, szSec, phTst);
1782}
1783
1784/**
1785 * Initializes a test object.
1786 *
1787 * @param pObj Object to initialize.
1788 */
1789static void audioTestObjInit(PAUDIOTESTOBJINT pObj)
1790{
1791 RT_BZERO(pObj, sizeof(AUDIOTESTOBJINT));
1792
1793 pObj->cRefs = 1;
1794
1795 RTListInit(&pObj->lstMeta);
1796}
1797
1798/**
1799 * Retrieves a child object of a specific parent object.
1800 *
1801 * @returns VBox status code.
1802 * @param pParent Parent object the child object contains.
1803 * @param idxObj Index of object to retrieve the object handle for.
1804 * @param pObj Where to store the object handle on success.
1805 */
1806static int audioTestObjGetChild(PAUDIOTESTOBJINT pParent, uint32_t idxObj, PAUDIOTESTOBJINT pObj)
1807{
1808 char szObj[AUDIOTEST_MAX_SEC_LEN];
1809 if (RTStrPrintf2(szObj, sizeof(szObj), "obj%RU32_uuid", idxObj) <= 0)
1810 AssertFailedReturn(VERR_BUFFER_OVERFLOW);
1811
1812 char szUuid[AUDIOTEST_MAX_SEC_LEN];
1813 int rc = audioTestObjGetStr(pParent, szObj, szUuid, sizeof(szUuid));
1814 if (RT_SUCCESS(rc))
1815 {
1816 audioTestObjInit(pObj);
1817
1818 AssertReturn(RTStrPrintf2(pObj->szSec, sizeof(pObj->szSec), "obj_%s", szUuid) > 0, VERR_BUFFER_OVERFLOW);
1819
1820 /** @todo Check test section existence. */
1821
1822 pObj->pSet = pParent->pSet;
1823 }
1824
1825 return rc;
1826}
1827
1828/**
1829 * Verifies a value of a test verification job.
1830 *
1831 * @returns VBox status code.
1832 * @returns Error if the verification failed and test verification job has fKeepGoing not set.
1833 * @param pVerJob Verification job to verify value for.
1834 * @param pObjA Object handle A to verify value for.
1835 * @param pObjB Object handle B to verify value for.
1836 * @param pszKey Key to verify.
1837 * @param pszVal Value to verify.
1838 * @param pszErrFmt Error format string in case the verification failed.
1839 * @param ... Variable aruments for error format string.
1840 */
1841static int audioTestVerifyValue(PAUDIOTESTVERIFYJOB pVerJob,
1842 PAUDIOTESTOBJINT pObjA, PAUDIOTESTOBJINT pObjB, const char *pszKey, const char *pszVal, const char *pszErrFmt, ...)
1843{
1844 va_list va;
1845 va_start(va, pszErrFmt);
1846
1847 char szValA[_1K];
1848 int rc = audioTestObjGetStr(pObjA, pszKey, szValA, sizeof(szValA));
1849 if (RT_SUCCESS(rc))
1850 {
1851 char szValB[_1K];
1852 rc = audioTestObjGetStr(pObjB, pszKey, szValB, sizeof(szValB));
1853 if (RT_SUCCESS(rc))
1854 {
1855 if (RTStrCmp(szValA, szValB))
1856 {
1857 int rc2 = audioTestErrorDescAddError(pVerJob->pErr, pVerJob->idxTest,
1858 "Values are not equal ('%s' vs. '%s')", szValA, szValB);
1859 AssertRC(rc2);
1860 rc = VERR_WRONG_TYPE; /** @todo Fudge! */
1861 }
1862
1863 if (pszVal)
1864 {
1865 if (RTStrCmp(szValA, pszVal))
1866 {
1867 int rc2 = audioTestErrorDescAddError(pVerJob->pErr, pVerJob->idxTest,
1868 "Values don't match expected value (got '%s', expected '%s')", szValA, pszVal);
1869 AssertRC(rc2);
1870 rc = VERR_WRONG_TYPE; /** @todo Fudge! */
1871 }
1872 }
1873 }
1874 }
1875
1876 if (RT_FAILURE(rc))
1877 {
1878 int rc2 = audioTestErrorDescAddV(pVerJob->pErr, pVerJob->idxTest, rc, pszErrFmt, va);
1879 AssertRC(rc2);
1880 }
1881
1882 va_end(va);
1883
1884 return pVerJob->Opts.fKeepGoing ? VINF_SUCCESS : rc;
1885}
1886
1887/**
1888 * Opens a test object which is a regular file.
1889 *
1890 * @returns VBox status code.
1891 * @param pObj Test object to open.
1892 * @param pszFile Absolute file path of file to open.
1893 */
1894static int audioTestObjOpenFile(PAUDIOTESTOBJINT pObj, const char *pszFile)
1895{
1896 int rc = RTFileOpen(&pObj->File.hFile, pszFile, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
1897 if (RT_SUCCESS(rc))
1898 {
1899 int rc2 = RTStrCopy(pObj->szName, sizeof(pObj->szName), pszFile);
1900 AssertRC(rc2);
1901
1902 pObj->enmType = AUDIOTESTOBJTYPE_FILE;
1903 }
1904
1905 return rc;
1906}
1907
1908/**
1909 * Opens an existing audio test object.
1910 *
1911 * @returns VBox status code.
1912 * @param pObj Object to open.
1913 */
1914static int audioTestObjOpen(PAUDIOTESTOBJINT pObj)
1915{
1916 AssertReturn(pObj->enmType == AUDIOTESTOBJTYPE_UNKNOWN, VERR_WRONG_ORDER);
1917
1918 char szFileName[AUDIOTEST_MAX_SEC_LEN];
1919 int rc = audioTestObjGetStr(pObj, "obj_name", szFileName, sizeof(szFileName));
1920 if (RT_SUCCESS(rc))
1921 {
1922 char szFilePath[RTPATH_MAX];
1923 rc = RTPathJoin(szFilePath, sizeof(szFilePath), pObj->pSet->szPathAbs, szFileName);
1924 if (RT_SUCCESS(rc))
1925 {
1926 /** @todo Check "obj_type". */
1927 rc = audioTestObjOpenFile(pObj, szFilePath);
1928 }
1929 }
1930 return rc;
1931}
1932
1933/**
1934 * Closes an audio test set object.
1935 *
1936 * @returns VBox status code.
1937 * @param pObj Object to close.
1938 */
1939static int audioTestObjClose(PAUDIOTESTOBJINT pObj)
1940{
1941 if (!audioTestObjIsOpen(pObj))
1942 return VINF_SUCCESS;
1943
1944 int rc;
1945
1946 /** @todo Generalize this function more once we have more object types. */
1947
1948 if (RTFileIsValid(pObj->File.hFile))
1949 {
1950 rc = RTFileClose(pObj->File.hFile);
1951 if (RT_SUCCESS(rc))
1952 pObj->File.hFile = NIL_RTFILE;
1953 }
1954 else
1955 rc = VINF_SUCCESS;
1956
1957 return rc;
1958}
1959
1960/**
1961 * Returns whether a test set object is in opened state or not.
1962 *
1963 * @returns \c true if open, or \c false if not.
1964 * @param pObj Object to return status for.
1965 */
1966static bool audioTestObjIsOpen(PAUDIOTESTOBJINT pObj)
1967{
1968 return pObj->enmType != AUDIOTESTOBJTYPE_UNKNOWN;
1969}
1970
1971/**
1972 * Finalizes an audio test set object.
1973 *
1974 * @param pObj Test object to finalize.
1975 */
1976static void audioTestObjFinalize(PAUDIOTESTOBJINT pObj)
1977{
1978 /** @todo Generalize this function more once we have more object types. */
1979 AssertReturnVoid(pObj->enmType == AUDIOTESTOBJTYPE_FILE);
1980
1981 if (RTFileIsValid(pObj->File.hFile))
1982 pObj->File.cbSize = RTFileTell(pObj->File.hFile);
1983}
1984
1985/**
1986 * Retrieves tone PCM properties of an object.
1987 *
1988 * @returns VBox status code.
1989 * @param pObj Object to retrieve PCM properties for.
1990 * @param pProps Where to store the PCM properties on success.
1991 */
1992static int audioTestObjGetTonePcmProps(PAUDIOTESTOBJINT pObj, PPDMAUDIOPCMPROPS pProps)
1993{
1994 int rc;
1995 uint32_t uHz;
1996 rc = audioTestObjGetUInt32(pObj, "tone_pcm_hz", &uHz);
1997 AssertRCReturn(rc, rc);
1998 uint8_t cBits;
1999 rc = audioTestObjGetUInt8(pObj, "tone_pcm_bits", &cBits);
2000 AssertRCReturn(rc, rc);
2001 uint8_t cChan;
2002 rc = audioTestObjGetUInt8(pObj, "tone_pcm_channels", &cChan);
2003 AssertRCReturn(rc, rc);
2004 bool fSigned;
2005 rc = audioTestObjGetBool(pObj, "tone_pcm_is_signed", &fSigned);
2006 AssertRCReturn(rc, rc);
2007
2008 PDMAudioPropsInit(pProps, (cBits / 8), fSigned, cChan, uHz);
2009
2010 return VINF_SUCCESS;
2011}
2012
2013/**
2014 * Normalizes PCM audio data.
2015 * Only supports 16 bit stereo PCM data for now.
2016 *
2017 * @returns VBox status code.
2018 * @param hFileSrc Source file handle of audio data to normalize.
2019 * @param pProps PCM properties to use for normalization.
2020 * @param cbSize Size (in bytes) of audio data to normalize.
2021 * @param dbNormalizePercent Normalization (percent) to achieve.
2022 * @param hFileDst Destiation file handle (must be open) where to write the normalized audio data to.
2023 * @param pdbRatio Where to store the normalization ratio used on success. Optional and can be NULL.
2024 * A ration of exactly 1 means no normalization.
2025 *
2026 * @note The source file handle must point at the beginning of the PCM audio data to normalize.
2027 */
2028static int audioTestFileNormalizePCM(RTFILE hFileSrc, PCPDMAUDIOPCMPROPS pProps, uint64_t cbSize,
2029 double dbNormalizePercent, RTFILE hFileDst, double *pdbRatio)
2030{
2031 if ( !pProps->fSigned
2032 || pProps->cbSampleX != 2) /* Fend-off non-supported stuff first. */
2033 return VERR_NOT_SUPPORTED;
2034
2035 int rc = VINF_SUCCESS; /* Shut up MSVC. */
2036
2037 if (!cbSize)
2038 {
2039 rc = RTFileQuerySize(hFileSrc, &cbSize);
2040 AssertRCReturn(rc, rc);
2041 }
2042 else
2043 AssertReturn(PDMAudioPropsIsSizeAligned(pProps, (uint32_t)cbSize), VERR_INVALID_PARAMETER);
2044
2045 uint64_t offStart = RTFileTell(hFileSrc);
2046 size_t cbToRead = cbSize;
2047
2048 /* Find minimum and maximum peaks. */
2049 int16_t iMin = 0;
2050 int16_t iMax = 0;
2051 double dbRatio = 0.0;
2052
2053 uint8_t auBuf[_64K];
2054 while (cbToRead)
2055 {
2056 size_t const cbChunk = RT_MIN(cbToRead, sizeof(auBuf));
2057 size_t cbRead = 0;
2058 rc = RTFileRead(hFileSrc, auBuf, cbChunk, &cbRead);
2059 if (rc == VERR_EOF)
2060 break;
2061 AssertRCBreak(rc);
2062
2063 AssertBreak(PDMAudioPropsIsSizeAligned(pProps, (uint32_t)cbRead));
2064
2065 switch (pProps->cbSampleX)
2066 {
2067 case 2: /* 16 bit signed */
2068 {
2069 int16_t *pi16Src = (int16_t *)auBuf;
2070 for (size_t i = 0; i < cbRead / pProps->cbSampleX; i += pProps->cbSampleX)
2071 {
2072 if (*pi16Src < iMin)
2073 iMin = *pi16Src;
2074 if (*pi16Src > iMax)
2075 iMax = *pi16Src;
2076 pi16Src++;
2077 }
2078 break;
2079 }
2080
2081 default:
2082 AssertMsgFailedBreakStmt(("Invalid bytes per sample: %RU8\n", pProps->cbSampleX), rc = VERR_NOT_SUPPORTED);
2083 }
2084
2085 Assert(cbToRead >= cbRead);
2086 cbToRead -= cbRead;
2087 }
2088
2089 if (RT_FAILURE(rc))
2090 return rc;
2091
2092 /* Now rewind and do the actual gain / attenuation. */
2093 rc = RTFileSeek(hFileSrc, offStart, RTFILE_SEEK_BEGIN, NULL /* poffActual */);
2094 AssertRCReturn(rc, rc);
2095 cbToRead = cbSize;
2096
2097 switch (pProps->cbSampleX)
2098 {
2099 case 2: /* 16 bit signed */
2100 {
2101 if (iMin == INT16_MIN)
2102 iMin = INT16_MIN + 1;
2103 if ((-iMin) > iMax)
2104 iMax = -iMin;
2105
2106 dbRatio = iMax == 0 ? 1.0 : ((double)INT16_MAX * dbNormalizePercent) / ((double)iMax * 100.0);
2107
2108 while (cbToRead)
2109 {
2110 size_t const cbChunk = RT_MIN(cbToRead, sizeof(auBuf));
2111 size_t cbRead;
2112 rc = RTFileRead(hFileSrc, auBuf, cbChunk, &cbRead);
2113 if (rc == VERR_EOF)
2114 break;
2115 AssertRCBreak(rc);
2116
2117 int16_t *pi16Src = (int16_t *)auBuf;
2118 for (size_t i = 0; i < cbRead / pProps->cbSampleX; i += pProps->cbSampleX)
2119 {
2120 /** @todo Optimize this -- use a lookup table for sample indices? */
2121 if ((*pi16Src * dbRatio) > INT16_MAX)
2122 *pi16Src = INT16_MAX;
2123 else if ((*pi16Src * dbRatio) < INT16_MIN)
2124 *pi16Src = INT16_MIN;
2125 else
2126 *pi16Src = (int16_t)(*pi16Src * dbRatio);
2127 pi16Src++;
2128 }
2129
2130 size_t cbWritten;
2131 rc = RTFileWrite(hFileDst, auBuf, cbChunk, &cbWritten);
2132 AssertRCBreak(rc);
2133 Assert(cbWritten == cbChunk);
2134
2135 Assert(cbToRead >= cbRead);
2136 cbToRead -= cbRead;
2137 }
2138 break;
2139 }
2140
2141 default:
2142 AssertMsgFailedBreakStmt(("Invalid bytes per sample: %RU8\n", pProps->cbSampleX), rc = VERR_NOT_SUPPORTED);
2143 }
2144
2145 if (RT_SUCCESS(rc))
2146 {
2147 if (pdbRatio)
2148 *pdbRatio = dbRatio;
2149 }
2150
2151 return rc;
2152}
2153
2154/**
2155 * Normalizes a test set audio object's audio data, extended version.
2156 *
2157 * @returns VBox status code. On success the test set object will point to the (temporary) normalized file data.
2158 * @param pVerJob Verification job that contains \a pObj.
2159 * @param pObj Test set object to normalize.
2160 * @param pProps PCM properties to use for normalization.
2161 * @param cbSize Size (in bytes) of audio data to normalize.
2162 * @param dbNormalizePercent Normalization to achieve (in percent).
2163 *
2164 * @note The test set's file pointer must point to beginning of PCM data to normalize.
2165 */
2166static int audioTestObjFileNormalizeEx(PAUDIOTESTVERIFYJOB pVerJob,
2167 PAUDIOTESTOBJINT pObj, PPDMAUDIOPCMPROPS pProps, uint64_t cbSize, double dbNormalizePercent)
2168{
2169 /* Store normalized file into a temporary file. */
2170 char szFileDst[RTPATH_MAX];
2171 int rc = RTPathTemp(szFileDst, sizeof(szFileDst));
2172 AssertRCReturn(rc, rc);
2173
2174 rc = RTPathAppend(szFileDst, sizeof(szFileDst), "VBoxAudioTest-normalized-XXX.pcm");
2175 AssertRCReturn(rc, rc);
2176
2177 rc = RTFileCreateTemp(szFileDst, 0600);
2178 AssertRCReturn(rc, rc);
2179
2180 RTFILE hFileDst;
2181 rc = RTFileOpen(&hFileDst, szFileDst, RTFILE_O_OPEN | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
2182 AssertRCReturn(rc, rc);
2183
2184 double dbRatio = 0.0;
2185 rc = audioTestFileNormalizePCM(pObj->File.hFile, pProps, cbSize, dbNormalizePercent, hFileDst, &dbRatio);
2186 if (RT_SUCCESS(rc))
2187 {
2188 int rc2 = audioTestErrorDescAddInfo(pVerJob->pErr, pVerJob->idxTest, "Normalized '%s' -> '%s' (ratio is %u.%02u%%)\n",
2189 pObj->szName, szFileDst, (unsigned)dbRatio, (unsigned)(dbRatio * 100) % 100);
2190 AssertRC(rc2);
2191 }
2192
2193 int rc2 = RTFileClose(hFileDst);
2194 if (RT_SUCCESS(rc))
2195 rc = rc2;
2196
2197 if (RT_SUCCESS(rc))
2198 {
2199 /* Close the original test set object and use the (temporary) normalized file instead now. */
2200 rc = audioTestObjClose(pObj);
2201 if (RT_SUCCESS(rc))
2202 rc = audioTestObjOpenFile(pObj, szFileDst);
2203 }
2204
2205 return rc;
2206}
2207
2208/**
2209 * Normalizes a test set audio object's audio data.
2210 *
2211 * @returns VBox status code.
2212 * @param pVerJob Verification job that contains \a pObj.
2213 * @param pObj Test set object to normalize.
2214 * @param pProps PCM properties to use for normalization.
2215 *
2216 * @note The test set's file pointer must point to beginning of PCM data to normalize.
2217 */
2218static int audioTestObjFileNormalize(PAUDIOTESTVERIFYJOB pVerJob, PAUDIOTESTOBJINT pObj, PPDMAUDIOPCMPROPS pProps)
2219{
2220 return audioTestObjFileNormalizeEx(pVerJob,
2221 pObj, pProps, 0 /* cbSize, 0 means all */, 100.0 /* dbNormalizePercent */);
2222}
2223
2224/**
2225 * Structure for keeping file comparison parameters for one file.
2226 */
2227typedef struct AUDIOTESTFILECMPPARMS
2228{
2229 /** File name for logging purposes. */
2230 const char *pszName;
2231 /** File handle to file to compare. */
2232 RTFILE hFile;
2233 /** Absolute offset (in bytes) to start comparing.
2234 * Ignored when set to 0. */
2235 uint64_t offStart;
2236 /** Size (in bytes) of area to compare.
2237 * Starts at \a offStart. */
2238 uint64_t cbSize;
2239} AUDIOTESTFILECMPPARMS;
2240/** Pointer to file comparison parameters for one file. */
2241typedef AUDIOTESTFILECMPPARMS *PAUDIOTESTFILECMPPARMS;
2242
2243/**
2244 * Finds differences in two audio test files by binary comparing chunks.
2245 *
2246 * @returns Number of differences. 0 means they are equal (but not necessarily identical).
2247 * @param pVerJob Verification job to verify PCM data for.
2248 * @param pCmpA File comparison parameters to file A to compare file B with.
2249 * @param pCmpB File comparison parameters to file B to compare file A with.
2250 * @param pToneParms Tone parameters to use for comparison.
2251 */
2252static uint32_t audioTestFilesFindDiffsBinary(PAUDIOTESTVERIFYJOB pVerJob,
2253 PAUDIOTESTFILECMPPARMS pCmpA, PAUDIOTESTFILECMPPARMS pCmpB,
2254 PAUDIOTESTTONEPARMS pToneParms)
2255{
2256 uint8_t auBufA[_4K];
2257 uint8_t auBufB[_4K];
2258
2259 int rc = RTFileSeek(pCmpA->hFile, pCmpA->offStart, RTFILE_SEEK_BEGIN, NULL);
2260 AssertRC(rc);
2261
2262 rc = RTFileSeek(pCmpB->hFile, pCmpB->offStart, RTFILE_SEEK_BEGIN, NULL);
2263 AssertRC(rc);
2264
2265 uint32_t cDiffs = 0;
2266 uint64_t cbDiffs = 0;
2267
2268 uint32_t const cbChunkSize = PDMAudioPropsFrameSize(&pToneParms->Props); /* Use the audio frame size as chunk size. */
2269
2270 uint64_t offCur = 0;
2271 uint64_t offDiffStart = 0;
2272 bool fInDiff = false;
2273 uint64_t cbSize = RT_MIN(pCmpA->cbSize, pCmpB->cbSize);
2274 uint64_t cbToCompare = cbSize;
2275
2276 while (cbToCompare)
2277 {
2278 size_t cbReadA;
2279 rc = RTFileRead(pCmpA->hFile, auBufA, RT_MIN(cbToCompare, cbChunkSize), &cbReadA);
2280 AssertRCBreak(rc);
2281 size_t cbReadB;
2282 rc = RTFileRead(pCmpB->hFile, auBufB, RT_MIN(cbToCompare, cbChunkSize), &cbReadB);
2283 AssertRCBreak(rc);
2284 AssertBreakStmt(cbReadA == cbReadB, rc = VERR_INVALID_PARAMETER); /** @todo Find a better rc. */
2285
2286 if (memcmp(auBufA, auBufB, RT_MIN(cbReadA, cbReadB)) != 0)
2287 {
2288 if (!fInDiff) /* No consequitive different chunk? Count as new then. */
2289 {
2290 cDiffs++;
2291 offDiffStart = offCur;
2292 fInDiff = true;
2293 }
2294 }
2295 else /* Reset and count next difference as new then. */
2296 {
2297 if (fInDiff)
2298 {
2299 uint32_t const cbDiff = offCur - offDiffStart;
2300 int rc2 = audioTestErrorDescAddInfo(pVerJob->pErr, pVerJob->idxTest, "Chunks differ: A @ %#x vs. B @ %#x [%08RU64-%08RU64] (%RU64 bytes, %RU64ms)",
2301 pCmpA->offStart, pCmpB->offStart, offDiffStart, offCur,
2302 cbDiff, PDMAudioPropsBytesToMilli(&pToneParms->Props, cbDiff));
2303 AssertRC(rc2);
2304
2305 cbDiffs += cbDiff;
2306 }
2307 fInDiff = false;
2308 }
2309
2310 AssertBreakStmt(cbToCompare >= cbReadA, VERR_INTERNAL_ERROR);
2311 cbToCompare -= cbReadA;
2312 offCur += cbReadA;
2313 }
2314
2315 /* If we didn't mention the last diff yet, do so now. */
2316 if (fInDiff)
2317 {
2318 uint32_t const cbDiff = offCur - offDiffStart;
2319 int rc2 = audioTestErrorDescAddInfo(pVerJob->pErr, pVerJob->idxTest, "Chunks differ: A @ %#x vs. B @ %#x [%08RU64-%08RU64] (%RU64 bytes, %RU64ms)",
2320 pCmpA->offStart, pCmpB->offStart, offDiffStart, offCur,
2321 cbDiff, PDMAudioPropsBytesToMilli(&pToneParms->Props, cbDiff));
2322 AssertRC(rc2);
2323
2324 cbDiffs += cbDiff;
2325 }
2326
2327 if ( cbSize
2328 && cbDiffs)
2329 {
2330 uint8_t const uDiffPercent = cbDiffs / (cbSize * 100);
2331 if (uDiffPercent > pVerJob->Opts.uMaxDiffPercent)
2332 {
2333 int rc2 = audioTestErrorDescAddInfo(pVerJob->pErr, pVerJob->idxTest, "Files binary-differ too much (expected maximum %RU8%%, got %RU8%%)",
2334 pVerJob->Opts.uMaxDiffPercent, uDiffPercent);
2335 AssertRC(rc2);
2336 }
2337 }
2338
2339 return cDiffs;
2340}
2341
2342/**
2343 * Initializes a audio test audio beacon.
2344 *
2345 * @returns VBox status code.
2346 * @param pBeacon Audio test beacon to (re-)initialize.
2347 * @param enmType Beacon type to set.
2348 * @param pProps PCM properties to use for producing audio beacon data.
2349 */
2350void AudioTestBeaconInit(PAUDIOTESTTONEBEACON pBeacon, AUDIOTESTTONEBEACONTYPE enmType, PPDMAUDIOPCMPROPS pProps)
2351{
2352 AssertReturnVoid(PDMAudioPropsFrameSize(pProps) == 4); /** @todo Make this more dynamic. */
2353
2354 RT_BZERO(pBeacon, sizeof(AUDIOTESTTONEBEACON));
2355
2356 pBeacon->enmType = enmType;
2357 memcpy(&pBeacon->Props, pProps, sizeof(PDMAUDIOPCMPROPS));
2358
2359 pBeacon->cbSize = PDMAudioPropsFramesToBytes(&pBeacon->Props, AUDIOTEST_BEACON_SIZE_FRAMES);
2360}
2361
2362/**
2363 * Returns the beacon byte of a beacon type.
2364 *
2365 * @returns Beacon byte if found, 0 otherwise.
2366 * @param enmType Beacon type to get beacon byte for.
2367 */
2368DECLINLINE(uint8_t) AudioTestBeaconByteFromType(AUDIOTESTTONEBEACONTYPE enmType)
2369{
2370 switch (enmType)
2371 {
2372 case AUDIOTESTTONEBEACONTYPE_PLAY_PRE: return AUDIOTEST_BEACON_BYTE_PLAY_PRE;
2373 case AUDIOTESTTONEBEACONTYPE_PLAY_POST: return AUDIOTEST_BEACON_BYTE_PLAY_POST;
2374 case AUDIOTESTTONEBEACONTYPE_REC_PRE: return AUDIOTEST_BEACON_BYTE_REC_PRE;
2375 case AUDIOTESTTONEBEACONTYPE_REC_POST: return AUDIOTEST_BEACON_BYTE_REC_POST;
2376 default: break;
2377 }
2378
2379 AssertFailed();
2380 return 0;
2381}
2382
2383/**
2384 * Returns the total expected (total) size of an audio beacon (in bytes).
2385 *
2386 * @returns Beacon size in bytes.
2387 * @param pBeacon Beacon to get beacon size for.
2388 */
2389uint32_t AudioTestBeaconGetSize(PCAUDIOTESTTONEBEACON pBeacon)
2390{
2391 return pBeacon->cbSize;
2392}
2393
2394/**
2395 * Returns the beacon type of an audio beacon.
2396 *
2397 * @returns Beacon type.
2398 * @param pBeacon Beacon to get beacon size for.
2399 */
2400AUDIOTESTTONEBEACONTYPE AudioTestBeaconGetType(PCAUDIOTESTTONEBEACON pBeacon)
2401{
2402 return pBeacon->enmType;
2403}
2404
2405/**
2406 * Returns the remaining bytes (to be complete) of an audio beacon.
2407 *
2408 * @returns Remaining bytes.
2409 * @param pBeacon Beacon to get remaining size for.
2410 */
2411uint32_t AudioTestBeaconGetRemaining(PCAUDIOTESTTONEBEACON pBeacon)
2412{
2413 return pBeacon->cbSize - pBeacon->cbUsed;
2414}
2415
2416/**
2417 * Returns the already used (received) bytes (to be complete) of an audio beacon.
2418 *
2419 * @returns Used bytes.
2420 * @param pBeacon Beacon to get remaining size for.
2421 */
2422uint32_t AudioTestBeaconGetUsed(PCAUDIOTESTTONEBEACON pBeacon)
2423{
2424 return pBeacon->cbUsed;
2425}
2426
2427/**
2428 * Writes audio beacon data to a given buffer.
2429 *
2430 * @returns VBox status code.
2431 * @param pBeacon Beacon to write to buffer.
2432 * @param pvBuf Buffer to write to.
2433 * @param cbBuf Size (in bytes) of buffer to write to.
2434 */
2435int AudioTestBeaconWrite(PAUDIOTESTTONEBEACON pBeacon, void *pvBuf, uint32_t cbBuf)
2436{
2437 AssertReturn(pBeacon->cbUsed + cbBuf <= pBeacon->cbSize, VERR_BUFFER_OVERFLOW);
2438
2439 memset(pvBuf, AudioTestBeaconByteFromType(pBeacon->enmType), cbBuf);
2440
2441 pBeacon->cbUsed += cbBuf;
2442
2443 return VINF_SUCCESS;
2444}
2445
2446/**
2447 * Converts an audio beacon type to a string.
2448 *
2449 * @returns Pointer to read-only audio beacon type string on success,
2450 * "illegal" if invalid command value.
2451 * @param enmType The type to convert.
2452 */
2453const char *AudioTestBeaconTypeGetName(AUDIOTESTTONEBEACONTYPE enmType)
2454{
2455 switch (enmType)
2456 {
2457 case AUDIOTESTTONEBEACONTYPE_PLAY_PRE: return "pre-playback";
2458 case AUDIOTESTTONEBEACONTYPE_PLAY_POST: return "post-playback";
2459 case AUDIOTESTTONEBEACONTYPE_REC_PRE: return "pre-recording";
2460 case AUDIOTESTTONEBEACONTYPE_REC_POST: return "post-recording";
2461 default: break;
2462 }
2463 AssertMsgFailedReturn(("Invalid beacon type: #%x\n", enmType), "illegal");
2464}
2465
2466/**
2467 * Adds audio data to a given beacon.
2468 *
2469 * @returns VBox status code, VERR_NOT_FOUND if not beacon data was not found.
2470 * @param pBeacon Beacon to add data for.
2471 * @param pauBuf Buffer of audio data to add.
2472 * @param cbBuf Size (in bytes) of \a pauBuf.
2473 * @param pOff Where to return the offset within \a pauBuf where beacon ended on success.
2474 * Optional and can be NULL.
2475 *
2476 * @note The audio data must be a) match the beacon type and b) consecutive, that is, without any gaps,
2477 * to be added as valid to the beacon.
2478 */
2479int AudioTestBeaconAddConsecutive(PAUDIOTESTTONEBEACON pBeacon, const uint8_t *pauBuf, size_t cbBuf, size_t *pOff)
2480{
2481 AssertPtrReturn(pBeacon, VERR_INVALID_POINTER);
2482 AssertPtrReturn(pauBuf, VERR_INVALID_POINTER);
2483 /* pOff is optional. */
2484
2485 uint64_t offBeacon = UINT64_MAX;
2486 uint32_t const cbFrameSize = PDMAudioPropsFrameSize(&pBeacon->Props); /* Use the audio frame size as chunk size. */
2487
2488 uint8_t const byBeacon = AudioTestBeaconByteFromType(pBeacon->enmType);
2489 unsigned const cbStep = cbFrameSize;
2490
2491 /* Make sure that we do frame-aligned reads. */
2492 cbBuf = PDMAudioPropsFloorBytesToFrame(&pBeacon->Props, (uint32_t)cbBuf);
2493
2494 for (size_t i = 0; i < cbBuf; i += cbStep)
2495 {
2496 if ( pauBuf[i] == byBeacon
2497 && pauBuf[i + 1] == byBeacon
2498 && pauBuf[i + 2] == byBeacon
2499 && pauBuf[i + 3] == byBeacon)
2500 {
2501 /* Make sure to handle overflows and let beacon start from scratch. */
2502 pBeacon->cbUsed = (pBeacon->cbUsed + cbStep) % pBeacon->cbSize;
2503 if (pBeacon->cbUsed == 0) /* Beacon complete (see module line above)? */
2504 {
2505 pBeacon->cbUsed = pBeacon->cbSize;
2506 offBeacon = i + cbStep; /* Point to data right *after* the beacon. */
2507 }
2508 }
2509 else
2510 {
2511 /* If beacon is not complete yet, we detected a gap here. Start all over then. */
2512 if (RT_LIKELY(pBeacon->cbUsed != pBeacon->cbSize))
2513 pBeacon->cbUsed = 0;
2514 }
2515 }
2516
2517 if (offBeacon != UINT64_MAX)
2518 {
2519 if (pOff)
2520 *pOff = offBeacon;
2521 }
2522
2523 return offBeacon == UINT64_MAX ? VERR_NOT_FOUND : VINF_SUCCESS;
2524}
2525
2526/**
2527 * Returns whether a beacon is considered to be complete or not.
2528 *
2529 * A complete beacon means that all data for it has been retrieved.
2530 *
2531 * @returns \c true if complete, or \c false if not.
2532 * @param pBeacon Beacon to get completion status for.
2533 */
2534bool AudioTestBeaconIsComplete(PCAUDIOTESTTONEBEACON pBeacon)
2535{
2536 AssertReturn(pBeacon->cbUsed <= pBeacon->cbSize, true);
2537 return (pBeacon->cbUsed == pBeacon->cbSize);
2538}
2539
2540/**
2541 * Verifies a pre/post beacon of a test tone.
2542 *
2543 * @returns VBox status code, VERR_NOT_FOUND if beacon was not found.
2544 * @param pVerJob Verification job to verify PCM data for.
2545 * @param fIn Set to \c true for recording, \c false for playback.
2546 * @param fPre Set to \c true to verify a pre beacon, or \c false to verify a post beacon.
2547 * @param pCmp File comparison parameters to file to verify beacon for.
2548 * @param pToneParms Tone parameters to use for verification.
2549 * @param puOff Where to return the absolute file offset (in bytes) right after the found beacon on success.
2550 * Optional and can be NULL.
2551 */
2552static int audioTestToneVerifyBeacon(PAUDIOTESTVERIFYJOB pVerJob,
2553 bool fIn, bool fPre, PAUDIOTESTFILECMPPARMS pCmp, PAUDIOTESTTONEPARMS pToneParms,
2554 uint64_t *puOff)
2555{
2556 int rc = RTFileSeek(pCmp->hFile, pCmp->offStart, RTFILE_SEEK_BEGIN, NULL);
2557 AssertRCReturn(rc, rc);
2558
2559 AUDIOTESTTONEBEACON Beacon;
2560 AudioTestBeaconInit(&Beacon,
2561 fIn
2562 ? (fPre ? AUDIOTESTTONEBEACONTYPE_PLAY_PRE : AUDIOTESTTONEBEACONTYPE_PLAY_POST)
2563 : (fPre ? AUDIOTESTTONEBEACONTYPE_REC_PRE : AUDIOTESTTONEBEACONTYPE_REC_POST), &pToneParms->Props);
2564
2565 uint8_t auBuf[_64K];
2566 uint64_t cbToCompare = pCmp->cbSize;
2567 uint32_t const cbFrameSize = PDMAudioPropsFrameSize(&Beacon.Props);
2568 uint64_t offBeaconLast = UINT64_MAX;
2569
2570 Assert(sizeof(auBuf) % cbFrameSize == 0);
2571
2572 while (cbToCompare)
2573 {
2574 size_t cbRead;
2575 rc = RTFileRead(pCmp->hFile, auBuf, RT_MIN(cbToCompare, sizeof(auBuf)), &cbRead);
2576 AssertRCBreak(rc);
2577
2578 if (cbRead < cbFrameSize)
2579 break;
2580
2581 size_t uOff;
2582 int rc2 = AudioTestBeaconAddConsecutive(&Beacon, auBuf, cbRead, &uOff);
2583 if (RT_SUCCESS(rc2))
2584 {
2585 /* Save the last found (absolute bytes, in file) position of a (partially) found beacon. */
2586 offBeaconLast = RTFileTell(pCmp->hFile) - (cbRead - uOff);
2587 }
2588
2589 Assert(cbToCompare >= cbRead);
2590 cbToCompare -= cbRead;
2591 }
2592
2593 uint32_t const cbBeacon = AudioTestBeaconGetUsed(&Beacon);
2594
2595 if (!AudioTestBeaconIsComplete(&Beacon))
2596 {
2597 int rc2 = audioTestErrorDescAddError(pVerJob->pErr, pVerJob->idxTest, "File '%s': %s beacon %s (got %RU32 bytes, expected %RU32)",
2598 pCmp->pszName,
2599 AudioTestBeaconTypeGetName(Beacon.enmType),
2600 cbBeacon ? "found" : "not found", cbBeacon,
2601 AudioTestBeaconGetSize(&Beacon));
2602 AssertRC(rc2);
2603 return VERR_NOT_FOUND;
2604 }
2605 else
2606 {
2607 AssertReturn(AudioTestBeaconGetRemaining(&Beacon) == 0, VERR_INTERNAL_ERROR);
2608 AssertReturn(offBeaconLast != UINT32_MAX, VERR_INTERNAL_ERROR);
2609 AssertReturn(offBeaconLast >= AudioTestBeaconGetSize(&Beacon), VERR_INTERNAL_ERROR);
2610
2611 int rc2 = audioTestErrorDescAddInfo(pVerJob->pErr, pVerJob->idxTest, "File '%s': %s beacon found at offset %RU64 and valid",
2612 pCmp->pszName, AudioTestBeaconTypeGetName(Beacon.enmType),
2613 offBeaconLast - AudioTestBeaconGetSize(&Beacon));
2614 AssertRC(rc2);
2615
2616 if (puOff)
2617 *puOff = offBeaconLast;
2618 }
2619
2620 return rc;
2621}
2622
2623#define CHECK_RC_MAYBE_RET(a_rc, a_pVerJob) \
2624 if (RT_FAILURE(a_rc)) \
2625 { \
2626 if (!a_pVerJob->Opts.fKeepGoing) \
2627 return VINF_SUCCESS; \
2628 }
2629
2630#define CHECK_RC_MSG_MAYBE_RET(a_rc, a_pVerJob, a_Msg) \
2631 if (RT_FAILURE(a_rc)) \
2632 { \
2633 int rc3 = audioTestErrorDescAddError(a_pVerJob->pErr, a_pVerJob->idxTest, a_Msg); \
2634 AssertRC(rc3); \
2635 if (!a_pVerJob->Opts.fKeepGoing) \
2636 return VINF_SUCCESS; \
2637 }
2638
2639#define CHECK_RC_MSG_VA_MAYBE_RET(a_rc, a_pVerJob, a_Msg, ...) \
2640 if (RT_FAILURE(a_rc)) \
2641 { \
2642 int rc3 = audioTestErrorDescAddError(a_pVerJob->pErr, a_pVerJob->idxTest, a_Msg, __VA_ARGS__); \
2643 AssertRC(rc3); \
2644 if (!a_pVerJob->Opts.fKeepGoing) \
2645 return VINF_SUCCESS; \
2646
2647/**
2648 * Does the actual PCM data verification of a test tone.
2649 *
2650 * @returns VBox status code.
2651 * @param pVerJob Verification job to verify PCM data for.
2652 * @param phTestA Test handle A of test to verify PCM data for.
2653 * @param phTestB Test handle B of test to verify PCM data for.
2654 */
2655static int audioTestVerifyTestToneData(PAUDIOTESTVERIFYJOB pVerJob, PAUDIOTESTOBJINT phTestA, PAUDIOTESTOBJINT phTestB)
2656{
2657 int rc;
2658
2659 /** @todo For now ASSUME that we only have one object per test. */
2660
2661 AUDIOTESTOBJINT ObjA;
2662 rc = audioTestObjGetChild(phTestA, 0 /* idxObj */, &ObjA);
2663 CHECK_RC_MSG_MAYBE_RET(rc, pVerJob, "Unable to get object A");
2664
2665 rc = audioTestObjOpen(&ObjA);
2666 CHECK_RC_MSG_MAYBE_RET(rc, pVerJob, "Unable to open object A");
2667
2668 AUDIOTESTOBJINT ObjB;
2669 rc = audioTestObjGetChild(phTestB, 0 /* idxObj */, &ObjB);
2670 CHECK_RC_MSG_MAYBE_RET(rc, pVerJob, "Unable to get object B");
2671
2672 rc = audioTestObjOpen(&ObjB);
2673 CHECK_RC_MSG_MAYBE_RET(rc, pVerJob, "Unable to open object B");
2674
2675 /*
2676 * Start with most obvious methods first.
2677 */
2678 uint64_t cbFileSizeA, cbFileSizeB;
2679 rc = RTFileQuerySize(ObjA.File.hFile, &cbFileSizeA);
2680 AssertRCReturn(rc, rc);
2681 rc = RTFileQuerySize(ObjB.File.hFile, &cbFileSizeB);
2682 AssertRCReturn(rc, rc);
2683
2684 if (!cbFileSizeA)
2685 {
2686 int rc2 = audioTestErrorDescAddError(pVerJob->pErr, pVerJob->idxTest, "File '%s' is empty", ObjA.szName);
2687 AssertRC(rc2);
2688 }
2689
2690 if (!cbFileSizeB)
2691 {
2692 int rc2 = audioTestErrorDescAddError(pVerJob->pErr, pVerJob->idxTest, "File '%s' is empty", ObjB.szName);
2693 AssertRC(rc2);
2694 }
2695
2696 if (cbFileSizeA != cbFileSizeB)
2697 {
2698 size_t const cbDiffAbs = cbFileSizeA > cbFileSizeB ? cbFileSizeA - cbFileSizeB : cbFileSizeB - cbFileSizeA;
2699
2700 int rc2 = audioTestErrorDescAddInfo(pVerJob->pErr, pVerJob->idxTest, "File '%s': %zu bytes (%RU64ms)",
2701 ObjA.szName, cbFileSizeA, PDMAudioPropsBytesToMilli(&pVerJob->PCMProps, cbFileSizeA));
2702 AssertRC(rc2);
2703 rc2 = audioTestErrorDescAddInfo(pVerJob->pErr, pVerJob->idxTest, "File '%s': %zu bytes (%RU64ms)",
2704 ObjB.szName, cbFileSizeB, PDMAudioPropsBytesToMilli(&pVerJob->PCMProps, cbFileSizeB));
2705 AssertRC(rc2);
2706
2707 uint8_t const uSizeDiffPercentAbs
2708 = cbFileSizeA > cbFileSizeB ? 100 - ((cbFileSizeB * 100) / cbFileSizeA) : 100 - ((cbFileSizeA * 100) / cbFileSizeB);
2709
2710 if (uSizeDiffPercentAbs > pVerJob->Opts.uMaxSizePercent)
2711 {
2712 rc2 = audioTestErrorDescAddError(pVerJob->pErr, pVerJob->idxTest,
2713 "File '%s' is %RU8%% (%zu bytes, %RU64ms) %s than '%s' (threshold is %RU8%%)",
2714 ObjA.szName,
2715 uSizeDiffPercentAbs,
2716 cbDiffAbs, PDMAudioPropsBytesToMilli(&pVerJob->PCMProps, (uint32_t)cbDiffAbs),
2717 cbFileSizeA > cbFileSizeB ? "bigger" : "smaller",
2718 ObjB.szName, pVerJob->Opts.uMaxSizePercent);
2719 AssertRC(rc2);
2720 }
2721 }
2722
2723 /* Do normalization first if enabled. */
2724 if (pVerJob->Opts.fNormalize)
2725 {
2726 rc = audioTestObjFileNormalize(pVerJob, &ObjA, &pVerJob->PCMProps);
2727 if (RT_SUCCESS(rc))
2728 rc = audioTestObjFileNormalize(pVerJob, &ObjB, &pVerJob->PCMProps);
2729 }
2730
2731 /** @todo For now we only support comparison of data which do have identical PCM properties! */
2732
2733 AUDIOTESTTONEPARMS ToneParmsA;
2734 RT_ZERO(ToneParmsA);
2735 ToneParmsA.Props = pVerJob->PCMProps;
2736
2737 size_t cbSearchWindow = PDMAudioPropsMilliToBytes(&ToneParmsA.Props, pVerJob->Opts.msSearchWindow);
2738
2739 AUDIOTESTFILECMPPARMS FileA;
2740 RT_ZERO(FileA);
2741 FileA.pszName = ObjA.szName;
2742 FileA.hFile = ObjA.File.hFile;
2743 FileA.offStart = audioTestToneFileFind(ObjA.File.hFile, true /* fFindSilence */,
2744 0 /* uOff */, cbFileSizeA /* cbMax */, &ToneParmsA, cbSearchWindow);
2745 FileA.cbSize = audioTestToneFileFind(ObjA.File.hFile, false /* fFindSilence */,
2746 FileA.offStart /* uOff */, cbFileSizeA - FileA.offStart /* cbMax */, &ToneParmsA, cbSearchWindow);
2747 AssertReturn(FileA.offStart + FileA.cbSize <= cbFileSizeA, VERR_INTERNAL_ERROR);
2748
2749 AUDIOTESTTONEPARMS ToneParmsB;
2750 RT_ZERO(ToneParmsB);
2751 ToneParmsB.Props = pVerJob->PCMProps;
2752
2753 AUDIOTESTFILECMPPARMS FileB;
2754 RT_ZERO(FileB);
2755 FileB.pszName = ObjB.szName;
2756 FileB.hFile = ObjB.File.hFile;
2757 FileB.offStart = audioTestToneFileFind(ObjB.File.hFile, true /* fFindSilence */,
2758 0 /* uOff */, cbFileSizeB /* cbMax */, &ToneParmsB, cbSearchWindow);
2759 FileB.cbSize = audioTestToneFileFind(ObjB.File.hFile, false /* fFindSilence */,
2760 FileB.offStart /* uOff */, cbFileSizeB - FileB.offStart /* cbMax */, &ToneParmsB, cbSearchWindow);
2761 AssertReturn(FileB.offStart + FileB.cbSize <= cbFileSizeB, VERR_INTERNAL_ERROR);
2762
2763 int rc2;
2764
2765 uint64_t offBeaconAbs;
2766 rc = audioTestToneVerifyBeacon(pVerJob, phTestA->enmTestType == AUDIOTESTTYPE_TESTTONE_PLAY /* fIn */,
2767 true /* fPre */, &FileA, &ToneParmsA, &offBeaconAbs);
2768 if (RT_SUCCESS(rc))
2769 {
2770 FileA.offStart = offBeaconAbs;
2771 FileA.cbSize = cbFileSizeA - FileA.offStart;
2772 rc = audioTestToneVerifyBeacon(pVerJob, phTestA->enmTestType == AUDIOTESTTYPE_TESTTONE_PLAY /* fIn */,
2773 false /* fPre */, &FileA, &ToneParmsA, &offBeaconAbs);
2774 if (RT_SUCCESS(rc))
2775 {
2776 /* Adjust the size of the area to compare so that it's within the pre + post beacons. */
2777 Assert(offBeaconAbs >= FileA.offStart);
2778 FileA.cbSize = offBeaconAbs - FileA.offStart;
2779 }
2780 }
2781
2782 rc = audioTestToneVerifyBeacon(pVerJob, phTestB->enmTestType == AUDIOTESTTYPE_TESTTONE_RECORD /* fIn */,
2783 true /* fPre */, &FileB, &ToneParmsB, &offBeaconAbs);
2784 if (RT_SUCCESS(rc))
2785 {
2786 FileB.offStart = offBeaconAbs;
2787 FileB.cbSize = cbFileSizeB - FileB.offStart;
2788 rc = audioTestToneVerifyBeacon(pVerJob, phTestB->enmTestType == AUDIOTESTTYPE_TESTTONE_RECORD /* fIn */,
2789 false /* fPre */, &FileB, &ToneParmsB, &offBeaconAbs);
2790 if (RT_SUCCESS(rc))
2791 {
2792 /* Adjust the size of the area to compare so that it's within the pre + post beacons. */
2793 Assert(offBeaconAbs >= FileB.offStart);
2794 FileB.cbSize = offBeaconAbs - FileB.offStart;
2795 }
2796 }
2797
2798 if (RT_SUCCESS(rc))
2799 {
2800 uint32_t const cDiffs = audioTestFilesFindDiffsBinary(pVerJob, &FileA, &FileB, &ToneParmsA);
2801
2802 if (cDiffs > pVerJob->Opts.cMaxDiff)
2803 {
2804 rc2 = audioTestErrorDescAddError(pVerJob->pErr, pVerJob->idxTest,
2805 "Files '%s' and '%s' have too many different chunks (got %RU32, expected %RU32)",
2806 ObjA.szName, ObjB.szName, cDiffs, pVerJob->Opts.cMaxDiff);
2807 AssertRC(rc2);
2808 }
2809 }
2810
2811 if (AudioTestErrorDescFailed(pVerJob->pErr))
2812 {
2813 rc2 = audioTestErrorDescAddInfo(pVerJob->pErr, pVerJob->idxTest, "Files '%s' and '%s' do not match",
2814 ObjA.szName, ObjB.szName);
2815 AssertRC(rc2);
2816 }
2817
2818 rc = audioTestObjClose(&ObjA);
2819 AssertRCReturn(rc, rc);
2820 rc = audioTestObjClose(&ObjB);
2821 AssertRCReturn(rc, rc);
2822
2823 return rc;
2824}
2825
2826/**
2827 * Verifies a test tone test.
2828 *
2829 * @returns VBox status code.
2830 * @returns Error if the verification failed and test verification job has fKeepGoing not set.
2831 * @retval VERR_
2832 * @param pVerJob Verification job to verify test tone for.
2833 * @param phTestA Test handle of test tone A to verify tone B with.
2834 * @param phTestB Test handle of test tone B to verify tone A with.*
2835 */
2836static int audioTestVerifyTestTone(PAUDIOTESTVERIFYJOB pVerJob, PAUDIOTESTOBJINT phTestA, PAUDIOTESTOBJINT phTestB)
2837{
2838 int rc;
2839
2840 /*
2841 * Verify test parameters.
2842 * More important items have precedence.
2843 */
2844 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "error_rc", "0", "Test was reported as failed");
2845 CHECK_RC_MAYBE_RET(rc, pVerJob);
2846 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "obj_count", NULL, "Object counts don't match");
2847 CHECK_RC_MAYBE_RET(rc, pVerJob);
2848 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_freq_hz", NULL, "Tone frequency doesn't match");
2849 CHECK_RC_MAYBE_RET(rc, pVerJob);
2850 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_prequel_ms", NULL, "Tone prequel (ms) doesn't match");
2851 CHECK_RC_MAYBE_RET(rc, pVerJob);
2852 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_duration_ms", NULL, "Tone duration (ms) doesn't match");
2853 CHECK_RC_MAYBE_RET(rc, pVerJob);
2854 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_sequel_ms", NULL, "Tone sequel (ms) doesn't match");
2855 CHECK_RC_MAYBE_RET(rc, pVerJob);
2856 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_volume_percent", NULL, "Tone volume (percent) doesn't match");
2857 CHECK_RC_MAYBE_RET(rc, pVerJob);
2858 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_pcm_hz", NULL, "Tone PCM Hz doesn't match");
2859 CHECK_RC_MAYBE_RET(rc, pVerJob);
2860 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_pcm_channels", NULL, "Tone PCM channels don't match");
2861 CHECK_RC_MAYBE_RET(rc, pVerJob);
2862 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_pcm_bits", NULL, "Tone PCM bits don't match");
2863 CHECK_RC_MAYBE_RET(rc, pVerJob);
2864 rc = audioTestVerifyValue(pVerJob, phTestA, phTestB, "tone_pcm_is_signed", NULL, "Tone PCM signed bit doesn't match");
2865 CHECK_RC_MAYBE_RET(rc, pVerJob);
2866
2867 rc = audioTestObjGetTonePcmProps(phTestA, &pVerJob->PCMProps);
2868 CHECK_RC_MAYBE_RET(rc, pVerJob);
2869
2870 /*
2871 * Now the fun stuff, PCM data analysis.
2872 */
2873 rc = audioTestVerifyTestToneData(pVerJob, phTestA, phTestB);
2874 if (RT_FAILURE(rc))
2875 {
2876 int rc2 = audioTestErrorDescAddError(pVerJob->pErr, pVerJob->idxTest, "Verififcation of test tone data failed\n");
2877 AssertRC(rc2);
2878 }
2879
2880 return VINF_SUCCESS;
2881}
2882
2883/**
2884 * Verifies an opened audio test set, extended version.
2885 *
2886 * @returns VBox status code.
2887 * @param pSetA Test set A to verify.
2888 * @param pSetB Test set to verify test set A with.
2889 * @param pOpts Verification options to use.
2890 * @param pErrDesc Where to return the test verification errors.
2891 *
2892 * @note Test verification errors have to be checked for errors, regardless of the
2893 * actual return code.
2894 * @note Uses the standard verification options. Use AudioTestSetVerifyEx() to specify
2895 * own options.
2896 */
2897int AudioTestSetVerifyEx(PAUDIOTESTSET pSetA, PAUDIOTESTSET pSetB, PAUDIOTESTVERIFYOPTS pOpts, PAUDIOTESTERRORDESC pErrDesc)
2898{
2899 AssertPtrReturn(pSetA, VERR_INVALID_POINTER);
2900 AssertPtrReturn(pSetB, VERR_INVALID_POINTER);
2901 AssertReturn(audioTestManifestIsOpen(pSetA), VERR_WRONG_ORDER);
2902 AssertReturn(audioTestManifestIsOpen(pSetB), VERR_WRONG_ORDER);
2903 AssertPtrReturn(pOpts, VERR_INVALID_POINTER);
2904
2905 /* We ASSUME the caller has not init'd pErrDesc. */
2906 audioTestErrorDescInit(pErrDesc);
2907
2908 AUDIOTESTVERIFYJOB VerJob;
2909 RT_ZERO(VerJob);
2910 VerJob.pErr = pErrDesc;
2911 VerJob.pSetA = pSetA;
2912 VerJob.pSetB = pSetB;
2913
2914 memcpy(&VerJob.Opts, pOpts, sizeof(AUDIOTESTVERIFYOPTS));
2915
2916 PAUDIOTESTVERIFYJOB pVerJob = &VerJob;
2917
2918 int rc;
2919
2920 /*
2921 * Compare obvious values first.
2922 */
2923 AUDIOTESTOBJINT hHdrA;
2924 rc = audioTestSetGetSection(pVerJob->pSetA, AUDIOTEST_SEC_HDR_STR, &hHdrA);
2925 CHECK_RC_MAYBE_RET(rc, pVerJob);
2926
2927 AUDIOTESTOBJINT hHdrB;
2928 rc = audioTestSetGetSection(pVerJob->pSetB, AUDIOTEST_SEC_HDR_STR, &hHdrB);
2929 CHECK_RC_MAYBE_RET(rc, pVerJob);
2930
2931 rc = audioTestVerifyValue(&VerJob, &hHdrA, &hHdrB, "magic", "vkat_ini", "Manifest magic wrong");
2932 CHECK_RC_MAYBE_RET(rc, pVerJob);
2933 rc = audioTestVerifyValue(&VerJob, &hHdrA, &hHdrB, "ver", "1" , "Manifest version wrong");
2934 CHECK_RC_MAYBE_RET(rc, pVerJob);
2935 rc = audioTestVerifyValue(&VerJob, &hHdrA, &hHdrB, "tag", NULL, "Manifest tags don't match");
2936 CHECK_RC_MAYBE_RET(rc, pVerJob);
2937 rc = audioTestVerifyValue(&VerJob, &hHdrA, &hHdrB, "test_count", NULL, "Test counts don't match");
2938 CHECK_RC_MAYBE_RET(rc, pVerJob);
2939 rc = audioTestVerifyValue(&VerJob, &hHdrA, &hHdrB, "obj_count", NULL, "Object counts don't match");
2940 CHECK_RC_MAYBE_RET(rc, pVerJob);
2941
2942 /*
2943 * Compare ran tests.
2944 */
2945 uint32_t cTests;
2946 rc = audioTestObjGetUInt32(&hHdrA, "test_count", &cTests);
2947 AssertRCReturn(rc, rc);
2948
2949 for (uint32_t i = 0; i < cTests; i++)
2950 {
2951 VerJob.idxTest = i;
2952
2953 AUDIOTESTOBJINT hTestA;
2954 rc = audioTestSetGetTest(VerJob.pSetA, i, &hTestA);
2955 CHECK_RC_MSG_MAYBE_RET(rc, pVerJob, "Test A not found");
2956
2957 AUDIOTESTOBJINT hTestB;
2958 rc = audioTestSetGetTest(VerJob.pSetB, i, &hTestB);
2959 CHECK_RC_MSG_MAYBE_RET(rc, pVerJob, "Test B not found");
2960
2961 rc = audioTestObjGetUInt32(&hTestA, "test_type", (uint32_t *)&hTestA.enmTestType);
2962 CHECK_RC_MSG_MAYBE_RET(rc, pVerJob, "Test type A not found");
2963
2964 rc = audioTestObjGetUInt32(&hTestB, "test_type", (uint32_t *)&hTestB.enmTestType);
2965 CHECK_RC_MSG_MAYBE_RET(rc, pVerJob, "Test type B not found");
2966
2967 switch (hTestA.enmTestType)
2968 {
2969 case AUDIOTESTTYPE_TESTTONE_PLAY:
2970 {
2971 if (hTestB.enmTestType == AUDIOTESTTYPE_TESTTONE_RECORD)
2972 rc = audioTestVerifyTestTone(&VerJob, &hTestA, &hTestB);
2973 else
2974 rc = audioTestErrorDescAddError(pErrDesc, i, "Playback test types don't match (set A=%#x, set B=%#x)",
2975 hTestA.enmTestType, hTestB.enmTestType);
2976 break;
2977 }
2978
2979 case AUDIOTESTTYPE_TESTTONE_RECORD:
2980 {
2981 if (hTestB.enmTestType == AUDIOTESTTYPE_TESTTONE_PLAY)
2982 rc = audioTestVerifyTestTone(&VerJob, &hTestB, &hTestA);
2983 else
2984 rc = audioTestErrorDescAddError(pErrDesc, i, "Recording test types don't match (set A=%#x, set B=%#x)",
2985 hTestA.enmTestType, hTestB.enmTestType);
2986 break;
2987 }
2988
2989 case AUDIOTESTTYPE_INVALID:
2990 rc = VERR_INVALID_PARAMETER;
2991 break;
2992
2993 default:
2994 rc = VERR_NOT_IMPLEMENTED;
2995 break;
2996 }
2997
2998 AssertRC(rc);
2999 }
3000
3001 /* Only return critical stuff not related to actual testing here. */
3002 return VINF_SUCCESS;
3003}
3004
3005/**
3006 * Initializes audio test verification options in a strict manner.
3007 *
3008 * @param pOpts Verification options to initialize.
3009 */
3010void AudioTestSetVerifyOptsInitStrict(PAUDIOTESTVERIFYOPTS pOpts)
3011{
3012 RT_BZERO(pOpts, sizeof(AUDIOTESTVERIFYOPTS));
3013
3014 pOpts->fKeepGoing = true;
3015 pOpts->fNormalize = false; /* Skip normalization by default now, as we now use the OS' master volume to play/record tones. */
3016 pOpts->cMaxDiff = 0; /* By default we're very strict and consider any diff as being erroneous. */
3017 pOpts->uMaxSizePercent = 10; /* 10% is okay for us for now; might be due to any buffering / setup phase.
3018 Anything above this is suspicious and should be reported for further investigation. */
3019 pOpts->msSearchWindow = 10; /* We use a search window of 10ms by default for finding (non-)silent parts. */
3020}
3021
3022/**
3023 * Initializes audio test verification options with default values (strict!).
3024 *
3025 * @param pOpts Verification options to initialize.
3026 */
3027void AudioTestSetVerifyOptsInit(PAUDIOTESTVERIFYOPTS pOpts)
3028{
3029 AudioTestSetVerifyOptsInitStrict(pOpts);
3030}
3031
3032/**
3033 * Returns whether two audio test verification options are equal.
3034 *
3035 * @returns \c true if equal, or \c false if not.
3036 * @param pOptsA Options A to compare.
3037 * @param pOptsB Options B to compare Options A with.
3038 */
3039bool AudioTestSetVerifyOptsAreEqual(PAUDIOTESTVERIFYOPTS pOptsA, PAUDIOTESTVERIFYOPTS pOptsB)
3040{
3041 if (pOptsA == pOptsB)
3042 return true;
3043
3044 return ( pOptsA->cMaxDiff == pOptsB->cMaxDiff
3045 && pOptsA->fKeepGoing == pOptsB->fKeepGoing
3046 && pOptsA->fNormalize == pOptsB->fNormalize
3047 && pOptsA->uMaxDiffPercent == pOptsB->uMaxDiffPercent
3048 && pOptsA->uMaxSizePercent == pOptsB->uMaxSizePercent
3049 && pOptsA->msSearchWindow == pOptsB->msSearchWindow);
3050}
3051
3052/**
3053 * Verifies an opened audio test set.
3054 *
3055 * @returns VBox status code.
3056 * @param pSetA Test set A to verify.
3057 * @param pSetB Test set to verify test set A with.
3058 * @param pErrDesc Where to return the test verification errors.
3059 *
3060 * @note Test verification errors have to be checked for errors, regardless of the
3061 * actual return code.
3062 * @note Uses the standard verification options (strict!).
3063 * Use AudioTestSetVerifyEx() to specify own options.
3064 */
3065int AudioTestSetVerify(PAUDIOTESTSET pSetA, PAUDIOTESTSET pSetB, PAUDIOTESTERRORDESC pErrDesc)
3066{
3067 AUDIOTESTVERIFYOPTS Opts;
3068 AudioTestSetVerifyOptsInitStrict(&Opts);
3069
3070 return AudioTestSetVerifyEx(pSetA,pSetB, &Opts, pErrDesc);
3071}
3072
3073#undef CHECK_RC_MAYBE_RET
3074#undef CHECK_RC_MSG_MAYBE_RET
3075
3076/**
3077 * Converts an audio test state enum value to a string.
3078 *
3079 * @returns Pointer to read-only internal test state string on success,
3080 * "illegal" if invalid command value.
3081 * @param enmState The state to convert.
3082 */
3083const char *AudioTestStateToStr(AUDIOTESTSTATE enmState)
3084{
3085 switch (enmState)
3086 {
3087 case AUDIOTESTSTATE_INIT: return "init";
3088 case AUDIOTESTSTATE_PRE: return "pre";
3089 case AUDIOTESTSTATE_RUN: return "run";
3090 case AUDIOTESTSTATE_POST: return "post";
3091 case AUDIOTESTSTATE_DONE: return "done";
3092 case AUDIOTESTSTATE_32BIT_HACK:
3093 break;
3094 }
3095 AssertMsgFailedReturn(("Invalid test state: #%x\n", enmState), "illegal");
3096}
3097
3098
3099/*********************************************************************************************************************************
3100* WAVE File Reader. *
3101*********************************************************************************************************************************/
3102
3103/**
3104 * Counts the number of set bits in @a fMask.
3105 */
3106static unsigned audioTestWaveCountBits(uint32_t fMask)
3107{
3108 unsigned cBits = 0;
3109 while (fMask)
3110 {
3111 if (fMask & 1)
3112 cBits++;
3113 fMask >>= 1;
3114 }
3115 return cBits;
3116}
3117
3118/**
3119 * Opens a wave (.WAV) file for reading.
3120 *
3121 * @returns VBox status code.
3122 * @param pszFile The file to open.
3123 * @param pWaveFile The open wave file structure to fill in on success.
3124 * @param pErrInfo Where to return addition error details on failure.
3125 */
3126int AudioTestWaveFileOpen(const char *pszFile, PAUDIOTESTWAVEFILE pWaveFile, PRTERRINFO pErrInfo)
3127{
3128 pWaveFile->u32Magic = AUDIOTESTWAVEFILE_MAGIC_DEAD;
3129 RT_ZERO(pWaveFile->Props);
3130 pWaveFile->hFile = NIL_RTFILE;
3131 int rc = RTFileOpen(&pWaveFile->hFile, pszFile, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
3132 if (RT_FAILURE(rc))
3133 return RTErrInfoSet(pErrInfo, rc, "RTFileOpen failed");
3134 uint64_t cbFile = 0;
3135 rc = RTFileQuerySize(pWaveFile->hFile, &cbFile);
3136 if (RT_SUCCESS(rc))
3137 {
3138 union
3139 {
3140 uint8_t ab[512];
3141 struct
3142 {
3143 RTRIFFHDR Hdr;
3144 union
3145 {
3146 RTRIFFWAVEFMTCHUNK Fmt;
3147 RTRIFFWAVEFMTEXTCHUNK FmtExt;
3148 } u;
3149 } Wave;
3150 RTRIFFLIST List;
3151 RTRIFFCHUNK Chunk;
3152 RTRIFFWAVEDATACHUNK Data;
3153 } uBuf;
3154
3155 rc = RTFileRead(pWaveFile->hFile, &uBuf.Wave, sizeof(uBuf.Wave), NULL);
3156 if (RT_SUCCESS(rc))
3157 {
3158 rc = VERR_VFS_UNKNOWN_FORMAT;
3159 if ( uBuf.Wave.Hdr.uMagic == RTRIFFHDR_MAGIC
3160 && uBuf.Wave.Hdr.uFileType == RTRIFF_FILE_TYPE_WAVE
3161 && uBuf.Wave.u.Fmt.Chunk.uMagic == RTRIFFWAVEFMT_MAGIC
3162 && uBuf.Wave.u.Fmt.Chunk.cbChunk >= sizeof(uBuf.Wave.u.Fmt.Data))
3163 {
3164 if (uBuf.Wave.Hdr.cbFile != cbFile - sizeof(RTRIFFCHUNK))
3165 RTErrInfoSetF(pErrInfo, rc, "File size mismatch: %#x, actual %#RX64 (ignored)",
3166 uBuf.Wave.Hdr.cbFile, cbFile - sizeof(RTRIFFCHUNK));
3167 rc = VERR_VFS_BOGUS_FORMAT;
3168 if ( uBuf.Wave.u.Fmt.Data.uFormatTag != RTRIFFWAVEFMT_TAG_PCM
3169 && uBuf.Wave.u.Fmt.Data.uFormatTag != RTRIFFWAVEFMT_TAG_EXTENSIBLE)
3170 RTErrInfoSetF(pErrInfo, rc, "Unsupported uFormatTag value: %#x (expected %#x or %#x)",
3171 uBuf.Wave.u.Fmt.Data.uFormatTag, RTRIFFWAVEFMT_TAG_PCM, RTRIFFWAVEFMT_TAG_EXTENSIBLE);
3172 else if ( uBuf.Wave.u.Fmt.Data.cBitsPerSample != 8
3173 && uBuf.Wave.u.Fmt.Data.cBitsPerSample != 16
3174 /* && uBuf.Wave.u.Fmt.Data.cBitsPerSample != 24 - not supported by our stack */
3175 && uBuf.Wave.u.Fmt.Data.cBitsPerSample != 32)
3176 RTErrInfoSetF(pErrInfo, rc, "Unsupported cBitsPerSample value: %u", uBuf.Wave.u.Fmt.Data.cBitsPerSample);
3177 else if ( uBuf.Wave.u.Fmt.Data.cChannels < 1
3178 || uBuf.Wave.u.Fmt.Data.cChannels >= 16)
3179 RTErrInfoSetF(pErrInfo, rc, "Unsupported cChannels value: %u (expected 1..15)", uBuf.Wave.u.Fmt.Data.cChannels);
3180 else if ( uBuf.Wave.u.Fmt.Data.uHz < 4096
3181 || uBuf.Wave.u.Fmt.Data.uHz > 768000)
3182 RTErrInfoSetF(pErrInfo, rc, "Unsupported uHz value: %u (expected 4096..768000)", uBuf.Wave.u.Fmt.Data.uHz);
3183 else if (uBuf.Wave.u.Fmt.Data.cbFrame != uBuf.Wave.u.Fmt.Data.cChannels * uBuf.Wave.u.Fmt.Data.cBitsPerSample / 8)
3184 RTErrInfoSetF(pErrInfo, rc, "Invalid cbFrame value: %u (expected %u)", uBuf.Wave.u.Fmt.Data.cbFrame,
3185 uBuf.Wave.u.Fmt.Data.cChannels * uBuf.Wave.u.Fmt.Data.cBitsPerSample / 8);
3186 else if (uBuf.Wave.u.Fmt.Data.cbRate != uBuf.Wave.u.Fmt.Data.cbFrame * uBuf.Wave.u.Fmt.Data.uHz)
3187 RTErrInfoSetF(pErrInfo, rc, "Invalid cbRate value: %u (expected %u)", uBuf.Wave.u.Fmt.Data.cbRate,
3188 uBuf.Wave.u.Fmt.Data.cbFrame * uBuf.Wave.u.Fmt.Data.uHz);
3189 else if ( uBuf.Wave.u.Fmt.Data.uFormatTag == RTRIFFWAVEFMT_TAG_EXTENSIBLE
3190 && uBuf.Wave.u.FmtExt.Data.cbExtra < RTRIFFWAVEFMTEXT_EXTRA_SIZE)
3191 RTErrInfoSetF(pErrInfo, rc, "Invalid cbExtra value: %#x (expected at least %#x)",
3192 uBuf.Wave.u.FmtExt.Data.cbExtra, RTRIFFWAVEFMTEXT_EXTRA_SIZE);
3193 else if ( uBuf.Wave.u.Fmt.Data.uFormatTag == RTRIFFWAVEFMT_TAG_EXTENSIBLE
3194 && audioTestWaveCountBits(uBuf.Wave.u.FmtExt.Data.fChannelMask) != uBuf.Wave.u.Fmt.Data.cChannels)
3195 RTErrInfoSetF(pErrInfo, rc, "fChannelMask does not match cChannels: %#x (%u bits set) vs %u channels",
3196 uBuf.Wave.u.FmtExt.Data.fChannelMask,
3197 audioTestWaveCountBits(uBuf.Wave.u.FmtExt.Data.fChannelMask), uBuf.Wave.u.Fmt.Data.cChannels);
3198 else if ( uBuf.Wave.u.Fmt.Data.uFormatTag == RTRIFFWAVEFMT_TAG_EXTENSIBLE
3199 && RTUuidCompareStr(&uBuf.Wave.u.FmtExt.Data.SubFormat, RTRIFFWAVEFMTEXT_SUBTYPE_PCM) != 0)
3200 RTErrInfoSetF(pErrInfo, rc, "SubFormat is not PCM: %RTuuid (expected %s)",
3201 &uBuf.Wave.u.FmtExt.Data.SubFormat, RTRIFFWAVEFMTEXT_SUBTYPE_PCM);
3202 else
3203 {
3204 /*
3205 * Copy out the data we need from the file format structure.
3206 */
3207 PDMAudioPropsInit(&pWaveFile->Props, uBuf.Wave.u.Fmt.Data.cBitsPerSample / 8, true /*fSigned*/,
3208 uBuf.Wave.u.Fmt.Data.cChannels, uBuf.Wave.u.Fmt.Data.uHz);
3209 pWaveFile->offSamples = sizeof(RTRIFFHDR) + sizeof(RTRIFFCHUNK) + uBuf.Wave.u.Fmt.Chunk.cbChunk;
3210
3211 /*
3212 * Pick up channel assignments if present.
3213 */
3214 if (uBuf.Wave.u.Fmt.Data.uFormatTag == RTRIFFWAVEFMT_TAG_EXTENSIBLE)
3215 {
3216 static unsigned const s_cStdIds = (unsigned)PDMAUDIOCHANNELID_END_STANDARD
3217 - (unsigned)PDMAUDIOCHANNELID_FIRST_STANDARD;
3218 unsigned iCh = 0;
3219 for (unsigned idCh = 0; idCh < 32 && iCh < uBuf.Wave.u.Fmt.Data.cChannels; idCh++)
3220 if (uBuf.Wave.u.FmtExt.Data.fChannelMask & RT_BIT_32(idCh))
3221 {
3222 pWaveFile->Props.aidChannels[iCh] = idCh < s_cStdIds
3223 ? idCh + (unsigned)PDMAUDIOCHANNELID_FIRST_STANDARD
3224 : (unsigned)PDMAUDIOCHANNELID_UNKNOWN;
3225 iCh++;
3226 }
3227 }
3228
3229 /*
3230 * Find the 'data' chunk with the audio samples.
3231 *
3232 * There can be INFO lists both preceeding this and succeeding
3233 * it, containing IART and other things we can ignored. Thus
3234 * we read a list header here rather than just a chunk header,
3235 * since it doesn't matter if we read 4 bytes extra as
3236 * AudioTestWaveFileRead uses RTFileReadAt anyway.
3237 */
3238 rc = RTFileReadAt(pWaveFile->hFile, pWaveFile->offSamples, &uBuf, sizeof(uBuf.List), NULL);
3239 for (uint32_t i = 0;
3240 i < 128
3241 && RT_SUCCESS(rc)
3242 && uBuf.Chunk.uMagic != RTRIFFWAVEDATACHUNK_MAGIC
3243 && (uint64_t)uBuf.Chunk.cbChunk + sizeof(RTRIFFCHUNK) * 2 <= cbFile - pWaveFile->offSamples;
3244 i++)
3245 {
3246 if ( uBuf.List.uMagic == RTRIFFLIST_MAGIC
3247 && uBuf.List.uListType == RTRIFFLIST_TYPE_INFO)
3248 { /*skip*/ }
3249 else if (uBuf.Chunk.uMagic == RTRIFFPADCHUNK_MAGIC)
3250 { /*skip*/ }
3251 else
3252 break;
3253 pWaveFile->offSamples += sizeof(RTRIFFCHUNK) + uBuf.Chunk.cbChunk;
3254 rc = RTFileReadAt(pWaveFile->hFile, pWaveFile->offSamples, &uBuf, sizeof(uBuf.List), NULL);
3255 }
3256 if (RT_SUCCESS(rc))
3257 {
3258 pWaveFile->offSamples += sizeof(uBuf.Data.Chunk);
3259 pWaveFile->cbSamples = (uint32_t)cbFile - pWaveFile->offSamples;
3260
3261 rc = VERR_VFS_BOGUS_FORMAT;
3262 if ( uBuf.Data.Chunk.uMagic == RTRIFFWAVEDATACHUNK_MAGIC
3263 && uBuf.Data.Chunk.cbChunk <= pWaveFile->cbSamples
3264 && PDMAudioPropsIsSizeAligned(&pWaveFile->Props, uBuf.Data.Chunk.cbChunk))
3265 {
3266 pWaveFile->cbSamples = uBuf.Data.Chunk.cbChunk;
3267
3268 /*
3269 * We're good!
3270 */
3271 pWaveFile->offCur = 0;
3272 pWaveFile->fReadMode = true;
3273 pWaveFile->u32Magic = AUDIOTESTWAVEFILE_MAGIC;
3274 return VINF_SUCCESS;
3275 }
3276
3277 RTErrInfoSetF(pErrInfo, rc, "Bad data header: uMagic=%#x (expected %#x), cbChunk=%#x (max %#RX64, align %u)",
3278 uBuf.Data.Chunk.uMagic, RTRIFFWAVEDATACHUNK_MAGIC,
3279 uBuf.Data.Chunk.cbChunk, pWaveFile->cbSamples, PDMAudioPropsFrameSize(&pWaveFile->Props));
3280 }
3281 else
3282 RTErrInfoSet(pErrInfo, rc, "Failed to read data header");
3283 }
3284 }
3285 else
3286 RTErrInfoSetF(pErrInfo, rc, "Bad file header: uMagic=%#x (vs. %#x), uFileType=%#x (vs %#x), uFmtMagic=%#x (vs %#x) cbFmtChunk=%#x (min %#x)",
3287 uBuf.Wave.Hdr.uMagic, RTRIFFHDR_MAGIC, uBuf.Wave.Hdr.uFileType, RTRIFF_FILE_TYPE_WAVE,
3288 uBuf.Wave.u.Fmt.Chunk.uMagic, RTRIFFWAVEFMT_MAGIC,
3289 uBuf.Wave.u.Fmt.Chunk.cbChunk, sizeof(uBuf.Wave.u.Fmt.Data));
3290 }
3291 else
3292 rc = RTErrInfoSet(pErrInfo, rc, "Failed to read file header");
3293 }
3294 else
3295 rc = RTErrInfoSet(pErrInfo, rc, "Failed to query file size");
3296
3297 RTFileClose(pWaveFile->hFile);
3298 pWaveFile->hFile = NIL_RTFILE;
3299 return rc;
3300}
3301
3302
3303/**
3304 * Creates a new wave file.
3305 *
3306 * @returns VBox status code.
3307 * @param pszFile The filename.
3308 * @param pProps The audio format properties.
3309 * @param pWaveFile The wave file structure to fill in on success.
3310 * @param pErrInfo Where to return addition error details on failure.
3311 */
3312int AudioTestWaveFileCreate(const char *pszFile, PCPDMAUDIOPCMPROPS pProps, PAUDIOTESTWAVEFILE pWaveFile, PRTERRINFO pErrInfo)
3313{
3314 /*
3315 * Construct the file header first (we'll do some input validation
3316 * here, so better do it before creating the file).
3317 */
3318 struct
3319 {
3320 RTRIFFHDR Hdr;
3321 RTRIFFWAVEFMTEXTCHUNK FmtExt;
3322 RTRIFFCHUNK Data;
3323 } FileHdr;
3324
3325 FileHdr.Hdr.uMagic = RTRIFFHDR_MAGIC;
3326 FileHdr.Hdr.cbFile = 0; /* need to update this later */
3327 FileHdr.Hdr.uFileType = RTRIFF_FILE_TYPE_WAVE;
3328 FileHdr.FmtExt.Chunk.uMagic = RTRIFFWAVEFMT_MAGIC;
3329 FileHdr.FmtExt.Chunk.cbChunk = sizeof(RTRIFFWAVEFMTEXTCHUNK) - sizeof(RTRIFFCHUNK);
3330 FileHdr.FmtExt.Data.Core.uFormatTag = RTRIFFWAVEFMT_TAG_EXTENSIBLE;
3331 FileHdr.FmtExt.Data.Core.cChannels = PDMAudioPropsChannels(pProps);
3332 FileHdr.FmtExt.Data.Core.uHz = PDMAudioPropsHz(pProps);
3333 FileHdr.FmtExt.Data.Core.cbRate = PDMAudioPropsFramesToBytes(pProps, PDMAudioPropsHz(pProps));
3334 FileHdr.FmtExt.Data.Core.cbFrame = PDMAudioPropsFrameSize(pProps);
3335 FileHdr.FmtExt.Data.Core.cBitsPerSample = PDMAudioPropsSampleBits(pProps);
3336 FileHdr.FmtExt.Data.cbExtra = sizeof(FileHdr.FmtExt.Data) - sizeof(FileHdr.FmtExt.Data.Core);
3337 FileHdr.FmtExt.Data.cValidBitsPerSample = PDMAudioPropsSampleBits(pProps);
3338 FileHdr.FmtExt.Data.fChannelMask = 0;
3339 for (uintptr_t idxCh = 0; idxCh < FileHdr.FmtExt.Data.Core.cChannels; idxCh++)
3340 {
3341 PDMAUDIOCHANNELID const idCh = (PDMAUDIOCHANNELID)pProps->aidChannels[idxCh];
3342 if ( idCh >= PDMAUDIOCHANNELID_FIRST_STANDARD
3343 && idCh < PDMAUDIOCHANNELID_END_STANDARD)
3344 {
3345 if (!(FileHdr.FmtExt.Data.fChannelMask & RT_BIT_32(idCh - PDMAUDIOCHANNELID_FIRST_STANDARD)))
3346 FileHdr.FmtExt.Data.fChannelMask |= RT_BIT_32(idCh - PDMAUDIOCHANNELID_FIRST_STANDARD);
3347 else
3348 return RTErrInfoSetF(pErrInfo, VERR_INVALID_PARAMETER, "Channel #%u repeats channel ID %d", idxCh, idCh);
3349 }
3350 else
3351 return RTErrInfoSetF(pErrInfo, VERR_INVALID_PARAMETER, "Invalid channel ID %d for channel #%u", idCh, idxCh);
3352 }
3353
3354 RTUUID UuidTmp;
3355 int rc = RTUuidFromStr(&UuidTmp, RTRIFFWAVEFMTEXT_SUBTYPE_PCM);
3356 AssertRCReturn(rc, rc);
3357 FileHdr.FmtExt.Data.SubFormat = UuidTmp; /* (64-bit field maybe unaligned) */
3358
3359 FileHdr.Data.uMagic = RTRIFFWAVEDATACHUNK_MAGIC;
3360 FileHdr.Data.cbChunk = 0; /* need to update this later */
3361
3362 /*
3363 * Create the file and write the header.
3364 */
3365 pWaveFile->hFile = NIL_RTFILE;
3366 rc = RTFileOpen(&pWaveFile->hFile, pszFile, RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
3367 if (RT_FAILURE(rc))
3368 return RTErrInfoSet(pErrInfo, rc, "RTFileOpen failed");
3369
3370 rc = RTFileWrite(pWaveFile->hFile, &FileHdr, sizeof(FileHdr), NULL);
3371 if (RT_SUCCESS(rc))
3372 {
3373 /*
3374 * Initialize the wave file structure.
3375 */
3376 pWaveFile->fReadMode = false;
3377 pWaveFile->offCur = 0;
3378 pWaveFile->offSamples = 0;
3379 pWaveFile->cbSamples = 0;
3380 pWaveFile->Props = *pProps;
3381 pWaveFile->offSamples = RTFileTell(pWaveFile->hFile);
3382 if (pWaveFile->offSamples != UINT32_MAX)
3383 {
3384 pWaveFile->u32Magic = AUDIOTESTWAVEFILE_MAGIC;
3385 return VINF_SUCCESS;
3386 }
3387 rc = RTErrInfoSet(pErrInfo, VERR_SEEK, "RTFileTell failed");
3388 }
3389 else
3390 RTErrInfoSet(pErrInfo, rc, "RTFileWrite failed writing header");
3391
3392 RTFileClose(pWaveFile->hFile);
3393 pWaveFile->hFile = NIL_RTFILE;
3394 pWaveFile->u32Magic = AUDIOTESTWAVEFILE_MAGIC_DEAD;
3395
3396 RTFileDelete(pszFile);
3397 return rc;
3398}
3399
3400
3401/**
3402 * Closes a wave file.
3403 */
3404int AudioTestWaveFileClose(PAUDIOTESTWAVEFILE pWaveFile)
3405{
3406 AssertReturn(pWaveFile->u32Magic == AUDIOTESTWAVEFILE_MAGIC, VERR_INVALID_MAGIC);
3407 int rcRet = VINF_SUCCESS;
3408 int rc;
3409
3410 /*
3411 * Update the size fields if writing.
3412 */
3413 if (!pWaveFile->fReadMode)
3414 {
3415 uint64_t cbFile = RTFileTell(pWaveFile->hFile);
3416 if (cbFile != UINT64_MAX)
3417 {
3418 uint32_t cbFile32 = cbFile - sizeof(RTRIFFCHUNK);
3419 rc = RTFileWriteAt(pWaveFile->hFile, RT_OFFSETOF(RTRIFFHDR, cbFile), &cbFile32, sizeof(cbFile32), NULL);
3420 AssertRCStmt(rc, rcRet = rc);
3421
3422 uint32_t cbSamples = cbFile - pWaveFile->offSamples;
3423 rc = RTFileWriteAt(pWaveFile->hFile, pWaveFile->offSamples - sizeof(uint32_t), &cbSamples, sizeof(cbSamples), NULL);
3424 AssertRCStmt(rc, rcRet = rc);
3425 }
3426 else
3427 rcRet = VERR_SEEK;
3428 }
3429
3430 /*
3431 * Close it.
3432 */
3433 rc = RTFileClose(pWaveFile->hFile);
3434 AssertRCStmt(rc, rcRet = rc);
3435
3436 pWaveFile->hFile = NIL_RTFILE;
3437 pWaveFile->u32Magic = AUDIOTESTWAVEFILE_MAGIC_DEAD;
3438 return rcRet;
3439}
3440
3441/**
3442 * Reads samples from a wave file.
3443 *
3444 * @returns VBox status code. See RTVfsFileRead for EOF status handling.
3445 * @param pWaveFile The file to read from.
3446 * @param pvBuf Where to put the samples.
3447 * @param cbBuf How much to read at most.
3448 * @param pcbRead Where to return the actual number of bytes read,
3449 * optional.
3450 */
3451int AudioTestWaveFileRead(PAUDIOTESTWAVEFILE pWaveFile, void *pvBuf, size_t cbBuf, size_t *pcbRead)
3452{
3453 AssertReturn(pWaveFile->u32Magic == AUDIOTESTWAVEFILE_MAGIC, VERR_INVALID_MAGIC);
3454 AssertReturn(pWaveFile->fReadMode, VERR_ACCESS_DENIED);
3455
3456 bool fEofAdjusted;
3457 if (pWaveFile->offCur + cbBuf <= pWaveFile->cbSamples)
3458 fEofAdjusted = false;
3459 else if (pcbRead)
3460 {
3461 fEofAdjusted = true;
3462 cbBuf = pWaveFile->cbSamples - pWaveFile->offCur;
3463 }
3464 else
3465 return VERR_EOF;
3466
3467 int rc = RTFileReadAt(pWaveFile->hFile, pWaveFile->offSamples + pWaveFile->offCur, pvBuf, cbBuf, pcbRead);
3468 if (RT_SUCCESS(rc))
3469 {
3470 if (pcbRead)
3471 {
3472 pWaveFile->offCur += (uint32_t)*pcbRead;
3473 if (fEofAdjusted || cbBuf > *pcbRead)
3474 rc = VINF_EOF;
3475 else if (!cbBuf && pWaveFile->offCur == pWaveFile->cbSamples)
3476 rc = VINF_EOF;
3477 }
3478 else
3479 pWaveFile->offCur += (uint32_t)cbBuf;
3480 }
3481 return rc;
3482}
3483
3484
3485/**
3486 * Writes samples to a wave file.
3487 *
3488 * @returns VBox status code.
3489 * @param pWaveFile The file to write to.
3490 * @param pvBuf The samples to write.
3491 * @param cbBuf How many bytes of samples to write.
3492 */
3493int AudioTestWaveFileWrite(PAUDIOTESTWAVEFILE pWaveFile, const void *pvBuf, size_t cbBuf)
3494{
3495 AssertReturn(pWaveFile->u32Magic == AUDIOTESTWAVEFILE_MAGIC, VERR_INVALID_MAGIC);
3496 AssertReturn(!pWaveFile->fReadMode, VERR_ACCESS_DENIED);
3497
3498 pWaveFile->cbSamples += (uint32_t)cbBuf;
3499 return RTFileWrite(pWaveFile->hFile, pvBuf, cbBuf, NULL);
3500}
3501
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