VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/DrvAudioCommon.cpp@ 73429

Last change on this file since 73429 was 73429, checked in by vboxsync, 7 years ago

Audio/Common: Added DrvAudioHlpStreamStatusCanRead() and DrvAudioHlpStreamStatusCanWrite().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 52.2 KB
Line 
1/* $Id: DrvAudioCommon.cpp 73429 2018-08-01 14:47:53Z vboxsync $ */
2/** @file
3 * Intermedia audio driver, common routines.
4 *
5 * These are also used in the drivers which are bound to Main, e.g. the VRDE
6 * or the video audio recording drivers.
7 */
8
9/*
10 * Copyright (C) 2006-2018 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 <iprt/alloc.h>
26#include <iprt/asm-math.h>
27#include <iprt/assert.h>
28#include <iprt/dir.h>
29#include <iprt/file.h>
30#include <iprt/string.h>
31#include <iprt/uuid.h>
32
33#define LOG_GROUP LOG_GROUP_DRV_AUDIO
34#include <VBox/log.h>
35
36#include <VBox/err.h>
37#include <VBox/vmm/pdmdev.h>
38#include <VBox/vmm/pdm.h>
39#include <VBox/vmm/mm.h>
40
41#include <ctype.h>
42#include <stdlib.h>
43
44#include "DrvAudio.h"
45#include "AudioMixBuffer.h"
46
47
48/*********************************************************************************************************************************
49* Structures and Typedefs *
50*********************************************************************************************************************************/
51/**
52 * Structure for building up a .WAV file header.
53 */
54typedef struct AUDIOWAVFILEHDR
55{
56 uint32_t u32RIFF;
57 uint32_t u32Size;
58 uint32_t u32WAVE;
59
60 uint32_t u32Fmt;
61 uint32_t u32Size1;
62 uint16_t u16AudioFormat;
63 uint16_t u16NumChannels;
64 uint32_t u32SampleRate;
65 uint32_t u32ByteRate;
66 uint16_t u16BlockAlign;
67 uint16_t u16BitsPerSample;
68
69 uint32_t u32ID2;
70 uint32_t u32Size2;
71} AUDIOWAVFILEHDR, *PAUDIOWAVFILEHDR;
72AssertCompileSize(AUDIOWAVFILEHDR, 11*4);
73
74/**
75 * Structure for keeeping the internal .WAV file data
76 */
77typedef struct AUDIOWAVFILEDATA
78{
79 /** The file header/footer. */
80 AUDIOWAVFILEHDR Hdr;
81} AUDIOWAVFILEDATA, *PAUDIOWAVFILEDATA;
82
83
84
85
86/**
87 * Retrieves the matching PDMAUDIOFMT for given bits + signing flag.
88 *
89 * @return IPRT status code.
90 * @return PDMAUDIOFMT Resulting audio format or PDMAUDIOFMT_INVALID if invalid.
91 * @param cBits Bits to retrieve audio format for.
92 * @param fSigned Signed flag for bits to retrieve audio format for.
93 */
94PDMAUDIOFMT DrvAudioAudFmtBitsToAudFmt(uint8_t cBits, bool fSigned)
95{
96 if (fSigned)
97 {
98 switch (cBits)
99 {
100 case 8: return PDMAUDIOFMT_S8;
101 case 16: return PDMAUDIOFMT_S16;
102 case 32: return PDMAUDIOFMT_S32;
103 default: break;
104 }
105 }
106 else
107 {
108 switch (cBits)
109 {
110 case 8: return PDMAUDIOFMT_U8;
111 case 16: return PDMAUDIOFMT_U16;
112 case 32: return PDMAUDIOFMT_U32;
113 default: break;
114 }
115 }
116
117 AssertMsgFailed(("Bogus audio bits %RU8\n", cBits));
118 return PDMAUDIOFMT_INVALID;
119}
120
121/**
122 * Clears a sample buffer by the given amount of audio frames with silence (according to the format
123 * given by the PCM properties).
124 *
125 * @param pPCMProps PCM properties to use for the buffer to clear.
126 * @param pvBuf Buffer to clear.
127 * @param cbBuf Size (in bytes) of the buffer.
128 * @param cFrames Number of audio frames to clear in the buffer.
129 */
130void DrvAudioHlpClearBuf(const PPDMAUDIOPCMPROPS pPCMProps, void *pvBuf, size_t cbBuf, uint32_t cFrames)
131{
132 AssertPtrReturnVoid(pPCMProps);
133 AssertPtrReturnVoid(pvBuf);
134
135 if (!cbBuf || !cFrames)
136 return;
137
138 Assert(pPCMProps->cBits);
139 size_t cbToClear = DrvAudioHlpFramesToBytes(cFrames, pPCMProps);
140 Assert(cbBuf >= cbToClear);
141
142 if (cbBuf < cbToClear)
143 cbToClear = cbBuf;
144
145 Log2Func(("pPCMProps=%p, pvBuf=%p, cFrames=%RU32, fSigned=%RTbool, cBits=%RU8\n",
146 pPCMProps, pvBuf, cFrames, pPCMProps->fSigned, pPCMProps->cBits));
147
148 Assert(pPCMProps->fSwapEndian == false); /** @todo Swapping Endianness is not supported yet. */
149
150 if (pPCMProps->fSigned)
151 {
152 RT_BZERO(pvBuf, cbToClear);
153 }
154 else
155 {
156 switch (pPCMProps->cBits)
157 {
158 case 8:
159 {
160 memset(pvBuf, 0x80, cbToClear);
161 break;
162 }
163
164 case 16:
165 {
166 uint16_t *p = (uint16_t *)pvBuf;
167 uint16_t s = 0x8000;
168
169 for (uint32_t i = 0; i < DrvAudioHlpBytesToFrames((uint32_t)cbToClear, pPCMProps); i++)
170 p[i] = s;
171
172 break;
173 }
174
175 /** @todo Add 24 bit? */
176
177 case 32:
178 {
179 uint32_t *p = (uint32_t *)pvBuf;
180 uint32_t s = 0x80000000;
181
182 for (uint32_t i = 0; i < DrvAudioHlpBytesToFrames((uint32_t)cbToClear, pPCMProps); i++)
183 p[i] = s;
184
185 break;
186 }
187
188 default:
189 {
190 AssertMsgFailed(("Invalid bits: %RU8\n", pPCMProps->cBits));
191 break;
192 }
193 }
194 }
195}
196
197/**
198 * Returns an unique file name for this given audio connector instance.
199 *
200 * @return Allocated file name. Must be free'd using RTStrFree().
201 * @param uInstance Driver / device instance.
202 * @param pszPath Path name of the file to delete. The path must exist.
203 * @param pszSuffix File name suffix to use.
204 */
205char *DrvAudioDbgGetFileNameA(uint8_t uInstance, const char *pszPath, const char *pszSuffix)
206{
207 char szFileName[64];
208 RTStrPrintf(szFileName, sizeof(szFileName), "drvAudio%RU8-%s", uInstance, pszSuffix);
209
210 char szFilePath[RTPATH_MAX];
211 int rc2 = RTStrCopy(szFilePath, sizeof(szFilePath), pszPath);
212 AssertRC(rc2);
213 rc2 = RTPathAppend(szFilePath, sizeof(szFilePath), szFileName);
214 AssertRC(rc2);
215
216 return RTStrDup(szFilePath);
217}
218
219/**
220 * Allocates an audio device.
221 *
222 * @returns Newly allocated audio device, or NULL if failed.
223 * @param cbData How much additional data (in bytes) should be allocated to provide
224 * a (backend) specific area to store additional data.
225 * Optional, can be 0.
226 */
227PPDMAUDIODEVICE DrvAudioHlpDeviceAlloc(size_t cbData)
228{
229 PPDMAUDIODEVICE pDev = (PPDMAUDIODEVICE)RTMemAllocZ(sizeof(PDMAUDIODEVICE));
230 if (!pDev)
231 return NULL;
232
233 if (cbData)
234 {
235 pDev->pvData = RTMemAllocZ(cbData);
236 if (!pDev->pvData)
237 {
238 RTMemFree(pDev);
239 return NULL;
240 }
241 }
242
243 pDev->cbData = cbData;
244
245 pDev->cMaxInputChannels = 0;
246 pDev->cMaxOutputChannels = 0;
247
248 return pDev;
249}
250
251/**
252 * Frees an audio device.
253 *
254 * @param pDev Device to free.
255 */
256void DrvAudioHlpDeviceFree(PPDMAUDIODEVICE pDev)
257{
258 if (!pDev)
259 return;
260
261 Assert(pDev->cRefCount == 0);
262
263 if (pDev->pvData)
264 {
265 Assert(pDev->cbData);
266
267 RTMemFree(pDev->pvData);
268 pDev->pvData = NULL;
269 }
270
271 RTMemFree(pDev);
272 pDev = NULL;
273}
274
275/**
276 * Duplicates an audio device entry.
277 *
278 * @returns Duplicated audio device entry on success, or NULL on failure.
279 * @param pDev Audio device entry to duplicate.
280 * @param fCopyUserData Whether to also copy the user data portion or not.
281 */
282PPDMAUDIODEVICE DrvAudioHlpDeviceDup(const PPDMAUDIODEVICE pDev, bool fCopyUserData)
283{
284 AssertPtrReturn(pDev, NULL);
285
286 PPDMAUDIODEVICE pDevDup = DrvAudioHlpDeviceAlloc(fCopyUserData ? pDev->cbData : 0);
287 if (pDevDup)
288 {
289 memcpy(pDevDup, pDev, sizeof(PDMAUDIODEVICE));
290
291 if ( fCopyUserData
292 && pDevDup->cbData)
293 {
294 memcpy(pDevDup->pvData, pDev->pvData, pDevDup->cbData);
295 }
296 else
297 {
298 pDevDup->cbData = 0;
299 pDevDup->pvData = NULL;
300 }
301 }
302
303 return pDevDup;
304}
305
306/**
307 * Initializes an audio device enumeration structure.
308 *
309 * @returns IPRT status code.
310 * @param pDevEnm Device enumeration to initialize.
311 */
312int DrvAudioHlpDeviceEnumInit(PPDMAUDIODEVICEENUM pDevEnm)
313{
314 AssertPtrReturn(pDevEnm, VERR_INVALID_POINTER);
315
316 RTListInit(&pDevEnm->lstDevices);
317 pDevEnm->cDevices = 0;
318
319 return VINF_SUCCESS;
320}
321
322/**
323 * Frees audio device enumeration data.
324 *
325 * @param pDevEnm Device enumeration to destroy.
326 */
327void DrvAudioHlpDeviceEnumFree(PPDMAUDIODEVICEENUM pDevEnm)
328{
329 if (!pDevEnm)
330 return;
331
332 PPDMAUDIODEVICE pDev, pDevNext;
333 RTListForEachSafe(&pDevEnm->lstDevices, pDev, pDevNext, PDMAUDIODEVICE, Node)
334 {
335 RTListNodeRemove(&pDev->Node);
336
337 DrvAudioHlpDeviceFree(pDev);
338
339 pDevEnm->cDevices--;
340 }
341
342 /* Sanity. */
343 Assert(RTListIsEmpty(&pDevEnm->lstDevices));
344 Assert(pDevEnm->cDevices == 0);
345}
346
347/**
348 * Adds an audio device to a device enumeration.
349 *
350 * @return IPRT status code.
351 * @param pDevEnm Device enumeration to add device to.
352 * @param pDev Device to add. The pointer will be owned by the device enumeration then.
353 */
354int DrvAudioHlpDeviceEnumAdd(PPDMAUDIODEVICEENUM pDevEnm, PPDMAUDIODEVICE pDev)
355{
356 AssertPtrReturn(pDevEnm, VERR_INVALID_POINTER);
357 AssertPtrReturn(pDev, VERR_INVALID_POINTER);
358
359 RTListAppend(&pDevEnm->lstDevices, &pDev->Node);
360 pDevEnm->cDevices++;
361
362 return VINF_SUCCESS;
363}
364
365/**
366 * Duplicates a device enumeration.
367 *
368 * @returns Duplicated device enumeration, or NULL on failure.
369 * Must be free'd with DrvAudioHlpDeviceEnumFree().
370 * @param pDevEnm Device enumeration to duplicate.
371 */
372PPDMAUDIODEVICEENUM DrvAudioHlpDeviceEnumDup(const PPDMAUDIODEVICEENUM pDevEnm)
373{
374 AssertPtrReturn(pDevEnm, NULL);
375
376 PPDMAUDIODEVICEENUM pDevEnmDup = (PPDMAUDIODEVICEENUM)RTMemAlloc(sizeof(PDMAUDIODEVICEENUM));
377 if (!pDevEnmDup)
378 return NULL;
379
380 int rc2 = DrvAudioHlpDeviceEnumInit(pDevEnmDup);
381 AssertRC(rc2);
382
383 PPDMAUDIODEVICE pDev;
384 RTListForEach(&pDevEnm->lstDevices, pDev, PDMAUDIODEVICE, Node)
385 {
386 PPDMAUDIODEVICE pDevDup = DrvAudioHlpDeviceDup(pDev, true /* fCopyUserData */);
387 if (!pDevDup)
388 {
389 rc2 = VERR_NO_MEMORY;
390 break;
391 }
392
393 rc2 = DrvAudioHlpDeviceEnumAdd(pDevEnmDup, pDevDup);
394 if (RT_FAILURE(rc2))
395 {
396 DrvAudioHlpDeviceFree(pDevDup);
397 break;
398 }
399 }
400
401 if (RT_FAILURE(rc2))
402 {
403 DrvAudioHlpDeviceEnumFree(pDevEnmDup);
404 pDevEnmDup = NULL;
405 }
406
407 return pDevEnmDup;
408}
409
410/**
411 * Copies device enumeration entries from the source to the destination enumeration.
412 *
413 * @returns IPRT status code.
414 * @param pDstDevEnm Destination enumeration to store enumeration entries into.
415 * @param pSrcDevEnm Source enumeration to use.
416 * @param enmUsage Which entries to copy. Specify PDMAUDIODIR_ANY to copy all entries.
417 * @param fCopyUserData Whether to also copy the user data portion or not.
418 */
419int DrvAudioHlpDeviceEnumCopyEx(PPDMAUDIODEVICEENUM pDstDevEnm, const PPDMAUDIODEVICEENUM pSrcDevEnm,
420 PDMAUDIODIR enmUsage, bool fCopyUserData)
421{
422 AssertPtrReturn(pDstDevEnm, VERR_INVALID_POINTER);
423 AssertPtrReturn(pSrcDevEnm, VERR_INVALID_POINTER);
424
425 int rc = VINF_SUCCESS;
426
427 PPDMAUDIODEVICE pSrcDev;
428 RTListForEach(&pSrcDevEnm->lstDevices, pSrcDev, PDMAUDIODEVICE, Node)
429 {
430 if ( enmUsage != PDMAUDIODIR_ANY
431 && enmUsage != pSrcDev->enmUsage)
432 {
433 continue;
434 }
435
436 PPDMAUDIODEVICE pDstDev = DrvAudioHlpDeviceDup(pSrcDev, fCopyUserData);
437 if (!pDstDev)
438 {
439 rc = VERR_NO_MEMORY;
440 break;
441 }
442
443 rc = DrvAudioHlpDeviceEnumAdd(pDstDevEnm, pDstDev);
444 if (RT_FAILURE(rc))
445 break;
446 }
447
448 return rc;
449}
450
451/**
452 * Copies all device enumeration entries from the source to the destination enumeration.
453 *
454 * Note: Does *not* copy the user-specific data assigned to a device enumeration entry.
455 * To do so, use DrvAudioHlpDeviceEnumCopyEx().
456 *
457 * @returns IPRT status code.
458 * @param pDstDevEnm Destination enumeration to store enumeration entries into.
459 * @param pSrcDevEnm Source enumeration to use.
460 */
461int DrvAudioHlpDeviceEnumCopy(PPDMAUDIODEVICEENUM pDstDevEnm, const PPDMAUDIODEVICEENUM pSrcDevEnm)
462{
463 return DrvAudioHlpDeviceEnumCopyEx(pDstDevEnm, pSrcDevEnm, PDMAUDIODIR_ANY, false /* fCopyUserData */);
464}
465
466/**
467 * Returns the default device of a given device enumeration.
468 * This assumes that only one default device per usage is set.
469 *
470 * @returns Default device if found, or NULL if none found.
471 * @param pDevEnm Device enumeration to get default device for.
472 * @param enmUsage Usage to get default device for.
473 */
474PPDMAUDIODEVICE DrvAudioHlpDeviceEnumGetDefaultDevice(const PPDMAUDIODEVICEENUM pDevEnm, PDMAUDIODIR enmUsage)
475{
476 AssertPtrReturn(pDevEnm, NULL);
477
478 PPDMAUDIODEVICE pDev;
479 RTListForEach(&pDevEnm->lstDevices, pDev, PDMAUDIODEVICE, Node)
480 {
481 if (enmUsage != PDMAUDIODIR_ANY)
482 {
483 if (enmUsage != pDev->enmUsage) /* Wrong usage? Skip. */
484 continue;
485 }
486
487 if (pDev->fFlags & PDMAUDIODEV_FLAGS_DEFAULT)
488 return pDev;
489 }
490
491 return NULL;
492}
493
494/**
495 * Logs an audio device enumeration.
496 *
497 * @param pszDesc Logging description.
498 * @param pDevEnm Device enumeration to log.
499 */
500void DrvAudioHlpDeviceEnumPrint(const char *pszDesc, const PPDMAUDIODEVICEENUM pDevEnm)
501{
502 AssertPtrReturnVoid(pszDesc);
503 AssertPtrReturnVoid(pDevEnm);
504
505 LogFunc(("%s: %RU16 devices\n", pszDesc, pDevEnm->cDevices));
506
507 PPDMAUDIODEVICE pDev;
508 RTListForEach(&pDevEnm->lstDevices, pDev, PDMAUDIODEVICE, Node)
509 {
510 char *pszFlags = DrvAudioHlpAudDevFlagsToStrA(pDev->fFlags);
511
512 LogFunc(("Device '%s':\n", pDev->szName));
513 LogFunc(("\tUsage = %s\n", DrvAudioHlpAudDirToStr(pDev->enmUsage)));
514 LogFunc(("\tFlags = %s\n", pszFlags ? pszFlags : "<NONE>"));
515 LogFunc(("\tInput channels = %RU8\n", pDev->cMaxInputChannels));
516 LogFunc(("\tOutput channels = %RU8\n", pDev->cMaxOutputChannels));
517 LogFunc(("\tData = %p (%zu bytes)\n", pDev->pvData, pDev->cbData));
518
519 if (pszFlags)
520 RTStrFree(pszFlags);
521 }
522}
523
524/**
525 * Converts an audio direction to a string.
526 *
527 * @returns Stringified audio direction, or "Unknown", if not found.
528 * @param enmDir Audio direction to convert.
529 */
530const char *DrvAudioHlpAudDirToStr(PDMAUDIODIR enmDir)
531{
532 switch (enmDir)
533 {
534 case PDMAUDIODIR_UNKNOWN: return "Unknown";
535 case PDMAUDIODIR_IN: return "Input";
536 case PDMAUDIODIR_OUT: return "Output";
537 case PDMAUDIODIR_ANY: return "Duplex";
538 default: break;
539 }
540
541 AssertMsgFailed(("Invalid audio direction %ld\n", enmDir));
542 return "Unknown";
543}
544
545/**
546 * Converts an audio mixer control to a string.
547 *
548 * @returns Stringified audio mixer control or "Unknown", if not found.
549 * @param enmMixerCtl Audio mixer control to convert.
550 */
551const char *DrvAudioHlpAudMixerCtlToStr(PDMAUDIOMIXERCTL enmMixerCtl)
552{
553 switch (enmMixerCtl)
554 {
555 case PDMAUDIOMIXERCTL_VOLUME_MASTER: return "Master Volume";
556 case PDMAUDIOMIXERCTL_FRONT: return "Front";
557 case PDMAUDIOMIXERCTL_CENTER_LFE: return "Center / LFE";
558 case PDMAUDIOMIXERCTL_REAR: return "Rear";
559 case PDMAUDIOMIXERCTL_LINE_IN: return "Line-In";
560 case PDMAUDIOMIXERCTL_MIC_IN: return "Microphone-In";
561 default: break;
562 }
563
564 AssertMsgFailed(("Invalid mixer control %ld\n", enmMixerCtl));
565 return "Unknown";
566}
567
568/**
569 * Converts an audio device flags to a string.
570 *
571 * @returns Stringified audio flags. Must be free'd with RTStrFree().
572 * NULL if no flags set.
573 * @param fFlags Audio flags to convert.
574 */
575char *DrvAudioHlpAudDevFlagsToStrA(PDMAUDIODEVFLAG fFlags)
576{
577#define APPEND_FLAG_TO_STR(_aFlag) \
578 if (fFlags & PDMAUDIODEV_FLAGS_##_aFlag) \
579 { \
580 if (pszFlags) \
581 { \
582 rc2 = RTStrAAppend(&pszFlags, " "); \
583 if (RT_FAILURE(rc2)) \
584 break; \
585 } \
586 \
587 rc2 = RTStrAAppend(&pszFlags, #_aFlag); \
588 if (RT_FAILURE(rc2)) \
589 break; \
590 } \
591
592 char *pszFlags = NULL;
593 int rc2 = VINF_SUCCESS;
594
595 do
596 {
597 APPEND_FLAG_TO_STR(DEFAULT);
598 APPEND_FLAG_TO_STR(HOTPLUG);
599 APPEND_FLAG_TO_STR(BUGGY);
600 APPEND_FLAG_TO_STR(IGNORE);
601 APPEND_FLAG_TO_STR(LOCKED);
602 APPEND_FLAG_TO_STR(DEAD);
603
604 } while (0);
605
606 if (!pszFlags)
607 rc2 = RTStrAAppend(&pszFlags, "NONE");
608
609 if ( RT_FAILURE(rc2)
610 && pszFlags)
611 {
612 RTStrFree(pszFlags);
613 pszFlags = NULL;
614 }
615
616#undef APPEND_FLAG_TO_STR
617
618 return pszFlags;
619}
620
621/**
622 * Converts a playback destination enumeration to a string.
623 *
624 * @returns Stringified playback destination, or "Unknown", if not found.
625 * @param enmPlaybackDst Playback destination to convert.
626 */
627const char *DrvAudioHlpPlaybackDstToStr(const PDMAUDIOPLAYBACKDEST enmPlaybackDst)
628{
629 switch (enmPlaybackDst)
630 {
631 case PDMAUDIOPLAYBACKDEST_UNKNOWN: return "Unknown";
632 case PDMAUDIOPLAYBACKDEST_FRONT: return "Front";
633 case PDMAUDIOPLAYBACKDEST_CENTER_LFE: return "Center / LFE";
634 case PDMAUDIOPLAYBACKDEST_REAR: return "Rear";
635 default:
636 break;
637 }
638
639 AssertMsgFailed(("Invalid playback destination %ld\n", enmPlaybackDst));
640 return "Unknown";
641}
642
643/**
644 * Converts a recording source enumeration to a string.
645 *
646 * @returns Stringified recording source, or "Unknown", if not found.
647 * @param enmRecSrc Recording source to convert.
648 */
649const char *DrvAudioHlpRecSrcToStr(const PDMAUDIORECSOURCE enmRecSrc)
650{
651 switch (enmRecSrc)
652 {
653 case PDMAUDIORECSOURCE_UNKNOWN: return "Unknown";
654 case PDMAUDIORECSOURCE_MIC: return "Microphone In";
655 case PDMAUDIORECSOURCE_CD: return "CD";
656 case PDMAUDIORECSOURCE_VIDEO: return "Video";
657 case PDMAUDIORECSOURCE_AUX: return "AUX";
658 case PDMAUDIORECSOURCE_LINE: return "Line In";
659 case PDMAUDIORECSOURCE_PHONE: return "Phone";
660 default:
661 break;
662 }
663
664 AssertMsgFailed(("Invalid recording source %ld\n", enmRecSrc));
665 return "Unknown";
666}
667
668/**
669 * Returns wether the given audio format has signed bits or not.
670 *
671 * @return IPRT status code.
672 * @return bool @c true for signed bits, @c false for unsigned.
673 * @param enmFmt Audio format to retrieve value for.
674 */
675bool DrvAudioHlpAudFmtIsSigned(PDMAUDIOFMT enmFmt)
676{
677 switch (enmFmt)
678 {
679 case PDMAUDIOFMT_S8:
680 case PDMAUDIOFMT_S16:
681 case PDMAUDIOFMT_S32:
682 return true;
683
684 case PDMAUDIOFMT_U8:
685 case PDMAUDIOFMT_U16:
686 case PDMAUDIOFMT_U32:
687 return false;
688
689 default:
690 break;
691 }
692
693 AssertMsgFailed(("Bogus audio format %ld\n", enmFmt));
694 return false;
695}
696
697/**
698 * Returns the bits of a given audio format.
699 *
700 * @return IPRT status code.
701 * @return uint8_t Bits of audio format.
702 * @param enmFmt Audio format to retrieve value for.
703 */
704uint8_t DrvAudioHlpAudFmtToBits(PDMAUDIOFMT enmFmt)
705{
706 switch (enmFmt)
707 {
708 case PDMAUDIOFMT_S8:
709 case PDMAUDIOFMT_U8:
710 return 8;
711
712 case PDMAUDIOFMT_U16:
713 case PDMAUDIOFMT_S16:
714 return 16;
715
716 case PDMAUDIOFMT_U32:
717 case PDMAUDIOFMT_S32:
718 return 32;
719
720 default:
721 break;
722 }
723
724 AssertMsgFailed(("Bogus audio format %ld\n", enmFmt));
725 return 0;
726}
727
728/**
729 * Converts an audio format to a string.
730 *
731 * @returns Stringified audio format, or "Unknown", if not found.
732 * @param enmFmt Audio format to convert.
733 */
734const char *DrvAudioHlpAudFmtToStr(PDMAUDIOFMT enmFmt)
735{
736 switch (enmFmt)
737 {
738 case PDMAUDIOFMT_U8:
739 return "U8";
740
741 case PDMAUDIOFMT_U16:
742 return "U16";
743
744 case PDMAUDIOFMT_U32:
745 return "U32";
746
747 case PDMAUDIOFMT_S8:
748 return "S8";
749
750 case PDMAUDIOFMT_S16:
751 return "S16";
752
753 case PDMAUDIOFMT_S32:
754 return "S32";
755
756 default:
757 break;
758 }
759
760 AssertMsgFailed(("Bogus audio format %ld\n", enmFmt));
761 return "Unknown";
762}
763
764/**
765 * Converts a given string to an audio format.
766 *
767 * @returns Audio format for the given string, or PDMAUDIOFMT_INVALID if not found.
768 * @param pszFmt String to convert to an audio format.
769 */
770PDMAUDIOFMT DrvAudioHlpStrToAudFmt(const char *pszFmt)
771{
772 AssertPtrReturn(pszFmt, PDMAUDIOFMT_INVALID);
773
774 if (!RTStrICmp(pszFmt, "u8"))
775 return PDMAUDIOFMT_U8;
776 else if (!RTStrICmp(pszFmt, "u16"))
777 return PDMAUDIOFMT_U16;
778 else if (!RTStrICmp(pszFmt, "u32"))
779 return PDMAUDIOFMT_U32;
780 else if (!RTStrICmp(pszFmt, "s8"))
781 return PDMAUDIOFMT_S8;
782 else if (!RTStrICmp(pszFmt, "s16"))
783 return PDMAUDIOFMT_S16;
784 else if (!RTStrICmp(pszFmt, "s32"))
785 return PDMAUDIOFMT_S32;
786
787 AssertMsgFailed(("Invalid audio format '%s'\n", pszFmt));
788 return PDMAUDIOFMT_INVALID;
789}
790
791/**
792 * Checks whether two given PCM properties are equal.
793 *
794 * @returns @c true if equal, @c false if not.
795 * @param pProps1 First properties to compare.
796 * @param pProps2 Second properties to compare.
797 */
798bool DrvAudioHlpPCMPropsAreEqual(const PPDMAUDIOPCMPROPS pProps1, const PPDMAUDIOPCMPROPS pProps2)
799{
800 AssertPtrReturn(pProps1, false);
801 AssertPtrReturn(pProps2, false);
802
803 if (pProps1 == pProps2) /* If the pointers match, take a shortcut. */
804 return true;
805
806 return pProps1->uHz == pProps2->uHz
807 && pProps1->cChannels == pProps2->cChannels
808 && pProps1->cBits == pProps2->cBits
809 && pProps1->fSigned == pProps2->fSigned
810 && pProps1->fSwapEndian == pProps2->fSwapEndian;
811}
812
813/**
814 * Checks whether given PCM properties are valid or not.
815 *
816 * Returns @c true if properties are valid, @c false if not.
817 * @param pProps PCM properties to check.
818 */
819bool DrvAudioHlpPCMPropsAreValid(const PPDMAUDIOPCMPROPS pProps)
820{
821 AssertPtrReturn(pProps, false);
822
823 /* Minimum 1 channel (mono), maximum 7.1 (= 8) channels. */
824 bool fValid = ( pProps->cChannels >= 1
825 && pProps->cChannels <= 8);
826
827 if (fValid)
828 {
829 switch (pProps->cBits)
830 {
831 case 8:
832 case 16:
833 /** @todo Do we need support for 24-bit samples? */
834 case 32:
835 break;
836 default:
837 fValid = false;
838 break;
839 }
840 }
841
842 if (!fValid)
843 return false;
844
845 fValid &= pProps->uHz > 0;
846 fValid &= pProps->cShift == PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(pProps->cBits, pProps->cChannels);
847 fValid &= pProps->fSwapEndian == false; /** @todo Handling Big Endian audio data is not supported yet. */
848
849 return fValid;
850}
851
852/**
853 * Checks whether the given PCM properties are equal with the given
854 * stream configuration.
855 *
856 * @returns @c true if equal, @c false if not.
857 * @param pProps PCM properties to compare.
858 * @param pCfg Stream configuration to compare.
859 */
860bool DrvAudioHlpPCMPropsAreEqual(const PPDMAUDIOPCMPROPS pProps, const PPDMAUDIOSTREAMCFG pCfg)
861{
862 AssertPtrReturn(pProps, false);
863 AssertPtrReturn(pCfg, false);
864
865 return DrvAudioHlpPCMPropsAreEqual(pProps, &pCfg->Props);
866}
867
868/**
869 * Returns the bytes per frame for given PCM properties.
870 *
871 * @return Bytes per (audio) frame.
872 * @param pProps PCM properties to retrieve bytes per frame for.
873 */
874uint32_t DrvAudioHlpPCMPropsBytesPerFrame(const PPDMAUDIOPCMPROPS pProps)
875{
876 return (pProps->cBits / 8) * pProps->cChannels;
877}
878
879/**
880 * Prints PCM properties to the debug log.
881 *
882 * @param pProps Stream configuration to log.
883 */
884void DrvAudioHlpPCMPropsPrint(const PPDMAUDIOPCMPROPS pProps)
885{
886 AssertPtrReturnVoid(pProps);
887
888 Log(("uHz=%RU32, cChannels=%RU8, cBits=%RU8%s",
889 pProps->uHz, pProps->cChannels, pProps->cBits, pProps->fSigned ? "S" : "U"));
890}
891
892/**
893 * Converts PCM properties to a audio stream configuration.
894 *
895 * @return IPRT status code.
896 * @param pProps Pointer to PCM properties to convert.
897 * @param pCfg Pointer to audio stream configuration to store result into.
898 */
899int DrvAudioHlpPCMPropsToStreamCfg(const PPDMAUDIOPCMPROPS pProps, PPDMAUDIOSTREAMCFG pCfg)
900{
901 AssertPtrReturn(pProps, VERR_INVALID_POINTER);
902 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
903
904 memcpy(&pCfg->Props, pProps, sizeof(PDMAUDIOPCMPROPS));
905 return VINF_SUCCESS;
906}
907
908/**
909 * Checks whether a given stream configuration is valid or not.
910 *
911 * Returns @c true if configuration is valid, @c false if not.
912 * @param pCfg Stream configuration to check.
913 */
914bool DrvAudioHlpStreamCfgIsValid(const PPDMAUDIOSTREAMCFG pCfg)
915{
916 AssertPtrReturn(pCfg, false);
917
918 bool fValid = ( pCfg->enmDir == PDMAUDIODIR_IN
919 || pCfg->enmDir == PDMAUDIODIR_OUT);
920
921 fValid &= ( pCfg->enmLayout == PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED
922 || pCfg->enmLayout == PDMAUDIOSTREAMLAYOUT_RAW);
923
924 if (fValid)
925 fValid = DrvAudioHlpPCMPropsAreValid(&pCfg->Props);
926
927 return fValid;
928}
929
930/**
931 * Frees an allocated audio stream configuration.
932 *
933 * @param pCfg Audio stream configuration to free.
934 */
935void DrvAudioHlpStreamCfgFree(PPDMAUDIOSTREAMCFG pCfg)
936{
937 if (pCfg)
938 {
939 RTMemFree(pCfg);
940 pCfg = NULL;
941 }
942}
943
944/**
945 * Copies a source stream configuration to a destination stream configuration.
946 *
947 * @returns IPRT status code.
948 * @param pDstCfg Destination stream configuration to copy source to.
949 * @param pSrcCfg Source stream configuration to copy to destination.
950 */
951int DrvAudioHlpStreamCfgCopy(PPDMAUDIOSTREAMCFG pDstCfg, const PPDMAUDIOSTREAMCFG pSrcCfg)
952{
953 AssertPtrReturn(pDstCfg, VERR_INVALID_POINTER);
954 AssertPtrReturn(pSrcCfg, VERR_INVALID_POINTER);
955
956#ifdef VBOX_STRICT
957 if (!DrvAudioHlpStreamCfgIsValid(pSrcCfg))
958 {
959 AssertMsgFailed(("Stream config '%s' (%p) is invalid\n", pSrcCfg->szName, pSrcCfg));
960 return VERR_INVALID_PARAMETER;
961 }
962#endif
963
964 memcpy(pDstCfg, pSrcCfg, sizeof(PDMAUDIOSTREAMCFG));
965
966 return VINF_SUCCESS;
967}
968
969/**
970 * Duplicates an audio stream configuration.
971 * Must be free'd with DrvAudioHlpStreamCfgFree().
972 *
973 * @return Duplicates audio stream configuration on success, or NULL on failure.
974 * @param pCfg Audio stream configuration to duplicate.
975 */
976PPDMAUDIOSTREAMCFG DrvAudioHlpStreamCfgDup(const PPDMAUDIOSTREAMCFG pCfg)
977{
978 AssertPtrReturn(pCfg, NULL);
979
980 PPDMAUDIOSTREAMCFG pDst = (PPDMAUDIOSTREAMCFG)RTMemAllocZ(sizeof(PDMAUDIOSTREAMCFG));
981 if (!pDst)
982 return NULL;
983
984 int rc2 = DrvAudioHlpStreamCfgCopy(pDst, pCfg);
985 if (RT_FAILURE(rc2))
986 {
987 DrvAudioHlpStreamCfgFree(pDst);
988 pDst = NULL;
989 }
990
991 AssertPtr(pDst);
992 return pDst;
993}
994
995/**
996 * Prints an audio stream configuration to the debug log.
997 *
998 * @param pCfg Stream configuration to log.
999 */
1000void DrvAudioHlpStreamCfgPrint(const PPDMAUDIOSTREAMCFG pCfg)
1001{
1002 if (!pCfg)
1003 return;
1004
1005 LogFunc(("szName=%s, enmDir=%RU32 (uHz=%RU32, cBits=%RU8%s, cChannels=%RU8)\n",
1006 pCfg->szName, pCfg->enmDir,
1007 pCfg->Props.uHz, pCfg->Props.cBits, pCfg->Props.fSigned ? "S" : "U", pCfg->Props.cChannels));
1008}
1009
1010/**
1011 * Converts a stream command to a string.
1012 *
1013 * @returns Stringified stream command, or "Unknown", if not found.
1014 * @param enmCmd Stream command to convert.
1015 */
1016const char *DrvAudioHlpStreamCmdToStr(PDMAUDIOSTREAMCMD enmCmd)
1017{
1018 switch (enmCmd)
1019 {
1020 case PDMAUDIOSTREAMCMD_UNKNOWN: return "Unknown";
1021 case PDMAUDIOSTREAMCMD_ENABLE: return "Enable";
1022 case PDMAUDIOSTREAMCMD_DISABLE: return "Disable";
1023 case PDMAUDIOSTREAMCMD_PAUSE: return "Pause";
1024 case PDMAUDIOSTREAMCMD_RESUME: return "Resume";
1025 case PDMAUDIOSTREAMCMD_DRAIN: return "Drain";
1026 case PDMAUDIOSTREAMCMD_DROP: return "Drop";
1027 default: break;
1028 }
1029
1030 AssertMsgFailed(("Invalid stream command %ld\n", enmCmd));
1031 return "Unknown";
1032}
1033
1034/**
1035 * Returns @c true if the given stream status indicates a can-be-read-from stream,
1036 * @c false if not.
1037 *
1038 * @returns @c true if ready to be read from, @c if not.
1039 * @param enmStatus Stream status to evaluate.
1040 */
1041bool DrvAudioHlpStreamStatusCanRead(PDMAUDIOSTREAMSTS enmStatus)
1042{
1043 AssertReturn(enmStatus & PDMAUDIOSTREAMSTS_VALID_MASK, false);
1044
1045 return enmStatus & PDMAUDIOSTREAMSTS_FLAG_INITIALIZED
1046 && enmStatus & PDMAUDIOSTREAMSTS_FLAG_ENABLED
1047 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PAUSED)
1048 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PENDING_REINIT);
1049}
1050
1051/**
1052 * Returns @c true if the given stream status indicates a can-be-written-to stream,
1053 * @c false if not.
1054 *
1055 * @returns @c true if ready to be written to, @c if not.
1056 * @param enmStatus Stream status to evaluate.
1057 */
1058bool DrvAudioHlpStreamStatusCanWrite(PDMAUDIOSTREAMSTS enmStatus)
1059{
1060 AssertReturn(enmStatus & PDMAUDIOSTREAMSTS_VALID_MASK, false);
1061
1062 return enmStatus & PDMAUDIOSTREAMSTS_FLAG_INITIALIZED
1063 && enmStatus & PDMAUDIOSTREAMSTS_FLAG_ENABLED
1064 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PAUSED)
1065 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PENDING_DISABLE)
1066 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PENDING_REINIT);
1067}
1068
1069/**
1070 * Returns @c true if the given stream status indicates a ready-to-operate stream,
1071 * @c false if not.
1072 *
1073 * @returns @c true if ready to operate, @c if not.
1074 * @param enmStatus Stream status to evaluate.
1075 */
1076bool DrvAudioHlpStreamStatusIsReady(PDMAUDIOSTREAMSTS enmStatus)
1077{
1078 AssertReturn(enmStatus & PDMAUDIOSTREAMSTS_VALID_MASK, false);
1079
1080 return enmStatus & PDMAUDIOSTREAMSTS_FLAG_INITIALIZED
1081 && enmStatus & PDMAUDIOSTREAMSTS_FLAG_ENABLED
1082 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PENDING_REINIT);
1083}
1084
1085/**
1086 * Calculates the audio bit rate of the given bits per sample, the Hz and the number
1087 * of audio channels.
1088 *
1089 * Divide the result by 8 to get the byte rate.
1090 *
1091 * @returns The calculated bit rate.
1092 * @param cBits Number of bits per sample.
1093 * @param uHz Hz (Hertz) rate.
1094 * @param cChannels Number of audio channels.
1095 */
1096uint32_t DrvAudioHlpCalcBitrate(uint8_t cBits, uint32_t uHz, uint8_t cChannels)
1097{
1098 return (cBits * uHz * cChannels);
1099}
1100
1101/**
1102 * Calculates the audio bit rate out of a given audio stream configuration.
1103 *
1104 * Divide the result by 8 to get the byte rate.
1105 *
1106 * @returns The calculated bit rate.
1107 * @param pProps PCM properties to calculate bitrate for.
1108 *
1109 * @remark
1110 */
1111uint32_t DrvAudioHlpCalcBitrate(const PPDMAUDIOPCMPROPS pProps)
1112{
1113 return DrvAudioHlpCalcBitrate(pProps->cBits, pProps->uHz, pProps->cChannels);
1114}
1115
1116/**
1117 * Aligns the given byte amount to the given PCM properties and returns the aligned
1118 * size.
1119 *
1120 * @return Aligned size (in bytes).
1121 * @param cbSize Size (in bytes) to align.
1122 * @param pProps PCM properties to align size to.
1123 */
1124uint32_t DrvAudioHlpBytesAlign(uint32_t cbSize, const PPDMAUDIOPCMPROPS pProps)
1125{
1126 AssertPtrReturn(pProps, 0);
1127
1128 if (!cbSize)
1129 return 0;
1130
1131 const uint32_t cbFrameSize = DrvAudioHlpPCMPropsBytesPerFrame(pProps);
1132 return (cbSize / cbFrameSize) * cbFrameSize;
1133}
1134
1135/**
1136 * Returns if the the given size is properly aligned to the given PCM properties.
1137 *
1138 * @return @c true if properly aligned, @c false if not.
1139 * @param cbSize Size (in bytes) to check alignment for.
1140 * @param pProps PCM properties to use for checking the alignment.
1141 */
1142bool DrvAudioHlpBytesIsAligned(uint32_t cbSize, const PPDMAUDIOPCMPROPS pProps)
1143{
1144 AssertPtrReturn(pProps, 0);
1145
1146 if (!cbSize)
1147 return true;
1148
1149 return (cbSize % DrvAudioHlpPCMPropsBytesPerFrame(pProps) == 0);
1150}
1151
1152/**
1153 * Returns the number of audio frames for a given amount of bytes.
1154 *
1155 * @return Calculated audio frames for given bytes.
1156 * @param cbBytes Bytes to convert to audio frames.
1157 * @param pProps PCM properties to calulate frames for.
1158 */
1159uint32_t DrvAudioHlpBytesToFrames(uint32_t cbBytes, const PPDMAUDIOPCMPROPS pProps)
1160{
1161 AssertPtrReturn(pProps, 0);
1162
1163 return cbBytes / ((pProps->cBits / 8) * pProps->cChannels);
1164}
1165
1166/**
1167 * Returns the time (in ms) for given byte amount and PCM properties.
1168 *
1169 * @return uint64_t Calculated time (in ms).
1170 * @param cbBytes Amount of bytes to calculate time for.
1171 * @param pProps PCM properties to calculate amount of bytes for.
1172 */
1173uint64_t DrvAudioHlpBytesToMilli(uint32_t cbBytes, const PPDMAUDIOPCMPROPS pProps)
1174{
1175 AssertPtrReturn(pProps, 0);
1176
1177 if (!cbBytes)
1178 return 0;
1179
1180 const uint64_t cbBytesPerSec = (pProps->cBits / 8) * pProps->cChannels * pProps->uHz;
1181 const double dbBytesPerMs = (double)cbBytesPerSec / (double)RT_MS_1SEC;
1182 Assert(dbBytesPerMs >= 0.0f);
1183 if (!dbBytesPerMs) /* Prevent division by zero. */
1184 return 0;
1185
1186 return (double)cbBytes / (double)dbBytesPerMs;
1187}
1188
1189/**
1190 * Returns the time (in ns) for given byte amount and PCM properties.
1191 *
1192 * @return uint64_t Calculated time (in ns).
1193 * @param cbBytes Amount of bytes to calculate time for.
1194 * @param pProps PCM properties to calculate amount of bytes for.
1195 */
1196uint64_t DrvAudioHlpBytesToNano(uint32_t cbBytes, const PPDMAUDIOPCMPROPS pProps)
1197{
1198 AssertPtrReturn(pProps, 0);
1199
1200 if (!cbBytes)
1201 return 0;
1202
1203 const double dbBytesPerMs = ((pProps->cBits / 8) * pProps->cChannels * pProps->uHz) / RT_NS_1SEC;
1204 Assert(dbBytesPerMs >= 0.0f);
1205 if (!dbBytesPerMs) /* Prevent division by zero. */
1206 return 0;
1207
1208 return cbBytes / dbBytesPerMs;
1209}
1210
1211/**
1212 * Returns the bytes for a given audio frames amount and PCM properties.
1213 *
1214 * @return Calculated bytes for given audio frames.
1215 * @param cFrames Amount of audio frames to calculate bytes for.
1216 * @param pProps PCM properties to calculate bytes for.
1217 */
1218uint32_t DrvAudioHlpFramesToBytes(uint32_t cFrames, const PPDMAUDIOPCMPROPS pProps)
1219{
1220 AssertPtrReturn(pProps, 0);
1221
1222 if (!cFrames)
1223 return 0;
1224
1225 const uint32_t cbFrame = (pProps->cBits / 8) * pProps->cChannels;
1226 return cFrames * cbFrame;
1227}
1228
1229/**
1230 * Returns the time (in ms) for given audio frames amount and PCM properties.
1231 *
1232 * @return uint64_t Calculated time (in ms).
1233 * @param cFrames Amount of audio frames to calculate time for.
1234 * @param pProps PCM properties to calculate time (in ms) for.
1235 */
1236uint64_t DrvAudioHlpFramesToMilli(uint32_t cFrames, const PPDMAUDIOPCMPROPS pProps)
1237{
1238 AssertPtrReturn(pProps, 0);
1239
1240 if (!cFrames)
1241 return 0;
1242
1243 if (!pProps->uHz) /* Prevent division by zero. */
1244 return 0;
1245
1246 return cFrames / ((double)pProps->uHz / (double)RT_MS_1SEC);
1247}
1248
1249/**
1250 * Returns the time (in ns) for given audio frames amount and PCM properties.
1251 *
1252 * @return uint64_t Calculated time (in ns).
1253 * @param cFrames Amount of audio frames to calculate time for.
1254 * @param pProps PCM properties to calculate time (in ns) for.
1255 */
1256uint64_t DrvAudioHlpFramesToNano(uint32_t cFrames, const PPDMAUDIOPCMPROPS pProps)
1257{
1258 AssertPtrReturn(pProps, 0);
1259
1260 if (!cFrames)
1261 return 0;
1262
1263 if (!pProps->uHz) /* Prevent division by zero. */
1264 return 0;
1265
1266 return cFrames / ((double)pProps->uHz / (double)RT_NS_1SEC);
1267}
1268
1269/**
1270 * Returns the amount of bytes for a given time (in ms) and PCM properties.
1271 *
1272 * @return uint32_t Calculated amount of bytes.
1273 * @param uMs Time (in ms) to calculate amount of bytes for.
1274 * @param pProps PCM properties to calculate amount of bytes for.
1275 */
1276uint32_t DrvAudioHlpMilliToBytes(uint64_t uMs, const PPDMAUDIOPCMPROPS pProps)
1277{
1278 AssertPtrReturn(pProps, 0);
1279
1280 if (!uMs)
1281 return 0;
1282
1283 const uint64_t cbBytesPerSec = (pProps->cBits / 8) * pProps->cChannels * pProps->uHz;
1284 return ((double)cbBytesPerSec / (double)RT_MS_1SEC) * uMs;
1285}
1286
1287/**
1288 * Returns the amount of bytes for a given time (in ns) and PCM properties.
1289 *
1290 * @return uint32_t Calculated amount of bytes.
1291 * @param uNs Time (in ns) to calculate amount of bytes for.
1292 * @param pProps PCM properties to calculate amount of bytes for.
1293 */
1294uint32_t DrvAudioHlpNanoToBytes(uint64_t uNs, const PPDMAUDIOPCMPROPS pProps)
1295{
1296 AssertPtrReturn(pProps, 0);
1297
1298 if (!uNs)
1299 return 0;
1300
1301 const uint64_t cbBytesPerSec = (pProps->cBits / 8) * pProps->cChannels * pProps->uHz;
1302 return ((double)cbBytesPerSec / (double)RT_NS_1SEC) * uNs;
1303}
1304
1305/**
1306 * Returns the amount of audio frames for a given time (in ms) and PCM properties.
1307 *
1308 * @return uint32_t Calculated amount of audio frames.
1309 * @param uMs Time (in ms) to calculate amount of frames for.
1310 * @param pProps PCM properties to calculate amount of frames for.
1311 */
1312uint32_t DrvAudioHlpMilliToFrames(uint64_t uMs, const PPDMAUDIOPCMPROPS pProps)
1313{
1314 AssertPtrReturn(pProps, 0);
1315
1316 const uint32_t cbFrame = (pProps->cBits / 8) * pProps->cChannels;
1317 if (!cbFrame) /* Prevent division by zero. */
1318 return 0;
1319
1320 return DrvAudioHlpMilliToBytes(uMs, pProps) / cbFrame;
1321}
1322
1323/**
1324 * Returns the amount of audio frames for a given time (in ns) and PCM properties.
1325 *
1326 * @return uint32_t Calculated amount of audio frames.
1327 * @param uNs Time (in ns) to calculate amount of frames for.
1328 * @param pProps PCM properties to calculate amount of frames for.
1329 */
1330uint32_t DrvAudioHlpNanoToFrames(uint64_t uNs, const PPDMAUDIOPCMPROPS pProps)
1331{
1332 AssertPtrReturn(pProps, 0);
1333
1334 const uint32_t cbFrame = (pProps->cBits / 8) * pProps->cChannels;
1335 if (!cbFrame) /* Prevent division by zero. */
1336 return 0;
1337
1338 return DrvAudioHlpNanoToBytes(uNs, pProps) / cbFrame;
1339}
1340
1341/**
1342 * Sanitizes the file name component so that unsupported characters
1343 * will be replaced by an underscore ("_").
1344 *
1345 * @return IPRT status code.
1346 * @param pszPath Path to sanitize.
1347 * @param cbPath Size (in bytes) of path to sanitize.
1348 */
1349int DrvAudioHlpFileNameSanitize(char *pszPath, size_t cbPath)
1350{
1351 RT_NOREF(cbPath);
1352 int rc = VINF_SUCCESS;
1353#ifdef RT_OS_WINDOWS
1354 /* Filter out characters not allowed on Windows platforms, put in by
1355 RTTimeSpecToString(). */
1356 /** @todo Use something like RTPathSanitize() if available later some time. */
1357 static RTUNICP const s_uszValidRangePairs[] =
1358 {
1359 ' ', ' ',
1360 '(', ')',
1361 '-', '.',
1362 '0', '9',
1363 'A', 'Z',
1364 'a', 'z',
1365 '_', '_',
1366 0xa0, 0xd7af,
1367 '\0'
1368 };
1369 ssize_t cReplaced = RTStrPurgeComplementSet(pszPath, s_uszValidRangePairs, '_' /* Replacement */);
1370 if (cReplaced < 0)
1371 rc = VERR_INVALID_UTF8_ENCODING;
1372#else
1373 RT_NOREF(pszPath);
1374#endif
1375 return rc;
1376}
1377
1378/**
1379 * Constructs an unique file name, based on the given path and the audio file type.
1380 *
1381 * @returns IPRT status code.
1382 * @param pszFile Where to store the constructed file name.
1383 * @param cchFile Size (in characters) of the file name buffer.
1384 * @param pszPath Base path to use.
1385 * @param pszName A name for better identifying the file.
1386 * @param uInstance Device / driver instance which is using this file.
1387 * @param enmType Audio file type to construct file name for.
1388 * @param fFlags File naming flags.
1389 */
1390int DrvAudioHlpFileNameGet(char *pszFile, size_t cchFile, const char *pszPath, const char *pszName,
1391 uint32_t uInstance, PDMAUDIOFILETYPE enmType, PDMAUDIOFILENAMEFLAGS fFlags)
1392{
1393 AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
1394 AssertReturn(cchFile, VERR_INVALID_PARAMETER);
1395 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1396 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
1397 /** @todo Validate fFlags. */
1398
1399 int rc;
1400
1401 do
1402 {
1403 char szFilePath[RTPATH_MAX + 1];
1404 RTStrPrintf2(szFilePath, sizeof(szFilePath), "%s", pszPath);
1405
1406 /* Create it when necessary. */
1407 if (!RTDirExists(szFilePath))
1408 {
1409 rc = RTDirCreateFullPath(szFilePath, RTFS_UNIX_IRWXU);
1410 if (RT_FAILURE(rc))
1411 break;
1412 }
1413
1414 char szFileName[RTPATH_MAX + 1];
1415 szFileName[0] = '\0';
1416
1417 if (fFlags & PDMAUDIOFILENAME_FLAG_TS)
1418 {
1419 RTTIMESPEC time;
1420 if (!RTTimeSpecToString(RTTimeNow(&time), szFileName, sizeof(szFileName)))
1421 {
1422 rc = VERR_BUFFER_OVERFLOW;
1423 break;
1424 }
1425
1426 rc = DrvAudioHlpFileNameSanitize(szFileName, sizeof(szFileName));
1427 if (RT_FAILURE(rc))
1428 break;
1429
1430 rc = RTStrCat(szFileName, sizeof(szFileName), "-");
1431 if (RT_FAILURE(rc))
1432 break;
1433 }
1434
1435 rc = RTStrCat(szFileName, sizeof(szFileName), pszName);
1436 if (RT_FAILURE(rc))
1437 break;
1438
1439 rc = RTStrCat(szFileName, sizeof(szFileName), "-");
1440 if (RT_FAILURE(rc))
1441 break;
1442
1443 char szInst[16];
1444 RTStrPrintf2(szInst, sizeof(szInst), "%RU32", uInstance);
1445 rc = RTStrCat(szFileName, sizeof(szFileName), szInst);
1446 if (RT_FAILURE(rc))
1447 break;
1448
1449 switch (enmType)
1450 {
1451 case PDMAUDIOFILETYPE_RAW:
1452 rc = RTStrCat(szFileName, sizeof(szFileName), ".pcm");
1453 break;
1454
1455 case PDMAUDIOFILETYPE_WAV:
1456 rc = RTStrCat(szFileName, sizeof(szFileName), ".wav");
1457 break;
1458
1459 default:
1460 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
1461 break;
1462 }
1463
1464 if (RT_FAILURE(rc))
1465 break;
1466
1467 rc = RTPathAppend(szFilePath, sizeof(szFilePath), szFileName);
1468 if (RT_FAILURE(rc))
1469 break;
1470
1471 RTStrPrintf2(pszFile, cchFile, "%s", szFilePath);
1472
1473 } while (0);
1474
1475 LogFlowFuncLeaveRC(rc);
1476 return rc;
1477}
1478
1479/**
1480 * Creates an audio file.
1481 *
1482 * @returns IPRT status code.
1483 * @param enmType Audio file type to open / create.
1484 * @param pszFile File path of file to open or create.
1485 * @param fFlags Audio file flags.
1486 * @param ppFile Where to store the created audio file handle.
1487 * Needs to be destroyed with DrvAudioHlpFileDestroy().
1488 */
1489int DrvAudioHlpFileCreate(PDMAUDIOFILETYPE enmType, const char *pszFile, PDMAUDIOFILEFLAGS fFlags, PPDMAUDIOFILE *ppFile)
1490{
1491 AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
1492 /** @todo Validate fFlags. */
1493
1494 PPDMAUDIOFILE pFile = (PPDMAUDIOFILE)RTMemAlloc(sizeof(PDMAUDIOFILE));
1495 if (!pFile)
1496 return VERR_NO_MEMORY;
1497
1498 int rc = VINF_SUCCESS;
1499
1500 switch (enmType)
1501 {
1502 case PDMAUDIOFILETYPE_RAW:
1503 case PDMAUDIOFILETYPE_WAV:
1504 pFile->enmType = enmType;
1505 break;
1506
1507 default:
1508 rc = VERR_INVALID_PARAMETER;
1509 break;
1510 }
1511
1512 if (RT_SUCCESS(rc))
1513 {
1514 RTStrPrintf(pFile->szName, RT_ELEMENTS(pFile->szName), "%s", pszFile);
1515 pFile->hFile = NIL_RTFILE;
1516 pFile->fFlags = fFlags;
1517 pFile->pvData = NULL;
1518 pFile->cbData = 0;
1519 }
1520
1521 if (RT_FAILURE(rc))
1522 {
1523 RTMemFree(pFile);
1524 pFile = NULL;
1525 }
1526 else
1527 *ppFile = pFile;
1528
1529 return rc;
1530}
1531
1532/**
1533 * Destroys a formerly created audio file.
1534 *
1535 * @param pFile Audio file (object) to destroy.
1536 */
1537void DrvAudioHlpFileDestroy(PPDMAUDIOFILE pFile)
1538{
1539 if (!pFile)
1540 return;
1541
1542 DrvAudioHlpFileClose(pFile);
1543
1544 RTMemFree(pFile);
1545 pFile = NULL;
1546}
1547
1548/**
1549 * Opens or creates an audio file.
1550 *
1551 * @returns IPRT status code.
1552 * @param pFile Pointer to audio file handle to use.
1553 * @param fOpen Open flags.
1554 * Use PDMAUDIOFILE_DEFAULT_OPEN_FLAGS for the default open flags.
1555 * @param pProps PCM properties to use.
1556 */
1557int DrvAudioHlpFileOpen(PPDMAUDIOFILE pFile, uint32_t fOpen, const PPDMAUDIOPCMPROPS pProps)
1558{
1559 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1560 /** @todo Validate fOpen flags. */
1561 AssertPtrReturn(pProps, VERR_INVALID_POINTER);
1562
1563 int rc;
1564
1565 if (pFile->enmType == PDMAUDIOFILETYPE_RAW)
1566 {
1567 rc = RTFileOpen(&pFile->hFile, pFile->szName, fOpen);
1568 }
1569 else if (pFile->enmType == PDMAUDIOFILETYPE_WAV)
1570 {
1571 Assert(pProps->cChannels);
1572 Assert(pProps->uHz);
1573 Assert(pProps->cBits);
1574
1575 pFile->pvData = (PAUDIOWAVFILEDATA)RTMemAllocZ(sizeof(AUDIOWAVFILEDATA));
1576 if (pFile->pvData)
1577 {
1578 pFile->cbData = sizeof(PAUDIOWAVFILEDATA);
1579
1580 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1581 AssertPtr(pData);
1582
1583 /* Header. */
1584 pData->Hdr.u32RIFF = AUDIO_MAKE_FOURCC('R','I','F','F');
1585 pData->Hdr.u32Size = 36;
1586 pData->Hdr.u32WAVE = AUDIO_MAKE_FOURCC('W','A','V','E');
1587
1588 pData->Hdr.u32Fmt = AUDIO_MAKE_FOURCC('f','m','t',' ');
1589 pData->Hdr.u32Size1 = 16; /* Means PCM. */
1590 pData->Hdr.u16AudioFormat = 1; /* PCM, linear quantization. */
1591 pData->Hdr.u16NumChannels = pProps->cChannels;
1592 pData->Hdr.u32SampleRate = pProps->uHz;
1593 pData->Hdr.u32ByteRate = DrvAudioHlpCalcBitrate(pProps->cBits, pProps->uHz, pProps->cChannels) / 8;
1594 pData->Hdr.u16BlockAlign = pProps->cChannels * pProps->cBits / 8;
1595 pData->Hdr.u16BitsPerSample = pProps->cBits;
1596
1597 /* Data chunk. */
1598 pData->Hdr.u32ID2 = AUDIO_MAKE_FOURCC('d','a','t','a');
1599 pData->Hdr.u32Size2 = 0;
1600
1601 rc = RTFileOpen(&pFile->hFile, pFile->szName, fOpen);
1602 if (RT_SUCCESS(rc))
1603 {
1604 rc = RTFileWrite(pFile->hFile, &pData->Hdr, sizeof(pData->Hdr), NULL);
1605 if (RT_FAILURE(rc))
1606 {
1607 RTFileClose(pFile->hFile);
1608 pFile->hFile = NIL_RTFILE;
1609 }
1610 }
1611
1612 if (RT_FAILURE(rc))
1613 {
1614 RTMemFree(pFile->pvData);
1615 pFile->pvData = NULL;
1616 pFile->cbData = 0;
1617 }
1618 }
1619 else
1620 rc = VERR_NO_MEMORY;
1621 }
1622 else
1623 rc = VERR_INVALID_PARAMETER;
1624
1625 if (RT_SUCCESS(rc))
1626 {
1627 LogRel2(("Audio: Opened file '%s'\n", pFile->szName));
1628 }
1629 else
1630 LogRel(("Audio: Failed opening file '%s', rc=%Rrc\n", pFile->szName, rc));
1631
1632 return rc;
1633}
1634
1635/**
1636 * Closes an audio file.
1637 *
1638 * @returns IPRT status code.
1639 * @param pFile Audio file handle to close.
1640 */
1641int DrvAudioHlpFileClose(PPDMAUDIOFILE pFile)
1642{
1643 if (!pFile)
1644 return VINF_SUCCESS;
1645
1646 size_t cbSize = DrvAudioHlpFileGetDataSize(pFile);
1647
1648 int rc = VINF_SUCCESS;
1649
1650 if (pFile->enmType == PDMAUDIOFILETYPE_RAW)
1651 {
1652 if (RTFileIsValid(pFile->hFile))
1653 rc = RTFileClose(pFile->hFile);
1654 }
1655 else if (pFile->enmType == PDMAUDIOFILETYPE_WAV)
1656 {
1657 if (RTFileIsValid(pFile->hFile))
1658 {
1659 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1660 if (pData) /* The .WAV file data only is valid when a file actually has been created. */
1661 {
1662 /* Update the header with the current data size. */
1663 RTFileWriteAt(pFile->hFile, 0, &pData->Hdr, sizeof(pData->Hdr), NULL);
1664 }
1665
1666 rc = RTFileClose(pFile->hFile);
1667 }
1668
1669 if (pFile->pvData)
1670 {
1671 RTMemFree(pFile->pvData);
1672 pFile->pvData = NULL;
1673 }
1674 }
1675 else
1676 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
1677
1678 if ( RT_SUCCESS(rc)
1679 && !cbSize
1680 && !(pFile->fFlags & PDMAUDIOFILE_FLAG_KEEP_IF_EMPTY))
1681 {
1682 rc = DrvAudioHlpFileDelete(pFile);
1683 }
1684
1685 pFile->cbData = 0;
1686
1687 if (RT_SUCCESS(rc))
1688 {
1689 pFile->hFile = NIL_RTFILE;
1690 LogRel2(("Audio: Closed file '%s' (%zu bytes)\n", pFile->szName, cbSize));
1691 }
1692 else
1693 LogRel(("Audio: Failed closing file '%s', rc=%Rrc\n", pFile->szName, rc));
1694
1695 return rc;
1696}
1697
1698/**
1699 * Deletes an audio file.
1700 *
1701 * @returns IPRT status code.
1702 * @param pFile Audio file handle to delete.
1703 */
1704int DrvAudioHlpFileDelete(PPDMAUDIOFILE pFile)
1705{
1706 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1707
1708 int rc = RTFileDelete(pFile->szName);
1709 if (RT_SUCCESS(rc))
1710 {
1711 LogRel2(("Audio: Deleted file '%s'\n", pFile->szName));
1712 }
1713 else if (rc == VERR_FILE_NOT_FOUND) /* Don't bitch if the file is not around (anymore). */
1714 rc = VINF_SUCCESS;
1715
1716 if (RT_FAILURE(rc))
1717 LogRel(("Audio: Failed deleting file '%s', rc=%Rrc\n", pFile->szName, rc));
1718
1719 return rc;
1720}
1721
1722/**
1723 * Returns the raw audio data size of an audio file.
1724 *
1725 * Note: This does *not* include file headers and other data which does
1726 * not belong to the actual PCM audio data.
1727 *
1728 * @returns Size (in bytes) of the raw PCM audio data.
1729 * @param pFile Audio file handle to retrieve the audio data size for.
1730 */
1731size_t DrvAudioHlpFileGetDataSize(PPDMAUDIOFILE pFile)
1732{
1733 AssertPtrReturn(pFile, 0);
1734
1735 size_t cbSize = 0;
1736
1737 if (pFile->enmType == PDMAUDIOFILETYPE_RAW)
1738 {
1739 cbSize = RTFileTell(pFile->hFile);
1740 }
1741 else if (pFile->enmType == PDMAUDIOFILETYPE_WAV)
1742 {
1743 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1744 if (pData) /* The .WAV file data only is valid when a file actually has been created. */
1745 cbSize = pData->Hdr.u32Size2;
1746 }
1747
1748 return cbSize;
1749}
1750
1751/**
1752 * Returns whether the given audio file is open and in use or not.
1753 *
1754 * @return bool True if open, false if not.
1755 * @param pFile Audio file handle to check open status for.
1756 */
1757bool DrvAudioHlpFileIsOpen(PPDMAUDIOFILE pFile)
1758{
1759 if (!pFile)
1760 return false;
1761
1762 return RTFileIsValid(pFile->hFile);
1763}
1764
1765/**
1766 * Write PCM data to a wave (.WAV) file.
1767 *
1768 * @returns IPRT status code.
1769 * @param pFile Audio file handle to write PCM data to.
1770 * @param pvBuf Audio data to write.
1771 * @param cbBuf Size (in bytes) of audio data to write.
1772 * @param fFlags Additional write flags. Not being used at the moment and must be 0.
1773 */
1774int DrvAudioHlpFileWrite(PPDMAUDIOFILE pFile, const void *pvBuf, size_t cbBuf, uint32_t fFlags)
1775{
1776 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1777 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1778
1779 AssertReturn(fFlags == 0, VERR_INVALID_PARAMETER); /** @todo fFlags are currently not implemented. */
1780
1781 if (!cbBuf)
1782 return VINF_SUCCESS;
1783
1784 AssertReturn(RTFileIsValid(pFile->hFile), VERR_WRONG_ORDER);
1785
1786 int rc;
1787
1788 if (pFile->enmType == PDMAUDIOFILETYPE_RAW)
1789 {
1790 rc = RTFileWrite(pFile->hFile, pvBuf, cbBuf, NULL);
1791 }
1792 else if (pFile->enmType == PDMAUDIOFILETYPE_WAV)
1793 {
1794 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1795 AssertPtr(pData);
1796
1797 rc = RTFileWrite(pFile->hFile, pvBuf, cbBuf, NULL);
1798 if (RT_SUCCESS(rc))
1799 {
1800 pData->Hdr.u32Size += (uint32_t)cbBuf;
1801 pData->Hdr.u32Size2 += (uint32_t)cbBuf;
1802 }
1803 }
1804 else
1805 rc = VERR_NOT_SUPPORTED;
1806
1807 return rc;
1808}
1809
Note: See TracBrowser for help on using the repository browser.

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