VirtualBox

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

Last change on this file since 73463 was 73463, checked in by vboxsync, 6 years ago

Audio/DrvAudioCommon: Check if the given stream configuration is valid in DrvAudioHlpStreamCfgDup().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 52.4 KB
Line 
1/* $Id: DrvAudioCommon.cpp 73463 2018-08-03 09:25:19Z 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#ifdef VBOX_STRICT
981 if (!DrvAudioHlpStreamCfgIsValid(pCfg))
982 {
983 AssertMsgFailed(("Stream config '%s' (%p) is invalid\n", pCfg->szName, pCfg));
984 return NULL;
985 }
986#endif
987
988 PPDMAUDIOSTREAMCFG pDst = (PPDMAUDIOSTREAMCFG)RTMemAllocZ(sizeof(PDMAUDIOSTREAMCFG));
989 if (!pDst)
990 return NULL;
991
992 int rc2 = DrvAudioHlpStreamCfgCopy(pDst, pCfg);
993 if (RT_FAILURE(rc2))
994 {
995 DrvAudioHlpStreamCfgFree(pDst);
996 pDst = NULL;
997 }
998
999 AssertPtr(pDst);
1000 return pDst;
1001}
1002
1003/**
1004 * Prints an audio stream configuration to the debug log.
1005 *
1006 * @param pCfg Stream configuration to log.
1007 */
1008void DrvAudioHlpStreamCfgPrint(const PPDMAUDIOSTREAMCFG pCfg)
1009{
1010 if (!pCfg)
1011 return;
1012
1013 LogFunc(("szName=%s, enmDir=%RU32 (uHz=%RU32, cBits=%RU8%s, cChannels=%RU8)\n",
1014 pCfg->szName, pCfg->enmDir,
1015 pCfg->Props.uHz, pCfg->Props.cBits, pCfg->Props.fSigned ? "S" : "U", pCfg->Props.cChannels));
1016}
1017
1018/**
1019 * Converts a stream command to a string.
1020 *
1021 * @returns Stringified stream command, or "Unknown", if not found.
1022 * @param enmCmd Stream command to convert.
1023 */
1024const char *DrvAudioHlpStreamCmdToStr(PDMAUDIOSTREAMCMD enmCmd)
1025{
1026 switch (enmCmd)
1027 {
1028 case PDMAUDIOSTREAMCMD_UNKNOWN: return "Unknown";
1029 case PDMAUDIOSTREAMCMD_ENABLE: return "Enable";
1030 case PDMAUDIOSTREAMCMD_DISABLE: return "Disable";
1031 case PDMAUDIOSTREAMCMD_PAUSE: return "Pause";
1032 case PDMAUDIOSTREAMCMD_RESUME: return "Resume";
1033 case PDMAUDIOSTREAMCMD_DRAIN: return "Drain";
1034 case PDMAUDIOSTREAMCMD_DROP: return "Drop";
1035 default: break;
1036 }
1037
1038 AssertMsgFailed(("Invalid stream command %ld\n", enmCmd));
1039 return "Unknown";
1040}
1041
1042/**
1043 * Returns @c true if the given stream status indicates a can-be-read-from stream,
1044 * @c false if not.
1045 *
1046 * @returns @c true if ready to be read from, @c if not.
1047 * @param enmStatus Stream status to evaluate.
1048 */
1049bool DrvAudioHlpStreamStatusCanRead(PDMAUDIOSTREAMSTS enmStatus)
1050{
1051 AssertReturn(enmStatus & PDMAUDIOSTREAMSTS_VALID_MASK, false);
1052
1053 return enmStatus & PDMAUDIOSTREAMSTS_FLAG_INITIALIZED
1054 && enmStatus & PDMAUDIOSTREAMSTS_FLAG_ENABLED
1055 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PAUSED)
1056 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PENDING_REINIT);
1057}
1058
1059/**
1060 * Returns @c true if the given stream status indicates a can-be-written-to stream,
1061 * @c false if not.
1062 *
1063 * @returns @c true if ready to be written to, @c if not.
1064 * @param enmStatus Stream status to evaluate.
1065 */
1066bool DrvAudioHlpStreamStatusCanWrite(PDMAUDIOSTREAMSTS enmStatus)
1067{
1068 AssertReturn(enmStatus & PDMAUDIOSTREAMSTS_VALID_MASK, false);
1069
1070 return enmStatus & PDMAUDIOSTREAMSTS_FLAG_INITIALIZED
1071 && enmStatus & PDMAUDIOSTREAMSTS_FLAG_ENABLED
1072 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PAUSED)
1073 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PENDING_DISABLE)
1074 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PENDING_REINIT);
1075}
1076
1077/**
1078 * Returns @c true if the given stream status indicates a ready-to-operate stream,
1079 * @c false if not.
1080 *
1081 * @returns @c true if ready to operate, @c if not.
1082 * @param enmStatus Stream status to evaluate.
1083 */
1084bool DrvAudioHlpStreamStatusIsReady(PDMAUDIOSTREAMSTS enmStatus)
1085{
1086 AssertReturn(enmStatus & PDMAUDIOSTREAMSTS_VALID_MASK, false);
1087
1088 return enmStatus & PDMAUDIOSTREAMSTS_FLAG_INITIALIZED
1089 && enmStatus & PDMAUDIOSTREAMSTS_FLAG_ENABLED
1090 && !(enmStatus & PDMAUDIOSTREAMSTS_FLAG_PENDING_REINIT);
1091}
1092
1093/**
1094 * Calculates the audio bit rate of the given bits per sample, the Hz and the number
1095 * of audio channels.
1096 *
1097 * Divide the result by 8 to get the byte rate.
1098 *
1099 * @returns The calculated bit rate.
1100 * @param cBits Number of bits per sample.
1101 * @param uHz Hz (Hertz) rate.
1102 * @param cChannels Number of audio channels.
1103 */
1104uint32_t DrvAudioHlpCalcBitrate(uint8_t cBits, uint32_t uHz, uint8_t cChannels)
1105{
1106 return (cBits * uHz * cChannels);
1107}
1108
1109/**
1110 * Calculates the audio bit rate out of a given audio stream configuration.
1111 *
1112 * Divide the result by 8 to get the byte rate.
1113 *
1114 * @returns The calculated bit rate.
1115 * @param pProps PCM properties to calculate bitrate for.
1116 *
1117 * @remark
1118 */
1119uint32_t DrvAudioHlpCalcBitrate(const PPDMAUDIOPCMPROPS pProps)
1120{
1121 return DrvAudioHlpCalcBitrate(pProps->cBits, pProps->uHz, pProps->cChannels);
1122}
1123
1124/**
1125 * Aligns the given byte amount to the given PCM properties and returns the aligned
1126 * size.
1127 *
1128 * @return Aligned size (in bytes).
1129 * @param cbSize Size (in bytes) to align.
1130 * @param pProps PCM properties to align size to.
1131 */
1132uint32_t DrvAudioHlpBytesAlign(uint32_t cbSize, const PPDMAUDIOPCMPROPS pProps)
1133{
1134 AssertPtrReturn(pProps, 0);
1135
1136 if (!cbSize)
1137 return 0;
1138
1139 const uint32_t cbFrameSize = DrvAudioHlpPCMPropsBytesPerFrame(pProps);
1140 return (cbSize / cbFrameSize) * cbFrameSize;
1141}
1142
1143/**
1144 * Returns if the the given size is properly aligned to the given PCM properties.
1145 *
1146 * @return @c true if properly aligned, @c false if not.
1147 * @param cbSize Size (in bytes) to check alignment for.
1148 * @param pProps PCM properties to use for checking the alignment.
1149 */
1150bool DrvAudioHlpBytesIsAligned(uint32_t cbSize, const PPDMAUDIOPCMPROPS pProps)
1151{
1152 AssertPtrReturn(pProps, 0);
1153
1154 if (!cbSize)
1155 return true;
1156
1157 return (cbSize % DrvAudioHlpPCMPropsBytesPerFrame(pProps) == 0);
1158}
1159
1160/**
1161 * Returns the number of audio frames for a given amount of bytes.
1162 *
1163 * @return Calculated audio frames for given bytes.
1164 * @param cbBytes Bytes to convert to audio frames.
1165 * @param pProps PCM properties to calulate frames for.
1166 */
1167uint32_t DrvAudioHlpBytesToFrames(uint32_t cbBytes, const PPDMAUDIOPCMPROPS pProps)
1168{
1169 AssertPtrReturn(pProps, 0);
1170
1171 return cbBytes / ((pProps->cBits / 8) * pProps->cChannels);
1172}
1173
1174/**
1175 * Returns the time (in ms) for given byte amount and PCM properties.
1176 *
1177 * @return uint64_t Calculated time (in ms).
1178 * @param cbBytes Amount of bytes to calculate time for.
1179 * @param pProps PCM properties to calculate amount of bytes for.
1180 */
1181uint64_t DrvAudioHlpBytesToMilli(uint32_t cbBytes, const PPDMAUDIOPCMPROPS pProps)
1182{
1183 AssertPtrReturn(pProps, 0);
1184
1185 if (!cbBytes)
1186 return 0;
1187
1188 const uint64_t cbBytesPerSec = (pProps->cBits / 8) * pProps->cChannels * pProps->uHz;
1189 const double dbBytesPerMs = (double)cbBytesPerSec / (double)RT_MS_1SEC;
1190 Assert(dbBytesPerMs >= 0.0f);
1191 if (!dbBytesPerMs) /* Prevent division by zero. */
1192 return 0;
1193
1194 return (double)cbBytes / (double)dbBytesPerMs;
1195}
1196
1197/**
1198 * Returns the time (in ns) for given byte amount and PCM properties.
1199 *
1200 * @return uint64_t Calculated time (in ns).
1201 * @param cbBytes Amount of bytes to calculate time for.
1202 * @param pProps PCM properties to calculate amount of bytes for.
1203 */
1204uint64_t DrvAudioHlpBytesToNano(uint32_t cbBytes, const PPDMAUDIOPCMPROPS pProps)
1205{
1206 AssertPtrReturn(pProps, 0);
1207
1208 if (!cbBytes)
1209 return 0;
1210
1211 const double dbBytesPerMs = ((pProps->cBits / 8) * pProps->cChannels * pProps->uHz) / RT_NS_1SEC;
1212 Assert(dbBytesPerMs >= 0.0f);
1213 if (!dbBytesPerMs) /* Prevent division by zero. */
1214 return 0;
1215
1216 return cbBytes / dbBytesPerMs;
1217}
1218
1219/**
1220 * Returns the bytes for a given audio frames amount and PCM properties.
1221 *
1222 * @return Calculated bytes for given audio frames.
1223 * @param cFrames Amount of audio frames to calculate bytes for.
1224 * @param pProps PCM properties to calculate bytes for.
1225 */
1226uint32_t DrvAudioHlpFramesToBytes(uint32_t cFrames, const PPDMAUDIOPCMPROPS pProps)
1227{
1228 AssertPtrReturn(pProps, 0);
1229
1230 if (!cFrames)
1231 return 0;
1232
1233 const uint32_t cbFrame = (pProps->cBits / 8) * pProps->cChannels;
1234 return cFrames * cbFrame;
1235}
1236
1237/**
1238 * Returns the time (in ms) for given audio frames amount and PCM properties.
1239 *
1240 * @return uint64_t Calculated time (in ms).
1241 * @param cFrames Amount of audio frames to calculate time for.
1242 * @param pProps PCM properties to calculate time (in ms) for.
1243 */
1244uint64_t DrvAudioHlpFramesToMilli(uint32_t cFrames, const PPDMAUDIOPCMPROPS pProps)
1245{
1246 AssertPtrReturn(pProps, 0);
1247
1248 if (!cFrames)
1249 return 0;
1250
1251 if (!pProps->uHz) /* Prevent division by zero. */
1252 return 0;
1253
1254 return cFrames / ((double)pProps->uHz / (double)RT_MS_1SEC);
1255}
1256
1257/**
1258 * Returns the time (in ns) for given audio frames amount and PCM properties.
1259 *
1260 * @return uint64_t Calculated time (in ns).
1261 * @param cFrames Amount of audio frames to calculate time for.
1262 * @param pProps PCM properties to calculate time (in ns) for.
1263 */
1264uint64_t DrvAudioHlpFramesToNano(uint32_t cFrames, const PPDMAUDIOPCMPROPS pProps)
1265{
1266 AssertPtrReturn(pProps, 0);
1267
1268 if (!cFrames)
1269 return 0;
1270
1271 if (!pProps->uHz) /* Prevent division by zero. */
1272 return 0;
1273
1274 return cFrames / ((double)pProps->uHz / (double)RT_NS_1SEC);
1275}
1276
1277/**
1278 * Returns the amount of bytes for a given time (in ms) and PCM properties.
1279 *
1280 * @return uint32_t Calculated amount of bytes.
1281 * @param uMs Time (in ms) to calculate amount of bytes for.
1282 * @param pProps PCM properties to calculate amount of bytes for.
1283 */
1284uint32_t DrvAudioHlpMilliToBytes(uint64_t uMs, const PPDMAUDIOPCMPROPS pProps)
1285{
1286 AssertPtrReturn(pProps, 0);
1287
1288 if (!uMs)
1289 return 0;
1290
1291 const uint64_t cbBytesPerSec = (pProps->cBits / 8) * pProps->cChannels * pProps->uHz;
1292 return ((double)cbBytesPerSec / (double)RT_MS_1SEC) * uMs;
1293}
1294
1295/**
1296 * Returns the amount of bytes for a given time (in ns) and PCM properties.
1297 *
1298 * @return uint32_t Calculated amount of bytes.
1299 * @param uNs Time (in ns) to calculate amount of bytes for.
1300 * @param pProps PCM properties to calculate amount of bytes for.
1301 */
1302uint32_t DrvAudioHlpNanoToBytes(uint64_t uNs, const PPDMAUDIOPCMPROPS pProps)
1303{
1304 AssertPtrReturn(pProps, 0);
1305
1306 if (!uNs)
1307 return 0;
1308
1309 const uint64_t cbBytesPerSec = (pProps->cBits / 8) * pProps->cChannels * pProps->uHz;
1310 return ((double)cbBytesPerSec / (double)RT_NS_1SEC) * uNs;
1311}
1312
1313/**
1314 * Returns the amount of audio frames for a given time (in ms) and PCM properties.
1315 *
1316 * @return uint32_t Calculated amount of audio frames.
1317 * @param uMs Time (in ms) to calculate amount of frames for.
1318 * @param pProps PCM properties to calculate amount of frames for.
1319 */
1320uint32_t DrvAudioHlpMilliToFrames(uint64_t uMs, const PPDMAUDIOPCMPROPS pProps)
1321{
1322 AssertPtrReturn(pProps, 0);
1323
1324 const uint32_t cbFrame = (pProps->cBits / 8) * pProps->cChannels;
1325 if (!cbFrame) /* Prevent division by zero. */
1326 return 0;
1327
1328 return DrvAudioHlpMilliToBytes(uMs, pProps) / cbFrame;
1329}
1330
1331/**
1332 * Returns the amount of audio frames for a given time (in ns) and PCM properties.
1333 *
1334 * @return uint32_t Calculated amount of audio frames.
1335 * @param uNs Time (in ns) to calculate amount of frames for.
1336 * @param pProps PCM properties to calculate amount of frames for.
1337 */
1338uint32_t DrvAudioHlpNanoToFrames(uint64_t uNs, const PPDMAUDIOPCMPROPS pProps)
1339{
1340 AssertPtrReturn(pProps, 0);
1341
1342 const uint32_t cbFrame = (pProps->cBits / 8) * pProps->cChannels;
1343 if (!cbFrame) /* Prevent division by zero. */
1344 return 0;
1345
1346 return DrvAudioHlpNanoToBytes(uNs, pProps) / cbFrame;
1347}
1348
1349/**
1350 * Sanitizes the file name component so that unsupported characters
1351 * will be replaced by an underscore ("_").
1352 *
1353 * @return IPRT status code.
1354 * @param pszPath Path to sanitize.
1355 * @param cbPath Size (in bytes) of path to sanitize.
1356 */
1357int DrvAudioHlpFileNameSanitize(char *pszPath, size_t cbPath)
1358{
1359 RT_NOREF(cbPath);
1360 int rc = VINF_SUCCESS;
1361#ifdef RT_OS_WINDOWS
1362 /* Filter out characters not allowed on Windows platforms, put in by
1363 RTTimeSpecToString(). */
1364 /** @todo Use something like RTPathSanitize() if available later some time. */
1365 static RTUNICP const s_uszValidRangePairs[] =
1366 {
1367 ' ', ' ',
1368 '(', ')',
1369 '-', '.',
1370 '0', '9',
1371 'A', 'Z',
1372 'a', 'z',
1373 '_', '_',
1374 0xa0, 0xd7af,
1375 '\0'
1376 };
1377 ssize_t cReplaced = RTStrPurgeComplementSet(pszPath, s_uszValidRangePairs, '_' /* Replacement */);
1378 if (cReplaced < 0)
1379 rc = VERR_INVALID_UTF8_ENCODING;
1380#else
1381 RT_NOREF(pszPath);
1382#endif
1383 return rc;
1384}
1385
1386/**
1387 * Constructs an unique file name, based on the given path and the audio file type.
1388 *
1389 * @returns IPRT status code.
1390 * @param pszFile Where to store the constructed file name.
1391 * @param cchFile Size (in characters) of the file name buffer.
1392 * @param pszPath Base path to use.
1393 * @param pszName A name for better identifying the file.
1394 * @param uInstance Device / driver instance which is using this file.
1395 * @param enmType Audio file type to construct file name for.
1396 * @param fFlags File naming flags.
1397 */
1398int DrvAudioHlpFileNameGet(char *pszFile, size_t cchFile, const char *pszPath, const char *pszName,
1399 uint32_t uInstance, PDMAUDIOFILETYPE enmType, PDMAUDIOFILENAMEFLAGS fFlags)
1400{
1401 AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
1402 AssertReturn(cchFile, VERR_INVALID_PARAMETER);
1403 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1404 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
1405 /** @todo Validate fFlags. */
1406
1407 int rc;
1408
1409 do
1410 {
1411 char szFilePath[RTPATH_MAX + 1];
1412 RTStrPrintf2(szFilePath, sizeof(szFilePath), "%s", pszPath);
1413
1414 /* Create it when necessary. */
1415 if (!RTDirExists(szFilePath))
1416 {
1417 rc = RTDirCreateFullPath(szFilePath, RTFS_UNIX_IRWXU);
1418 if (RT_FAILURE(rc))
1419 break;
1420 }
1421
1422 char szFileName[RTPATH_MAX + 1];
1423 szFileName[0] = '\0';
1424
1425 if (fFlags & PDMAUDIOFILENAME_FLAG_TS)
1426 {
1427 RTTIMESPEC time;
1428 if (!RTTimeSpecToString(RTTimeNow(&time), szFileName, sizeof(szFileName)))
1429 {
1430 rc = VERR_BUFFER_OVERFLOW;
1431 break;
1432 }
1433
1434 rc = DrvAudioHlpFileNameSanitize(szFileName, sizeof(szFileName));
1435 if (RT_FAILURE(rc))
1436 break;
1437
1438 rc = RTStrCat(szFileName, sizeof(szFileName), "-");
1439 if (RT_FAILURE(rc))
1440 break;
1441 }
1442
1443 rc = RTStrCat(szFileName, sizeof(szFileName), pszName);
1444 if (RT_FAILURE(rc))
1445 break;
1446
1447 rc = RTStrCat(szFileName, sizeof(szFileName), "-");
1448 if (RT_FAILURE(rc))
1449 break;
1450
1451 char szInst[16];
1452 RTStrPrintf2(szInst, sizeof(szInst), "%RU32", uInstance);
1453 rc = RTStrCat(szFileName, sizeof(szFileName), szInst);
1454 if (RT_FAILURE(rc))
1455 break;
1456
1457 switch (enmType)
1458 {
1459 case PDMAUDIOFILETYPE_RAW:
1460 rc = RTStrCat(szFileName, sizeof(szFileName), ".pcm");
1461 break;
1462
1463 case PDMAUDIOFILETYPE_WAV:
1464 rc = RTStrCat(szFileName, sizeof(szFileName), ".wav");
1465 break;
1466
1467 default:
1468 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
1469 break;
1470 }
1471
1472 if (RT_FAILURE(rc))
1473 break;
1474
1475 rc = RTPathAppend(szFilePath, sizeof(szFilePath), szFileName);
1476 if (RT_FAILURE(rc))
1477 break;
1478
1479 RTStrPrintf2(pszFile, cchFile, "%s", szFilePath);
1480
1481 } while (0);
1482
1483 LogFlowFuncLeaveRC(rc);
1484 return rc;
1485}
1486
1487/**
1488 * Creates an audio file.
1489 *
1490 * @returns IPRT status code.
1491 * @param enmType Audio file type to open / create.
1492 * @param pszFile File path of file to open or create.
1493 * @param fFlags Audio file flags.
1494 * @param ppFile Where to store the created audio file handle.
1495 * Needs to be destroyed with DrvAudioHlpFileDestroy().
1496 */
1497int DrvAudioHlpFileCreate(PDMAUDIOFILETYPE enmType, const char *pszFile, PDMAUDIOFILEFLAGS fFlags, PPDMAUDIOFILE *ppFile)
1498{
1499 AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
1500 /** @todo Validate fFlags. */
1501
1502 PPDMAUDIOFILE pFile = (PPDMAUDIOFILE)RTMemAlloc(sizeof(PDMAUDIOFILE));
1503 if (!pFile)
1504 return VERR_NO_MEMORY;
1505
1506 int rc = VINF_SUCCESS;
1507
1508 switch (enmType)
1509 {
1510 case PDMAUDIOFILETYPE_RAW:
1511 case PDMAUDIOFILETYPE_WAV:
1512 pFile->enmType = enmType;
1513 break;
1514
1515 default:
1516 rc = VERR_INVALID_PARAMETER;
1517 break;
1518 }
1519
1520 if (RT_SUCCESS(rc))
1521 {
1522 RTStrPrintf(pFile->szName, RT_ELEMENTS(pFile->szName), "%s", pszFile);
1523 pFile->hFile = NIL_RTFILE;
1524 pFile->fFlags = fFlags;
1525 pFile->pvData = NULL;
1526 pFile->cbData = 0;
1527 }
1528
1529 if (RT_FAILURE(rc))
1530 {
1531 RTMemFree(pFile);
1532 pFile = NULL;
1533 }
1534 else
1535 *ppFile = pFile;
1536
1537 return rc;
1538}
1539
1540/**
1541 * Destroys a formerly created audio file.
1542 *
1543 * @param pFile Audio file (object) to destroy.
1544 */
1545void DrvAudioHlpFileDestroy(PPDMAUDIOFILE pFile)
1546{
1547 if (!pFile)
1548 return;
1549
1550 DrvAudioHlpFileClose(pFile);
1551
1552 RTMemFree(pFile);
1553 pFile = NULL;
1554}
1555
1556/**
1557 * Opens or creates an audio file.
1558 *
1559 * @returns IPRT status code.
1560 * @param pFile Pointer to audio file handle to use.
1561 * @param fOpen Open flags.
1562 * Use PDMAUDIOFILE_DEFAULT_OPEN_FLAGS for the default open flags.
1563 * @param pProps PCM properties to use.
1564 */
1565int DrvAudioHlpFileOpen(PPDMAUDIOFILE pFile, uint32_t fOpen, const PPDMAUDIOPCMPROPS pProps)
1566{
1567 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1568 /** @todo Validate fOpen flags. */
1569 AssertPtrReturn(pProps, VERR_INVALID_POINTER);
1570
1571 int rc;
1572
1573 if (pFile->enmType == PDMAUDIOFILETYPE_RAW)
1574 {
1575 rc = RTFileOpen(&pFile->hFile, pFile->szName, fOpen);
1576 }
1577 else if (pFile->enmType == PDMAUDIOFILETYPE_WAV)
1578 {
1579 Assert(pProps->cChannels);
1580 Assert(pProps->uHz);
1581 Assert(pProps->cBits);
1582
1583 pFile->pvData = (PAUDIOWAVFILEDATA)RTMemAllocZ(sizeof(AUDIOWAVFILEDATA));
1584 if (pFile->pvData)
1585 {
1586 pFile->cbData = sizeof(PAUDIOWAVFILEDATA);
1587
1588 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1589 AssertPtr(pData);
1590
1591 /* Header. */
1592 pData->Hdr.u32RIFF = AUDIO_MAKE_FOURCC('R','I','F','F');
1593 pData->Hdr.u32Size = 36;
1594 pData->Hdr.u32WAVE = AUDIO_MAKE_FOURCC('W','A','V','E');
1595
1596 pData->Hdr.u32Fmt = AUDIO_MAKE_FOURCC('f','m','t',' ');
1597 pData->Hdr.u32Size1 = 16; /* Means PCM. */
1598 pData->Hdr.u16AudioFormat = 1; /* PCM, linear quantization. */
1599 pData->Hdr.u16NumChannels = pProps->cChannels;
1600 pData->Hdr.u32SampleRate = pProps->uHz;
1601 pData->Hdr.u32ByteRate = DrvAudioHlpCalcBitrate(pProps->cBits, pProps->uHz, pProps->cChannels) / 8;
1602 pData->Hdr.u16BlockAlign = pProps->cChannels * pProps->cBits / 8;
1603 pData->Hdr.u16BitsPerSample = pProps->cBits;
1604
1605 /* Data chunk. */
1606 pData->Hdr.u32ID2 = AUDIO_MAKE_FOURCC('d','a','t','a');
1607 pData->Hdr.u32Size2 = 0;
1608
1609 rc = RTFileOpen(&pFile->hFile, pFile->szName, fOpen);
1610 if (RT_SUCCESS(rc))
1611 {
1612 rc = RTFileWrite(pFile->hFile, &pData->Hdr, sizeof(pData->Hdr), NULL);
1613 if (RT_FAILURE(rc))
1614 {
1615 RTFileClose(pFile->hFile);
1616 pFile->hFile = NIL_RTFILE;
1617 }
1618 }
1619
1620 if (RT_FAILURE(rc))
1621 {
1622 RTMemFree(pFile->pvData);
1623 pFile->pvData = NULL;
1624 pFile->cbData = 0;
1625 }
1626 }
1627 else
1628 rc = VERR_NO_MEMORY;
1629 }
1630 else
1631 rc = VERR_INVALID_PARAMETER;
1632
1633 if (RT_SUCCESS(rc))
1634 {
1635 LogRel2(("Audio: Opened file '%s'\n", pFile->szName));
1636 }
1637 else
1638 LogRel(("Audio: Failed opening file '%s', rc=%Rrc\n", pFile->szName, rc));
1639
1640 return rc;
1641}
1642
1643/**
1644 * Closes an audio file.
1645 *
1646 * @returns IPRT status code.
1647 * @param pFile Audio file handle to close.
1648 */
1649int DrvAudioHlpFileClose(PPDMAUDIOFILE pFile)
1650{
1651 if (!pFile)
1652 return VINF_SUCCESS;
1653
1654 size_t cbSize = DrvAudioHlpFileGetDataSize(pFile);
1655
1656 int rc = VINF_SUCCESS;
1657
1658 if (pFile->enmType == PDMAUDIOFILETYPE_RAW)
1659 {
1660 if (RTFileIsValid(pFile->hFile))
1661 rc = RTFileClose(pFile->hFile);
1662 }
1663 else if (pFile->enmType == PDMAUDIOFILETYPE_WAV)
1664 {
1665 if (RTFileIsValid(pFile->hFile))
1666 {
1667 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1668 if (pData) /* The .WAV file data only is valid when a file actually has been created. */
1669 {
1670 /* Update the header with the current data size. */
1671 RTFileWriteAt(pFile->hFile, 0, &pData->Hdr, sizeof(pData->Hdr), NULL);
1672 }
1673
1674 rc = RTFileClose(pFile->hFile);
1675 }
1676
1677 if (pFile->pvData)
1678 {
1679 RTMemFree(pFile->pvData);
1680 pFile->pvData = NULL;
1681 }
1682 }
1683 else
1684 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
1685
1686 if ( RT_SUCCESS(rc)
1687 && !cbSize
1688 && !(pFile->fFlags & PDMAUDIOFILE_FLAG_KEEP_IF_EMPTY))
1689 {
1690 rc = DrvAudioHlpFileDelete(pFile);
1691 }
1692
1693 pFile->cbData = 0;
1694
1695 if (RT_SUCCESS(rc))
1696 {
1697 pFile->hFile = NIL_RTFILE;
1698 LogRel2(("Audio: Closed file '%s' (%zu bytes)\n", pFile->szName, cbSize));
1699 }
1700 else
1701 LogRel(("Audio: Failed closing file '%s', rc=%Rrc\n", pFile->szName, rc));
1702
1703 return rc;
1704}
1705
1706/**
1707 * Deletes an audio file.
1708 *
1709 * @returns IPRT status code.
1710 * @param pFile Audio file handle to delete.
1711 */
1712int DrvAudioHlpFileDelete(PPDMAUDIOFILE pFile)
1713{
1714 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1715
1716 int rc = RTFileDelete(pFile->szName);
1717 if (RT_SUCCESS(rc))
1718 {
1719 LogRel2(("Audio: Deleted file '%s'\n", pFile->szName));
1720 }
1721 else if (rc == VERR_FILE_NOT_FOUND) /* Don't bitch if the file is not around (anymore). */
1722 rc = VINF_SUCCESS;
1723
1724 if (RT_FAILURE(rc))
1725 LogRel(("Audio: Failed deleting file '%s', rc=%Rrc\n", pFile->szName, rc));
1726
1727 return rc;
1728}
1729
1730/**
1731 * Returns the raw audio data size of an audio file.
1732 *
1733 * Note: This does *not* include file headers and other data which does
1734 * not belong to the actual PCM audio data.
1735 *
1736 * @returns Size (in bytes) of the raw PCM audio data.
1737 * @param pFile Audio file handle to retrieve the audio data size for.
1738 */
1739size_t DrvAudioHlpFileGetDataSize(PPDMAUDIOFILE pFile)
1740{
1741 AssertPtrReturn(pFile, 0);
1742
1743 size_t cbSize = 0;
1744
1745 if (pFile->enmType == PDMAUDIOFILETYPE_RAW)
1746 {
1747 cbSize = RTFileTell(pFile->hFile);
1748 }
1749 else if (pFile->enmType == PDMAUDIOFILETYPE_WAV)
1750 {
1751 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1752 if (pData) /* The .WAV file data only is valid when a file actually has been created. */
1753 cbSize = pData->Hdr.u32Size2;
1754 }
1755
1756 return cbSize;
1757}
1758
1759/**
1760 * Returns whether the given audio file is open and in use or not.
1761 *
1762 * @return bool True if open, false if not.
1763 * @param pFile Audio file handle to check open status for.
1764 */
1765bool DrvAudioHlpFileIsOpen(PPDMAUDIOFILE pFile)
1766{
1767 if (!pFile)
1768 return false;
1769
1770 return RTFileIsValid(pFile->hFile);
1771}
1772
1773/**
1774 * Write PCM data to a wave (.WAV) file.
1775 *
1776 * @returns IPRT status code.
1777 * @param pFile Audio file handle to write PCM data to.
1778 * @param pvBuf Audio data to write.
1779 * @param cbBuf Size (in bytes) of audio data to write.
1780 * @param fFlags Additional write flags. Not being used at the moment and must be 0.
1781 */
1782int DrvAudioHlpFileWrite(PPDMAUDIOFILE pFile, const void *pvBuf, size_t cbBuf, uint32_t fFlags)
1783{
1784 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1785 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1786
1787 AssertReturn(fFlags == 0, VERR_INVALID_PARAMETER); /** @todo fFlags are currently not implemented. */
1788
1789 if (!cbBuf)
1790 return VINF_SUCCESS;
1791
1792 AssertReturn(RTFileIsValid(pFile->hFile), VERR_WRONG_ORDER);
1793
1794 int rc;
1795
1796 if (pFile->enmType == PDMAUDIOFILETYPE_RAW)
1797 {
1798 rc = RTFileWrite(pFile->hFile, pvBuf, cbBuf, NULL);
1799 }
1800 else if (pFile->enmType == PDMAUDIOFILETYPE_WAV)
1801 {
1802 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1803 AssertPtr(pData);
1804
1805 rc = RTFileWrite(pFile->hFile, pvBuf, cbBuf, NULL);
1806 if (RT_SUCCESS(rc))
1807 {
1808 pData->Hdr.u32Size += (uint32_t)cbBuf;
1809 pData->Hdr.u32Size2 += (uint32_t)cbBuf;
1810 }
1811 }
1812 else
1813 rc = VERR_NOT_SUPPORTED;
1814
1815 return rc;
1816}
1817
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