VirtualBox

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

Last change on this file since 63848 was 63743, checked in by vboxsync, 8 years ago

Audio: More code for device enumeration and dynamic device handling / switching.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 36.0 KB
Line 
1/* $Id: DrvAudioCommon.cpp 63743 2016-09-07 09:26:22Z vboxsync $ */
2/** @file
3 * Intermedia audio driver, common routines. These are also used
4 * in the drivers which are bound to Main, e.g. the VRDE or the
5 * video audio recording drivers.
6 */
7
8/*
9 * Copyright (C) 2006-2016 Oracle Corporation
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 * --------------------------------------------------------------------
19 *
20 * This code is based on: audio_template.h from QEMU AUDIO subsystem.
21 *
22 * QEMU Audio subsystem header
23 *
24 * Copyright (c) 2005 Vassili Karpov (malc)
25 *
26 * Permission is hereby granted, free of charge, to any person obtaining a copy
27 * of this software and associated documentation files (the "Software"), to deal
28 * in the Software without restriction, including without limitation the rights
29 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30 * copies of the Software, and to permit persons to whom the Software is
31 * furnished to do so, subject to the following conditions:
32 *
33 * The above copyright notice and this permission notice shall be included in
34 * all copies or substantial portions of the Software.
35 *
36 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
39 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
42 * THE SOFTWARE.
43 */
44#include <iprt/alloc.h>
45#include <iprt/asm-math.h>
46#include <iprt/assert.h>
47#include <iprt/dir.h>
48#include <iprt/file.h>
49#include <iprt/string.h>
50#include <iprt/uuid.h>
51
52#define LOG_GROUP LOG_GROUP_DRV_AUDIO
53#include <VBox/log.h>
54
55#include <VBox/err.h>
56#include <VBox/vmm/pdmdev.h>
57#include <VBox/vmm/pdm.h>
58#include <VBox/vmm/mm.h>
59
60#include <ctype.h>
61#include <stdlib.h>
62
63#include "DrvAudio.h"
64#include "AudioMixBuffer.h"
65
66#pragma pack(1)
67/**
68 * Structure for building up a .WAV file header.
69 */
70typedef struct AUDIOWAVFILEHDR
71{
72 uint32_t u32RIFF;
73 uint32_t u32Size;
74 uint32_t u32WAVE;
75
76 uint32_t u32Fmt;
77 uint32_t u32Size1;
78 uint16_t u16AudioFormat;
79 uint16_t u16NumChannels;
80 uint32_t u32SampleRate;
81 uint32_t u32ByteRate;
82 uint16_t u16BlockAlign;
83 uint16_t u16BitsPerSample;
84
85 uint32_t u32ID2;
86 uint32_t u32Size2;
87} AUDIOWAVFILEHDR, *PAUDIOWAVFILEHDR;
88#pragma pack()
89
90/**
91 * Structure for keeeping the internal .WAV file data
92 */
93typedef struct AUDIOWAVFILEDATA
94{
95 /** The file header/footer. */
96 AUDIOWAVFILEHDR Hdr;
97} AUDIOWAVFILEDATA, *PAUDIOWAVFILEDATA;
98
99/**
100 * Retrieves the matching PDMAUDIOFMT for given bits + signing flag.
101 *
102 * @return IPRT status code.
103 * @return PDMAUDIOFMT Resulting audio format or PDMAUDIOFMT_INVALID if invalid.
104 * @param cBits Bits to retrieve audio format for.
105 * @param fSigned Signed flag for bits to retrieve audio format for.
106 */
107PDMAUDIOFMT DrvAudioAudFmtBitsToAudFmt(uint8_t cBits, bool fSigned)
108{
109 if (fSigned)
110 {
111 switch (cBits)
112 {
113 case 8: return PDMAUDIOFMT_S8;
114 case 16: return PDMAUDIOFMT_S16;
115 case 32: return PDMAUDIOFMT_S32;
116 default: break;
117 }
118 }
119 else
120 {
121 switch (cBits)
122 {
123 case 8: return PDMAUDIOFMT_U8;
124 case 16: return PDMAUDIOFMT_U16;
125 case 32: return PDMAUDIOFMT_U32;
126 default: break;
127 }
128 }
129
130 AssertMsgFailed(("Bogus audio bits %RU8\n", cBits));
131 return PDMAUDIOFMT_INVALID;
132}
133
134/**
135 * Clears a sample buffer by the given amount of audio samples.
136 *
137 * @return IPRT status code.
138 * @param pPCMProps PCM properties to use for the buffer to clear.
139 * @param pvBuf Buffer to clear.
140 * @param cbBuf Size (in bytes) of the buffer.
141 * @param cSamples Number of audio samples to clear in the buffer.
142 */
143void DrvAudioHlpClearBuf(PPDMAUDIOPCMPROPS pPCMProps, void *pvBuf, size_t cbBuf, uint32_t cSamples)
144{
145 AssertPtrReturnVoid(pPCMProps);
146 AssertPtrReturnVoid(pvBuf);
147
148 if (!cbBuf || !cSamples)
149 return;
150
151 Log2Func(("pPCMInfo=%p, pvBuf=%p, cSamples=%RU32, fSigned=%RTbool, cBits=%RU8, cShift=%RU8\n",
152 pPCMProps, pvBuf, cSamples, pPCMProps->fSigned, pPCMProps->cBits, pPCMProps->cShift));
153
154 if (pPCMProps->fSigned)
155 {
156 memset(pvBuf, 0, cSamples << pPCMProps->cShift);
157 }
158 else
159 {
160 switch (pPCMProps->cBits)
161 {
162 case 8:
163 {
164 memset(pvBuf, 0x80, cSamples << pPCMProps->cShift);
165 break;
166 }
167
168 case 16:
169 {
170 uint16_t *p = (uint16_t *)pvBuf;
171 int shift = pPCMProps->cChannels - 1;
172 short s = INT16_MAX;
173
174 if (pPCMProps->fSwapEndian)
175 s = RT_BSWAP_U16(s);
176
177 for (unsigned i = 0; i < cSamples << shift; i++)
178 p[i] = s;
179
180 break;
181 }
182
183 case 32:
184 {
185 uint32_t *p = (uint32_t *)pvBuf;
186 int shift = pPCMProps->cChannels - 1;
187 int32_t s = INT32_MAX;
188
189 if (pPCMProps->fSwapEndian)
190 s = RT_BSWAP_U32(s);
191
192 for (unsigned i = 0; i < cSamples << shift; i++)
193 p[i] = s;
194
195 break;
196 }
197
198 default:
199 {
200 AssertMsgFailed(("Invalid bits: %RU8\n", pPCMProps->cBits));
201 break;
202 }
203 }
204 }
205}
206
207/**
208 * Allocates an audio device.
209 *
210 * @returns Newly allocated audio device, or NULL if failed.
211 * @param cbData How much additional data (in bytes) should be allocated to provide
212 * a (backend) specific area to store additional data.
213 * Optional, can be 0.
214 */
215PPDMAUDIODEVICE DrvAudioHlpDeviceAlloc(size_t cbData)
216{
217 PPDMAUDIODEVICE pDev = (PPDMAUDIODEVICE)RTMemAllocZ(sizeof(PDMAUDIODEVICE));
218 if (!pDev)
219 return NULL;
220
221 if (cbData)
222 {
223 pDev->pvData = RTMemAllocZ(cbData);
224 if (!pDev->pvData)
225 {
226 RTMemFree(pDev);
227 return NULL;
228 }
229 }
230
231 pDev->cbData = cbData;
232
233 pDev->cMaxInputChannels = 0;
234 pDev->cMaxOutputChannels = 0;
235
236 return pDev;
237}
238
239/**
240 * Frees an audio device.
241 *
242 * @param pDev Device to free.
243 */
244void DrvAudioHlpDeviceFree(PPDMAUDIODEVICE pDev)
245{
246 if (!pDev)
247 return;
248
249 Assert(pDev->cRefCount == 0);
250
251 if (pDev->pvData)
252 {
253 Assert(pDev->cbData);
254
255 RTMemFree(pDev->pvData);
256 pDev->pvData = NULL;
257 }
258
259 RTMemFree(pDev);
260 pDev = NULL;
261}
262
263/**
264 * Duplicates an audio device entry.
265 *
266 * @returns Duplicated audio device entry on success, or NULL on failure.
267 * @param pDev Audio device entry to duplicate.
268 * @param fCopyUserData Whether to also copy the user data portion or not.
269 */
270PPDMAUDIODEVICE DrvAudioHlpDeviceDup(PPDMAUDIODEVICE pDev, bool fCopyUserData)
271{
272 AssertPtrReturn(pDev, NULL);
273
274 PPDMAUDIODEVICE pDevDup = DrvAudioHlpDeviceAlloc(fCopyUserData ? pDev->cbData : 0);
275 if (pDevDup)
276 {
277 memcpy(pDevDup, pDev, sizeof(PDMAUDIODEVICE));
278
279 if ( fCopyUserData
280 && pDevDup->cbData)
281 {
282 memcpy(pDevDup->pvData, pDev->pvData, pDevDup->cbData);
283 }
284 else
285 {
286 pDevDup->cbData = 0;
287 pDevDup->pvData = NULL;
288 }
289 }
290
291 return pDevDup;
292}
293
294/**
295 * Initializes an audio device enumeration structure.
296 *
297 * @returns IPRT status code.
298 * @param pDevEnm Device enumeration to initialize.
299 */
300int DrvAudioHlpDeviceEnumInit(PPDMAUDIODEVICEENUM pDevEnm)
301{
302 AssertPtrReturn(pDevEnm, VERR_INVALID_POINTER);
303
304 RTListInit(&pDevEnm->lstDevices);
305 pDevEnm->cDevices = 0;
306
307 return VINF_SUCCESS;
308}
309
310/**
311 * Frees audio device enumeration data.
312 *
313 * @param pDevEnm Device enumeration to destroy.
314 */
315void DrvAudioHlpDeviceEnumFree(PPDMAUDIODEVICEENUM pDevEnm)
316{
317 if (!pDevEnm)
318 return;
319
320 PPDMAUDIODEVICE pDev, pDevNext;
321 RTListForEachSafe(&pDevEnm->lstDevices, pDev, pDevNext, PDMAUDIODEVICE, Node)
322 {
323 RTListNodeRemove(&pDev->Node);
324
325 DrvAudioHlpDeviceFree(pDev);
326
327 pDevEnm->cDevices--;
328 }
329
330 /* Sanity. */
331 Assert(RTListIsEmpty(&pDevEnm->lstDevices));
332 Assert(pDevEnm->cDevices == 0);
333}
334
335/**
336 * Adds an audio device to a device enumeration.
337 *
338 * @return IPRT status code.
339 * @param pDevEnm Device enumeration to add device to.
340 * @param pDev Device to add. The pointer will be owned by the device enumeration then.
341 */
342int DrvAudioHlpDeviceEnumAdd(PPDMAUDIODEVICEENUM pDevEnm, PPDMAUDIODEVICE pDev)
343{
344 AssertPtrReturn(pDevEnm, VERR_INVALID_POINTER);
345 AssertPtrReturn(pDev, VERR_INVALID_POINTER);
346
347 RTListAppend(&pDevEnm->lstDevices, &pDev->Node);
348 pDevEnm->cDevices++;
349
350 return VINF_SUCCESS;
351}
352
353/**
354 * Duplicates a device enumeration.
355 *
356 * @returns Duplicated device enumeration, or NULL on failure.
357 * Must be free'd with DrvAudioHlpDeviceEnumFree().
358 * @param pDevEnm Device enumeration to duplicate.
359 */
360PPDMAUDIODEVICEENUM DrvAudioHlpDeviceEnumDup(PPDMAUDIODEVICEENUM pDevEnm)
361{
362 AssertPtrReturn(pDevEnm, NULL);
363
364 PPDMAUDIODEVICEENUM pDevEnmDup = (PPDMAUDIODEVICEENUM)RTMemAlloc(sizeof(PDMAUDIODEVICEENUM));
365 if (!pDevEnmDup)
366 return NULL;
367
368 int rc2 = DrvAudioHlpDeviceEnumInit(pDevEnmDup);
369 AssertRC(rc2);
370
371 PPDMAUDIODEVICE pDev;
372 RTListForEach(&pDevEnm->lstDevices, pDev, PDMAUDIODEVICE, Node)
373 {
374 PPDMAUDIODEVICE pDevDup = DrvAudioHlpDeviceDup(pDev, true /* fCopyUserData */);
375 if (!pDevDup)
376 {
377 rc2 = VERR_NO_MEMORY;
378 break;
379 }
380
381 rc2 = DrvAudioHlpDeviceEnumAdd(pDevEnmDup, pDevDup);
382 if (RT_FAILURE(rc2))
383 {
384 DrvAudioHlpDeviceFree(pDevDup);
385 break;
386 }
387 }
388
389 if (RT_FAILURE(rc2))
390 {
391 DrvAudioHlpDeviceEnumFree(pDevEnmDup);
392 pDevEnmDup = NULL;
393 }
394
395 return pDevEnmDup;
396}
397
398/**
399 * Copies device enumeration entries from the source to the destination enumeration.
400 *
401 * @returns IPRT status code.
402 * @param pDstDevEnm Destination enumeration to store enumeration entries into.
403 * @param pSrcDevEnm Source enumeration to use.
404 * @param enmUsage Which entries to copy. Specify PDMAUDIODIR_ANY to copy all entries.
405 * @param fCopyUserData Whether to also copy the user data portion or not.
406 */
407int DrvAudioHlpDeviceEnumCopyEx(PPDMAUDIODEVICEENUM pDstDevEnm, PPDMAUDIODEVICEENUM pSrcDevEnm,
408 PDMAUDIODIR enmUsage, bool fCopyUserData)
409{
410 AssertPtrReturn(pDstDevEnm, VERR_INVALID_POINTER);
411 AssertPtrReturn(pSrcDevEnm, VERR_INVALID_POINTER);
412
413 int rc = VINF_SUCCESS;
414
415 PPDMAUDIODEVICE pSrcDev;
416 RTListForEach(&pSrcDevEnm->lstDevices, pSrcDev, PDMAUDIODEVICE, Node)
417 {
418 if ( enmUsage != PDMAUDIODIR_ANY
419 && enmUsage != pSrcDev->enmUsage)
420 {
421 continue;
422 }
423
424 PPDMAUDIODEVICE pDstDev = DrvAudioHlpDeviceDup(pSrcDev, fCopyUserData);
425 if (!pDstDev)
426 {
427 rc = VERR_NO_MEMORY;
428 break;
429 }
430
431 rc = DrvAudioHlpDeviceEnumAdd(pDstDevEnm, pDstDev);
432 if (RT_FAILURE(rc))
433 break;
434 }
435
436 return rc;
437}
438
439/**
440 * Copies all device enumeration entries from the source to the destination enumeration.
441 *
442 * Note: Does *not* copy the user-specific data assigned to a device enumeration entry.
443 * To do so, use DrvAudioHlpDeviceEnumCopyEx().
444 *
445 * @returns IPRT status code.
446 * @param pDstDevEnm Destination enumeration to store enumeration entries into.
447 * @param pSrcDevEnm Source enumeration to use.
448 */
449int DrvAudioHlpDeviceEnumCopy(PPDMAUDIODEVICEENUM pDstDevEnm, PPDMAUDIODEVICEENUM pSrcDevEnm)
450{
451 return DrvAudioHlpDeviceEnumCopyEx(pDstDevEnm, pSrcDevEnm, PDMAUDIODIR_ANY, false /* fCopyUserData */);
452}
453
454/**
455 * Returns the default device of a given device enumeration.
456 * This assumes that only one default device per usage is set.
457 *
458 * @returns Default device if found, or NULL if none found.
459 * @param pDevEnm Device enumeration to get default device for.
460 * @param enmUsage Usage to get default device for.
461 */
462PPDMAUDIODEVICE DrvAudioHlpDeviceEnumGetDefaultDevice(PPDMAUDIODEVICEENUM pDevEnm, PDMAUDIODIR enmUsage)
463{
464 AssertPtrReturn(pDevEnm, NULL);
465
466 PPDMAUDIODEVICE pDev;
467 RTListForEach(&pDevEnm->lstDevices, pDev, PDMAUDIODEVICE, Node)
468 {
469 if (enmUsage != PDMAUDIODIR_ANY)
470 {
471 if (enmUsage != pDev->enmUsage) /* Wrong usage? Skip. */
472 continue;
473 }
474
475 if (pDev->fFlags & PDMAUDIODEV_FLAGS_DEFAULT)
476 return pDev;
477 }
478
479 return NULL;
480}
481
482/**
483 * Logs an audio device enumeration.
484 *
485 * @param pszDesc Logging description.
486 * @param pDevEnm Device enumeration to log.
487 */
488void DrvAudioHlpDeviceEnumPrint(const char *pszDesc, PPDMAUDIODEVICEENUM pDevEnm)
489{
490 AssertPtrReturnVoid(pszDesc);
491 AssertPtrReturnVoid(pDevEnm);
492
493 LogFunc(("%s: %RU16 devices\n", pszDesc, pDevEnm->cDevices));
494
495 PPDMAUDIODEVICE pDev;
496 RTListForEach(&pDevEnm->lstDevices, pDev, PDMAUDIODEVICE, Node)
497 {
498 char *pszFlags = DrvAudioHlpAudDevFlagsToStrA(pDev->fFlags);
499
500 LogFunc(("Device '%s':\n", pDev->szName));
501 LogFunc(("\tUsage = %s\n", DrvAudioHlpAudDirToStr(pDev->enmUsage)));
502 LogFunc(("\tFlags = %s\n", pszFlags ? pszFlags : "<NONE>"));
503 LogFunc(("\tInput channels = %RU8\n", pDev->cMaxInputChannels));
504 LogFunc(("\tOutput channels = %RU8\n", pDev->cMaxOutputChannels));
505 LogFunc(("\tData = %p (%zu bytes)\n", pDev->pvData, pDev->cbData));
506
507 if (pszFlags)
508 RTStrFree(pszFlags);
509 }
510}
511
512/**
513 * Converts an audio direction to a string.
514 *
515 * @returns Stringified audio direction, or "Unknown", if not found.
516 * @param enmDir Audio direction to convert.
517 */
518const char *DrvAudioHlpAudDirToStr(PDMAUDIODIR enmDir)
519{
520 switch (enmDir)
521 {
522 case PDMAUDIODIR_UNKNOWN: return "Unknown";
523 case PDMAUDIODIR_IN: return "Input";
524 case PDMAUDIODIR_OUT: return "Output";
525 case PDMAUDIODIR_ANY: return "Duplex";
526 default: break;
527 }
528
529 AssertMsgFailed(("Invalid audio direction %ld\n", enmDir));
530 return "Unknown";
531}
532
533/**
534 * Converts an audio device flags to a string.
535 *
536 * @returns Stringified audio flags. Must be free'd with RTStrFree().
537 * NULL if no flags set.
538 * @param fFlags Audio flags to convert.
539 */
540char *DrvAudioHlpAudDevFlagsToStrA(PDMAUDIODEVFLAG fFlags)
541{
542
543#define APPEND_FLAG_TO_STR(_aFlag) \
544 if (fFlags & PDMAUDIODEV_FLAGS_##_aFlag) \
545 { \
546 if (pszFlags) \
547 { \
548 rc2 = RTStrAAppend(&pszFlags, " "); \
549 if (RT_FAILURE(rc2)) \
550 break; \
551 } \
552 \
553 rc2 = RTStrAAppend(&pszFlags, #_aFlag); \
554 if (RT_FAILURE(rc2)) \
555 break; \
556 } \
557
558 char *pszFlags = NULL;
559 int rc2 = VINF_SUCCESS;
560
561 do
562 {
563 APPEND_FLAG_TO_STR(DEFAULT);
564 APPEND_FLAG_TO_STR(HOTPLUG);
565 APPEND_FLAG_TO_STR(BUGGY);
566 APPEND_FLAG_TO_STR(IGNORE);
567
568 } while (0);
569
570 if ( RT_FAILURE(rc2)
571 && pszFlags)
572 {
573 RTStrFree(pszFlags);
574 pszFlags = NULL;
575 }
576
577#undef APPEND_FLAG_TO_STR
578
579 return pszFlags;
580}
581
582/**
583 * Converts a recording source enumeration to a string.
584 *
585 * @returns Stringified recording source, or "Unknown", if not found.
586 * @param enmRecSrc Recording source to convert.
587 */
588const char *DrvAudioHlpRecSrcToStr(PDMAUDIORECSOURCE enmRecSrc)
589{
590 switch (enmRecSrc)
591 {
592 case PDMAUDIORECSOURCE_UNKNOWN: return "Unknown";
593 case PDMAUDIORECSOURCE_MIC: return "Microphone In";
594 case PDMAUDIORECSOURCE_CD: return "CD";
595 case PDMAUDIORECSOURCE_VIDEO: return "Video";
596 case PDMAUDIORECSOURCE_AUX: return "AUX";
597 case PDMAUDIORECSOURCE_LINE: return "Line In";
598 case PDMAUDIORECSOURCE_PHONE: return "Phone";
599 default:
600 break;
601 }
602
603 AssertMsgFailed(("Invalid recording source %ld\n", enmRecSrc));
604 return "Unknown";
605}
606
607/**
608 * Returns wether the given audio format has signed bits or not.
609 *
610 * @return IPRT status code.
611 * @return bool @true for signed bits, @false for unsigned.
612 * @param enmFmt Audio format to retrieve value for.
613 */
614bool DrvAudioHlpAudFmtIsSigned(PDMAUDIOFMT enmFmt)
615{
616 switch (enmFmt)
617 {
618 case PDMAUDIOFMT_S8:
619 case PDMAUDIOFMT_S16:
620 case PDMAUDIOFMT_S32:
621 return true;
622
623 case PDMAUDIOFMT_U8:
624 case PDMAUDIOFMT_U16:
625 case PDMAUDIOFMT_U32:
626 return false;
627
628 default:
629 break;
630 }
631
632 AssertMsgFailed(("Bogus audio format %ld\n", enmFmt));
633 return false;
634}
635
636/**
637 * Returns the bits of a given audio format.
638 *
639 * @return IPRT status code.
640 * @return uint8_t Bits of audio format.
641 * @param enmFmt Audio format to retrieve value for.
642 */
643uint8_t DrvAudioHlpAudFmtToBits(PDMAUDIOFMT enmFmt)
644{
645 switch (enmFmt)
646 {
647 case PDMAUDIOFMT_S8:
648 case PDMAUDIOFMT_U8:
649 return 8;
650
651 case PDMAUDIOFMT_U16:
652 case PDMAUDIOFMT_S16:
653 return 16;
654
655 case PDMAUDIOFMT_U32:
656 case PDMAUDIOFMT_S32:
657 return 32;
658
659 default:
660 break;
661 }
662
663 AssertMsgFailed(("Bogus audio format %ld\n", enmFmt));
664 return 0;
665}
666
667/**
668 * Converts an audio format to a string.
669 *
670 * @returns Stringified audio format, or "Unknown", if not found.
671 * @param enmFmt Audio format to convert.
672 */
673const char *DrvAudioHlpAudFmtToStr(PDMAUDIOFMT enmFmt)
674{
675 switch (enmFmt)
676 {
677 case PDMAUDIOFMT_U8:
678 return "U8";
679
680 case PDMAUDIOFMT_U16:
681 return "U16";
682
683 case PDMAUDIOFMT_U32:
684 return "U32";
685
686 case PDMAUDIOFMT_S8:
687 return "S8";
688
689 case PDMAUDIOFMT_S16:
690 return "S16";
691
692 case PDMAUDIOFMT_S32:
693 return "S32";
694
695 default:
696 break;
697 }
698
699 AssertMsgFailed(("Bogus audio format %ld\n", enmFmt));
700 return "Unknown";
701}
702
703/**
704 * Converts a given string to an audio format.
705 *
706 * @returns Audio format for the given string, or PDMAUDIOFMT_INVALID if not found.
707 * @param pszFmt String to convert to an audio format.
708 */
709PDMAUDIOFMT DrvAudioHlpStrToAudFmt(const char *pszFmt)
710{
711 AssertPtrReturn(pszFmt, PDMAUDIOFMT_INVALID);
712
713 if (!RTStrICmp(pszFmt, "u8"))
714 return PDMAUDIOFMT_U8;
715 else if (!RTStrICmp(pszFmt, "u16"))
716 return PDMAUDIOFMT_U16;
717 else if (!RTStrICmp(pszFmt, "u32"))
718 return PDMAUDIOFMT_U32;
719 else if (!RTStrICmp(pszFmt, "s8"))
720 return PDMAUDIOFMT_S8;
721 else if (!RTStrICmp(pszFmt, "s16"))
722 return PDMAUDIOFMT_S16;
723 else if (!RTStrICmp(pszFmt, "s32"))
724 return PDMAUDIOFMT_S32;
725
726 AssertMsgFailed(("Invalid audio format '%s'\n", pszFmt));
727 return PDMAUDIOFMT_INVALID;
728}
729
730/**
731 * Checks whether the given PCM properties are equal with the given
732 * stream configuration.
733 *
734 * @returns @true if equal, @false if not.
735 * @param pProps PCM properties to compare.
736 * @param pCfg Stream configuration to compare.
737 */
738bool DrvAudioHlpPCMPropsAreEqual(PPDMAUDIOPCMPROPS pProps, PPDMAUDIOSTREAMCFG pCfg)
739{
740 AssertPtrReturn(pProps, false);
741 AssertPtrReturn(pCfg, false);
742
743 int cBits = 8;
744 bool fSigned = false;
745
746 switch (pCfg->enmFormat)
747 {
748 case PDMAUDIOFMT_S8:
749 fSigned = true;
750 case PDMAUDIOFMT_U8:
751 break;
752
753 case PDMAUDIOFMT_S16:
754 fSigned = true;
755 case PDMAUDIOFMT_U16:
756 cBits = 16;
757 break;
758
759 case PDMAUDIOFMT_S32:
760 fSigned = true;
761 case PDMAUDIOFMT_U32:
762 cBits = 32;
763 break;
764
765 default:
766 AssertMsgFailed(("Unknown format %ld\n", pCfg->enmFormat));
767 break;
768 }
769
770 bool fEqual = pProps->uHz == pCfg->uHz
771 && pProps->cChannels == pCfg->cChannels
772 && pProps->fSigned == fSigned
773 && pProps->cBits == cBits
774 && pProps->fSwapEndian == !(pCfg->enmEndianness == PDMAUDIOHOSTENDIANNESS);
775 return fEqual;
776}
777
778/**
779 * Checks whether two given PCM properties are equal.
780 *
781 * @returns @true if equal, @false if not.
782 * @param pProps1 First properties to compare.
783 * @param pProps2 Second properties to compare.
784 */
785bool DrvAudioHlpPCMPropsAreEqual(PPDMAUDIOPCMPROPS pProps1, PPDMAUDIOPCMPROPS pProps2)
786{
787 AssertPtrReturn(pProps1, false);
788 AssertPtrReturn(pProps2, false);
789
790 if (pProps1 == pProps2) /* If the pointers match, take a shortcut. */
791 return true;
792
793 return pProps1->uHz == pProps2->uHz
794 && pProps1->cChannels == pProps2->cChannels
795 && pProps1->fSigned == pProps2->fSigned
796 && pProps1->cBits == pProps2->cBits
797 && pProps1->fSwapEndian == pProps2->fSwapEndian;
798}
799
800/**
801 * Converts PCM properties to a audio stream configuration.
802 *
803 * @return IPRT status code.
804 * @param pPCMProps Pointer to PCM properties to convert.
805 * @param pCfg Pointer to audio stream configuration to store result into.
806 */
807int DrvAudioHlpPCMPropsToStreamCfg(PPDMAUDIOPCMPROPS pPCMProps, PPDMAUDIOSTREAMCFG pCfg)
808{
809 AssertPtrReturn(pPCMProps, VERR_INVALID_POINTER);
810 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
811
812 pCfg->uHz = pPCMProps->uHz;
813 pCfg->cChannels = pPCMProps->cChannels;
814 pCfg->enmFormat = DrvAudioAudFmtBitsToAudFmt(pPCMProps->cBits, pPCMProps->fSigned);
815
816 /** @todo We assume little endian is the default for now. */
817 pCfg->enmEndianness = pPCMProps->fSwapEndian == false ? PDMAUDIOENDIANNESS_LITTLE : PDMAUDIOENDIANNESS_BIG;
818 return VINF_SUCCESS;
819}
820
821/**
822 * Checks whether a given stream configuration is valid or not.
823 *
824 * Returns @true if configuration is valid, @false if not.
825 * @param pCfg Stream configuration to check.
826 */
827bool DrvAudioHlpStreamCfgIsValid(PPDMAUDIOSTREAMCFG pCfg)
828{
829 bool fValid = ( pCfg->cChannels == 1
830 || pCfg->cChannels == 2); /* Either stereo (2) or mono (1), per stream. */
831
832 fValid |= ( pCfg->enmEndianness == PDMAUDIOENDIANNESS_LITTLE
833 || pCfg->enmEndianness == PDMAUDIOENDIANNESS_BIG);
834
835 fValid |= ( pCfg->enmDir == PDMAUDIODIR_IN
836 || pCfg->enmDir == PDMAUDIODIR_OUT);
837
838 if (fValid)
839 {
840 switch (pCfg->enmFormat)
841 {
842 case PDMAUDIOFMT_S8:
843 case PDMAUDIOFMT_U8:
844 case PDMAUDIOFMT_S16:
845 case PDMAUDIOFMT_U16:
846 case PDMAUDIOFMT_S32:
847 case PDMAUDIOFMT_U32:
848 break;
849 default:
850 fValid = false;
851 break;
852 }
853 }
854
855 fValid |= pCfg->uHz > 0;
856 /** @todo Check for defined frequencies supported. */
857
858 return fValid;
859}
860
861/**
862 * Converts an audio stream configuration to matching PCM properties.
863 *
864 * @return IPRT status code.
865 * @param pCfg Audio stream configuration to convert.
866 * @param pProps PCM properties to save result to.
867 */
868int DrvAudioHlpStreamCfgToProps(PPDMAUDIOSTREAMCFG pCfg, PPDMAUDIOPCMPROPS pProps)
869{
870 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
871 AssertPtrReturn(pProps, VERR_INVALID_POINTER);
872
873 int rc = VINF_SUCCESS;
874
875 int cBits = 8, cShift = 0;
876 bool fSigned = false;
877
878 switch (pCfg->enmFormat)
879 {
880 case PDMAUDIOFMT_S8:
881 fSigned = true;
882 case PDMAUDIOFMT_U8:
883 break;
884
885 case PDMAUDIOFMT_S16:
886 fSigned = true;
887 case PDMAUDIOFMT_U16:
888 cBits = 16;
889 cShift = 1;
890 break;
891
892 case PDMAUDIOFMT_S32:
893 fSigned = true;
894 case PDMAUDIOFMT_U32:
895 cBits = 32;
896 cShift = 2;
897 break;
898
899 default:
900 AssertMsgFailed(("Unknown format %ld\n", pCfg->enmFormat));
901 rc = VERR_NOT_SUPPORTED;
902 break;
903 }
904
905 if (RT_SUCCESS(rc))
906 {
907 pProps->uHz = pCfg->uHz;
908 pProps->cBits = cBits;
909 pProps->fSigned = fSigned;
910 pProps->cShift = (pCfg->cChannels == 2) + cShift;
911 pProps->cChannels = pCfg->cChannels;
912 pProps->uAlign = (1 << pProps->cShift) - 1;
913 pProps->fSwapEndian = pCfg->enmEndianness != PDMAUDIOHOSTENDIANNESS;
914 }
915
916 return rc;
917}
918
919/**
920 * Prints an audio stream configuration to the debug log.
921 *
922 * @param pCfg Stream configuration to log.
923 */
924void DrvAudioHlpStreamCfgPrint(PPDMAUDIOSTREAMCFG pCfg)
925{
926 AssertPtrReturnVoid(pCfg);
927
928 LogFlowFunc(("uHz=%RU32, cChannels=%RU8, enmFormat=", pCfg->uHz, pCfg->cChannels));
929
930 switch (pCfg->enmFormat)
931 {
932 case PDMAUDIOFMT_S8:
933 LogFlow(("S8"));
934 break;
935 case PDMAUDIOFMT_U8:
936 LogFlow(("U8"));
937 break;
938 case PDMAUDIOFMT_S16:
939 LogFlow(("S16"));
940 break;
941 case PDMAUDIOFMT_U16:
942 LogFlow(("U16"));
943 break;
944 case PDMAUDIOFMT_S32:
945 LogFlow(("S32"));
946 break;
947 case PDMAUDIOFMT_U32:
948 LogFlow(("U32"));
949 break;
950 default:
951 LogFlow(("invalid(%d)", pCfg->enmFormat));
952 break;
953 }
954
955 LogFlow((", endianness="));
956 switch (pCfg->enmEndianness)
957 {
958 case PDMAUDIOENDIANNESS_LITTLE:
959 LogFlow(("little\n"));
960 break;
961 case PDMAUDIOENDIANNESS_BIG:
962 LogFlow(("big\n"));
963 break;
964 default:
965 LogFlow(("invalid\n"));
966 break;
967 }
968}
969
970/**
971 * Calculates the audio bit rate of the given bits per sample, the Hz and the number
972 * of audio channels.
973 *
974 * Divide the result by 8 to get the byte rate.
975 *
976 * @returns The calculated bit rate.
977 * @param cBits Number of bits per sample.
978 * @param uHz Hz (Hertz) rate.
979 * @param cChannels Number of audio channels.
980 */
981uint32_t DrvAudioHlpCalcBitrate(uint8_t cBits, uint32_t uHz, uint8_t cChannels)
982{
983 return (cBits * uHz * cChannels);
984}
985
986/**
987 * Calculates the audio bit rate out of a given audio stream configuration.
988 *
989 * Divide the result by 8 to get the byte rate.
990 *
991 * @returns The calculated bit rate.
992 * @param pCfg Audio stream configuration to calculate bit rate for.
993 *
994 * @remark
995 */
996uint32_t DrvAudioHlpCalcBitrate(PPDMAUDIOSTREAMCFG pCfg)
997{
998 return DrvAudioHlpCalcBitrate(DrvAudioHlpAudFmtToBits(pCfg->enmFormat), pCfg->uHz, pCfg->cChannels);
999}
1000
1001/**
1002 * Sanitizes the file name component so that unsupported characters
1003 * will be replaced by an underscore ("_").
1004 *
1005 * @return IPRT status code.
1006 * @param pszPath Path to sanitize.
1007 * @param cbPath Size (in bytes) of path to sanitize.
1008 */
1009int DrvAudioHlpSanitizeFileName(char *pszPath, size_t cbPath)
1010{
1011 RT_NOREF(cbPath);
1012 int rc = VINF_SUCCESS;
1013#ifdef RT_OS_WINDOWS
1014 /* Filter out characters not allowed on Windows platforms, put in by
1015 RTTimeSpecToString(). */
1016 /** @todo Use something like RTPathSanitize() if available later some time. */
1017 static RTUNICP const s_uszValidRangePairs[] =
1018 {
1019 ' ', ' ',
1020 '(', ')',
1021 '-', '.',
1022 '0', '9',
1023 'A', 'Z',
1024 'a', 'z',
1025 '_', '_',
1026 0xa0, 0xd7af,
1027 '\0'
1028 };
1029 ssize_t cReplaced = RTStrPurgeComplementSet(pszPath, s_uszValidRangePairs, '_' /* Replacement */);
1030 if (cReplaced < 0)
1031 rc = VERR_INVALID_UTF8_ENCODING;
1032#else
1033 RT_NOREF(pszPath);
1034#endif
1035 return rc;
1036}
1037
1038/**
1039 * Constructs an unique file name, based on the given path and the audio file type.
1040 *
1041 * @returns IPRT status code.
1042 * @param pszFile Where to store the constructed file name.
1043 * @param cchFile Size (in characters) of the file name buffer.
1044 * @param pszPath Base path to use.
1045 * @param pszName A name for better identifying the file. Optional.
1046 * @param enmType Audio file type to construct file name for.
1047 */
1048int DrvAudioHlpGetFileName(char *pszFile, size_t cchFile, const char *pszPath, const char *pszName, PDMAUDIOFILETYPE enmType)
1049{
1050 AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
1051 AssertReturn(cchFile, VERR_INVALID_PARAMETER);
1052 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1053 /* pszName is optional. */
1054
1055 int rc;
1056
1057 do
1058 {
1059 char szFilePath[RTPATH_MAX];
1060 RTStrPrintf(szFilePath, sizeof(szFilePath), "%s", pszPath);
1061
1062 /* Create it when necessary. */
1063 if (!RTDirExists(szFilePath))
1064 {
1065 rc = RTDirCreateFullPath(szFilePath, RTFS_UNIX_IRWXU);
1066 if (RT_FAILURE(rc))
1067 break;
1068 }
1069
1070 /* The actually drop directory consist of the current time stamp and a
1071 * unique number when necessary. */
1072 char pszTime[64];
1073 RTTIMESPEC time;
1074 if (!RTTimeSpecToString(RTTimeNow(&time), pszTime, sizeof(pszTime)))
1075 {
1076 rc = VERR_BUFFER_OVERFLOW;
1077 break;
1078 }
1079
1080 rc = DrvAudioHlpSanitizeFileName(pszTime, sizeof(pszTime));
1081 if (RT_FAILURE(rc))
1082 break;
1083
1084 rc = RTPathAppend(szFilePath, sizeof(szFilePath), pszTime);
1085 if (RT_FAILURE(rc))
1086 break;
1087
1088 if (pszName) /* Optional name given? */
1089 {
1090 rc = RTStrCat(szFilePath, sizeof(szFilePath), "-");
1091 if (RT_FAILURE(rc))
1092 break;
1093
1094 rc = RTStrCat(szFilePath, sizeof(szFilePath), pszName);
1095 if (RT_FAILURE(rc))
1096 break;
1097 }
1098
1099 switch (enmType)
1100 {
1101 case PDMAUDIOFILETYPE_WAV:
1102 rc = RTStrCat(szFilePath, sizeof(szFilePath), ".wav");
1103 break;
1104
1105 default:
1106 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
1107 }
1108
1109 if (RT_FAILURE(rc))
1110 break;
1111
1112 RTStrPrintf(pszFile, cchFile, "%s", szFilePath);
1113
1114 } while (0);
1115
1116 LogFlowFuncLeaveRC(rc);
1117 return rc;
1118}
1119
1120/**
1121 * Opens or creates a wave (.WAV) file.
1122 *
1123 * @returns IPRT status code.
1124 * @param pFile Pointer to audio file handle to use.
1125 * @param pszFile File path of file to open or create.
1126 * @param fOpen Open flags.
1127 * @param pProps PCM properties to use.
1128 * @param fFlags Audio file flags.
1129 */
1130int DrvAudioHlpWAVFileOpen(PPDMAUDIOFILE pFile, const char *pszFile, uint32_t fOpen, PPDMAUDIOPCMPROPS pProps,
1131 PDMAUDIOFILEFLAGS fFlags)
1132{
1133 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1134 AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
1135 /** @todo Validate fOpen flags. */
1136 AssertPtrReturn(pProps, VERR_INVALID_POINTER);
1137 RT_NOREF(fFlags); /** @todo Validate fFlags flags. */
1138
1139 Assert(pProps->cChannels);
1140 Assert(pProps->uHz);
1141 Assert(pProps->cBits);
1142
1143 pFile->pvData = (PAUDIOWAVFILEDATA)RTMemAllocZ(sizeof(AUDIOWAVFILEDATA));
1144 if (!pFile->pvData)
1145 return VERR_NO_MEMORY;
1146 pFile->cbData = sizeof(PAUDIOWAVFILEDATA);
1147
1148 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1149 AssertPtr(pData);
1150
1151 /* Header. */
1152 pData->Hdr.u32RIFF = AUDIO_MAKE_FOURCC('R','I','F','F');
1153 pData->Hdr.u32Size = 36;
1154 pData->Hdr.u32WAVE = AUDIO_MAKE_FOURCC('W','A','V','E');
1155
1156 pData->Hdr.u32Fmt = AUDIO_MAKE_FOURCC('f','m','t',' ');
1157 pData->Hdr.u32Size1 = 16; /* Means PCM. */
1158 pData->Hdr.u16AudioFormat = 1; /* PCM, linear quantization. */
1159 pData->Hdr.u16NumChannels = pProps->cChannels;
1160 pData->Hdr.u32SampleRate = pProps->uHz;
1161 pData->Hdr.u32ByteRate = DrvAudioHlpCalcBitrate(pProps->cBits, pProps->uHz, pProps->cChannels) / 8;
1162 pData->Hdr.u16BlockAlign = pProps->cChannels * pProps->cBits / 8;
1163 pData->Hdr.u16BitsPerSample = pProps->cBits;
1164
1165 /* Data chunk. */
1166 pData->Hdr.u32ID2 = AUDIO_MAKE_FOURCC('d','a','t','a');
1167 pData->Hdr.u32Size2 = 0;
1168
1169 int rc = RTFileOpen(&pFile->hFile, pszFile, fOpen);
1170 if (RT_SUCCESS(rc))
1171 {
1172 rc = RTFileWrite(pFile->hFile, &pData->Hdr, sizeof(pData->Hdr), NULL);
1173 if (RT_FAILURE(rc))
1174 {
1175 RTFileClose(pFile->hFile);
1176 pFile->hFile = NIL_RTFILE;
1177 }
1178 }
1179
1180 if (RT_SUCCESS(rc))
1181 {
1182 pFile->enmType = PDMAUDIOFILETYPE_WAV;
1183
1184 RTStrPrintf(pFile->szName, RT_ELEMENTS(pFile->szName), "%s", pszFile);
1185 }
1186 else
1187 {
1188 RTMemFree(pFile->pvData);
1189 pFile->pvData = NULL;
1190 pFile->cbData = 0;
1191 }
1192
1193 return rc;
1194}
1195
1196/**
1197 * Closes a wave (.WAV) audio file.
1198 *
1199 * @returns IPRT status code.
1200 * @param pFile Audio file handle to close.
1201 */
1202int DrvAudioHlpWAVFileClose(PPDMAUDIOFILE pFile)
1203{
1204 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1205
1206 Assert(pFile->enmType == PDMAUDIOFILETYPE_WAV);
1207
1208 if (pFile->hFile != NIL_RTFILE)
1209 {
1210 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1211 AssertPtr(pData);
1212
1213 /* Update the header with the current data size. */
1214 RTFileWriteAt(pFile->hFile, 0, &pData->Hdr, sizeof(pData->Hdr), NULL);
1215
1216 RTFileClose(pFile->hFile);
1217 pFile->hFile = NIL_RTFILE;
1218 }
1219
1220 if (pFile->pvData)
1221 {
1222 RTMemFree(pFile->pvData);
1223 pFile->pvData = NULL;
1224 }
1225
1226 pFile->cbData = 0;
1227 pFile->enmType = PDMAUDIOFILETYPE_UNKNOWN;
1228
1229 return VINF_SUCCESS;
1230}
1231
1232/**
1233 * Returns the raw PCM audio data size of a wave file.
1234 * This does *not* include file headers and other data which does
1235 * not belong to the actual PCM audio data.
1236 *
1237 * @returns Size (in bytes) of the raw PCM audio data.
1238 * @param pFile Audio file handle to retrieve the audio data size for.
1239 */
1240size_t DrvAudioHlpWAVFileGetDataSize(PPDMAUDIOFILE pFile)
1241{
1242 AssertPtrReturn(pFile, 0);
1243
1244 Assert(pFile->enmType == PDMAUDIOFILETYPE_WAV);
1245
1246 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1247 AssertPtr(pData);
1248
1249 return pData->Hdr.u32Size2;
1250}
1251
1252/**
1253 * Write PCM data to a wave (.WAV) file.
1254 *
1255 * @returns IPRT status code.
1256 * @param pFile Audio file handle to write PCM data to.
1257 * @param pvBuf Audio data to write.
1258 * @param cbBuf Size (in bytes) of audio data to write.
1259 * @param fFlags Additional write flags. Not being used at the moment and must be 0.
1260 */
1261int DrvAudioHlpWAVFileWrite(PPDMAUDIOFILE pFile, const void *pvBuf, size_t cbBuf, uint32_t fFlags)
1262{
1263 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
1264 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1265
1266 AssertReturn(fFlags == 0, VERR_INVALID_PARAMETER); /** @todo fFlags are currently not implemented. */
1267
1268 Assert(pFile->enmType == PDMAUDIOFILETYPE_WAV);
1269
1270 if (!cbBuf)
1271 return VINF_SUCCESS;
1272
1273 PAUDIOWAVFILEDATA pData = (PAUDIOWAVFILEDATA)pFile->pvData;
1274 AssertPtr(pData);
1275
1276 int rc = RTFileWrite(pFile->hFile, pvBuf, cbBuf, NULL);
1277 if (RT_SUCCESS(rc))
1278 {
1279 pData->Hdr.u32Size += (uint32_t)cbBuf;
1280 pData->Hdr.u32Size2 += (uint32_t)cbBuf;
1281 }
1282
1283 return rc;
1284}
1285
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