VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/HDAStream.cpp@ 70965

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

Audio/HDA: Implemented separate timers for per audio stream to a) remove a lot of complexity when it comes to synchronizing data when recording and playing back at the same time and b) to make recording a lot smoother while playing back audio.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.1 KB
Line 
1/* $Id: HDAStream.cpp 70964 2018-02-11 21:25:29Z vboxsync $ */
2/** @file
3 * HDAStream.cpp - Stream functions for HD Audio.
4 */
5
6/*
7 * Copyright (C) 2017-2018 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DEV_HDA
23#include <VBox/log.h>
24
25#include <iprt/mem.h>
26#include <iprt/semaphore.h>
27
28#include <VBox/vmm/pdmdev.h>
29#include <VBox/vmm/pdmaudioifs.h>
30
31#include "DrvAudio.h"
32
33#include "DevHDA.h"
34#include "HDAStream.h"
35
36
37#ifdef IN_RING3
38
39/**
40 * Creates an HDA stream.
41 *
42 * @returns IPRT status code.
43 * @param pStream HDA stream to create.
44 * @param pThis HDA state to assign the HDA stream to.
45 * @param u8SD Stream descriptor number to assign.
46 */
47int hdaStreamCreate(PHDASTREAM pStream, PHDASTATE pThis, uint8_t u8SD)
48{
49 RT_NOREF(pThis);
50 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
51
52 pStream->u8SD = u8SD;
53 pStream->pMixSink = NULL;
54 pStream->pHDAState = pThis;
55 pStream->pTimer = pThis->pTimer[u8SD];
56 AssertPtr(pStream->pTimer);
57
58 pStream->State.fInReset = false;
59 pStream->State.fRunning = false;
60#ifdef HDA_USE_DMA_ACCESS_HANDLER
61 RTListInit(&pStream->State.lstDMAHandlers);
62#endif
63
64 int rc = RTCritSectInit(&pStream->CritSect);
65 AssertRCReturn(rc, rc);
66
67 rc = RTCircBufCreate(&pStream->State.pCircBuf, _64K); /** @todo Make this configurable. */
68 AssertRCReturn(rc, rc);
69
70 rc = hdaStreamPeriodCreate(&pStream->State.Period);
71 AssertRCReturn(rc, rc);
72
73#ifdef DEBUG
74 rc = RTCritSectInit(&pStream->Dbg.CritSect);
75 AssertRCReturn(rc, rc);
76#endif
77
78 pStream->Dbg.Runtime.fEnabled = pThis->Dbg.fEnabled;
79
80 if (pStream->Dbg.Runtime.fEnabled)
81 {
82 char szFile[64];
83
84 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
85 RTStrPrintf(szFile, sizeof(szFile), "hdaStreamWriteSD%RU8", pStream->u8SD);
86 else
87 RTStrPrintf(szFile, sizeof(szFile), "hdaStreamReadSD%RU8", pStream->u8SD);
88
89 char szPath[RTPATH_MAX + 1];
90 int rc2 = DrvAudioHlpGetFileName(szPath, sizeof(szPath), pThis->Dbg.szOutPath, szFile,
91 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAG_NONE);
92 AssertRC(rc2);
93 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAG_NONE, &pStream->Dbg.Runtime.pFileStream);
94 AssertRC(rc2);
95
96 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
97 RTStrPrintf(szFile, sizeof(szFile), "hdaDMAWriteSD%RU8", pStream->u8SD);
98 else
99 RTStrPrintf(szFile, sizeof(szFile), "hdaDMAReadSD%RU8", pStream->u8SD);
100
101 rc2 = DrvAudioHlpGetFileName(szPath, sizeof(szPath), pThis->Dbg.szOutPath, szFile,
102 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAG_NONE);
103 AssertRC(rc2);
104
105 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAG_NONE, &pStream->Dbg.Runtime.pFileDMA);
106 AssertRC(rc2);
107
108 /* Delete stale debugging files from a former run. */
109 DrvAudioHlpFileDelete(pStream->Dbg.Runtime.pFileStream);
110 DrvAudioHlpFileDelete(pStream->Dbg.Runtime.pFileDMA);
111 }
112
113 return rc;
114}
115
116/**
117 * Destroys an HDA stream.
118 *
119 * @param pStream HDA stream to destroy.
120 */
121void hdaStreamDestroy(PHDASTREAM pStream)
122{
123 AssertPtrReturnVoid(pStream);
124
125 LogFlowFunc(("[SD%RU8]: Destroying ...\n", pStream->u8SD));
126
127 hdaStreamMapDestroy(&pStream->State.Mapping);
128
129 int rc2;
130
131#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
132 rc2 = hdaStreamAsyncIODestroy(pStream);
133 AssertRC(rc2);
134#endif
135
136 if (RTCritSectIsInitialized(&pStream->CritSect))
137 {
138 rc2 = RTCritSectDelete(&pStream->CritSect);
139 AssertRC(rc2);
140 }
141
142 if (pStream->State.pCircBuf)
143 {
144 RTCircBufDestroy(pStream->State.pCircBuf);
145 pStream->State.pCircBuf = NULL;
146 }
147
148 hdaStreamPeriodDestroy(&pStream->State.Period);
149
150#ifdef DEBUG
151 if (RTCritSectIsInitialized(&pStream->Dbg.CritSect))
152 {
153 rc2 = RTCritSectDelete(&pStream->Dbg.CritSect);
154 AssertRC(rc2);
155 }
156#endif
157
158 if (pStream->Dbg.Runtime.fEnabled)
159 {
160 DrvAudioHlpFileDestroy(pStream->Dbg.Runtime.pFileStream);
161 pStream->Dbg.Runtime.pFileStream = NULL;
162
163 DrvAudioHlpFileDestroy(pStream->Dbg.Runtime.pFileDMA);
164 pStream->Dbg.Runtime.pFileDMA = NULL;
165 }
166
167 LogFlowFuncLeave();
168}
169
170/**
171 * Initializes an HDA stream.
172 *
173 * @returns IPRT status code.
174 * @param pStream HDA stream to initialize.
175 * @param uSD SD (stream descriptor) number to assign the HDA stream to.
176 */
177int hdaStreamInit(PHDASTREAM pStream, uint8_t uSD)
178{
179 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
180
181 PHDASTATE pThis = pStream->pHDAState;
182 AssertPtr(pThis);
183
184 pStream->u8SD = uSD;
185 pStream->u64BDLBase = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, pStream->u8SD),
186 HDA_STREAM_REG(pThis, BDPU, pStream->u8SD));
187 pStream->u16LVI = HDA_STREAM_REG(pThis, LVI, pStream->u8SD);
188 pStream->u32CBL = HDA_STREAM_REG(pThis, CBL, pStream->u8SD);
189 pStream->u16FIFOS = HDA_STREAM_REG(pThis, FIFOS, pStream->u8SD) + 1;
190
191 PPDMAUDIOSTREAMCFG pCfg = &pStream->State.Cfg;
192
193 int rc = hdaSDFMTToPCMProps(HDA_STREAM_REG(pThis, FMT, uSD), &pCfg->Props);
194 if (RT_FAILURE(rc))
195 {
196 LogRel(("HDA: Warning: Format 0x%x for stream #%RU8 not supported\n", HDA_STREAM_REG(pThis, FMT, uSD), uSD));
197 return rc;
198 }
199
200 /* Set the stream's direction. */
201 pCfg->enmDir = hdaGetDirFromSD(pStream->u8SD);
202
203 /* The the stream's name, based on the direction. */
204 switch (pCfg->enmDir)
205 {
206 case PDMAUDIODIR_IN:
207# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
208# error "Implement me!"
209# else
210 pCfg->DestSource.Source = PDMAUDIORECSOURCE_LINE;
211 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
212 RTStrCopy(pCfg->szName, sizeof(pCfg->szName), "Line In");
213# endif
214 break;
215
216 case PDMAUDIODIR_OUT:
217 /* Destination(s) will be set in hdaAddStreamOut(),
218 * based on the channels / stream layout. */
219 break;
220
221 default:
222 rc = VERR_NOT_SUPPORTED;
223 break;
224 }
225
226 if ( !pStream->u32CBL
227 || !pStream->u16LVI
228 || !pStream->u64BDLBase
229 || !pStream->u16FIFOS)
230 {
231 return VINF_SUCCESS;
232 }
233
234 /* Set the stream's frame size. */
235 pStream->State.cbFrameSize = pCfg->Props.cChannels * (pCfg->Props.cBits / 8 /* To bytes */);
236 LogFunc(("[SD%RU8] cChannels=%RU8, cBits=%RU8 -> cbFrameSize=%RU32\n",
237 pStream->u8SD, pCfg->Props.cChannels, pCfg->Props.cBits, pStream->State.cbFrameSize));
238 Assert(pStream->State.cbFrameSize); /* Frame size must not be 0. */
239
240 /*
241 * Initialize the stream mapping in any case, regardless if
242 * we support surround audio or not. This is needed to handle
243 * the supported channels within a single audio stream, e.g. mono/stereo.
244 *
245 * In other words, the stream mapping *always* knows the real
246 * number of channels in a single audio stream.
247 */
248 rc = hdaStreamMapInit(&pStream->State.Mapping, &pCfg->Props);
249 AssertRCReturn(rc, rc);
250
251 LogFunc(("[SD%RU8] DMA @ 0x%x (%RU32 bytes), LVI=%RU16, FIFOS=%RU16, Hz=%RU32, rc=%Rrc\n",
252 pStream->u8SD, pStream->u64BDLBase, pStream->u32CBL, pStream->u16LVI, pStream->u16FIFOS,
253 pStream->State.Cfg.Props.uHz, rc));
254
255 /* Make sure that mandatory parameters are set up correctly. */
256 AssertStmt(pStream->u32CBL % pStream->State.cbFrameSize == 0, rc = VERR_INVALID_PARAMETER);
257 AssertStmt(pStream->u16LVI >= 1, rc = VERR_INVALID_PARAMETER);
258
259 if (RT_SUCCESS(rc))
260 {
261 /* Make sure that the chosen Hz rate dividable by the stream's rate. */
262 if (pStream->State.Cfg.Props.uHz % pThis->u16TimerHz != 0)
263 LogRel(("HDA: Device timer (%RU32) does not fit to stream #RU8 timing (%RU32)\n",
264 pThis->u16TimerHz, pStream->State.Cfg.Props.uHz));
265
266 /* Figure out how many transfer fragments we're going to use for this stream. */
267 /** @todo Use a more dynamic fragment size? */
268 Assert(pStream->u16LVI <= UINT8_MAX - 1);
269 uint8_t cFragments = pStream->u16LVI + 1;
270 if (cFragments <= 1)
271 cFragments = 2; /* At least two fragments (BDLEs) must be present. */
272
273 /*
274 * Handle the stream's position adjustment.
275 */
276 uint32_t cfPosAdjust = 0;
277
278 LogFunc(("[SD%RU8] fPosAdjustEnabled=%RTbool, cPosAdjustFrames=%RU16\n",
279 pStream->u8SD, pThis->fPosAdjustEnabled, pThis->cPosAdjustFrames));
280
281 if (pThis->fPosAdjustEnabled) /* Is the position adjustment enabled at all? */
282 {
283 HDABDLE BDLE;
284 RT_ZERO(BDLE);
285
286 int rc2 = hdaBDLEFetch(pThis, &BDLE, pStream->u64BDLBase, 0 /* Entry */);
287 AssertRC(rc2);
288
289 /* Note: Do *not* check if this BDLE aligns to the stream's frame size.
290 * It can happen that this isn't the case on some guests, e.g.
291 * on Windows with a 5.1 speaker setup.
292 *
293 * The only thing which counts is that the stream's CBL value
294 * properly aligns to the stream's frame size.
295 */
296
297 /* If no custom set position adjustment is set, apply some
298 * simple heuristics to detect the appropriate position adjustment. */
299 if ( !pThis->cPosAdjustFrames
300 /* Position adjustmenet buffer *must* have the IOC bit set! */
301 && hdaBDLENeedsInterrupt(&BDLE))
302 {
303 /** @todo Implement / use a (dynamic) table once this gets more complicated. */
304#ifdef VBOX_WITH_INTEL_HDA
305 /* Intel ICH / PCH: 1 frame. */
306 if (BDLE.Desc.u32BufSize == 1 * pStream->State.cbFrameSize)
307 {
308 cfPosAdjust = 1;
309 }
310 /* Intel Baytrail / Braswell: 32 frames. */
311 else if (BDLE.Desc.u32BufSize == 32 * pStream->State.cbFrameSize)
312 {
313 cfPosAdjust = 32;
314 }
315#endif
316 }
317 else /* Go with the set default. */
318 cfPosAdjust = pThis->cPosAdjustFrames;
319
320 if (cfPosAdjust)
321 {
322 /* Also adjust the number of fragments, as the position adjustment buffer
323 * does not count as an own fragment as such.
324 *
325 * This e.g. can happen on (newer) Ubuntu guests which use
326 * 4 (IOC) + 4408 (IOC) + 4408 (IOC) + 4408 (IOC) + 4404 (= 17632) bytes,
327 * where the first buffer (4) is used as position adjustment.
328 *
329 * Only skip a fragment if the whole buffer fragment is used for
330 * position adjustment.
331 */
332 if ( (cfPosAdjust * pStream->State.cbFrameSize) == BDLE.Desc.u32BufSize
333 && cFragments)
334 {
335 cFragments--;
336 }
337
338 /* Initialize position adjustment counter. */
339 pStream->State.cPosAdjustFramesLeft = cfPosAdjust;
340 LogRel2(("HDA: Position adjustment for stream #%RU8 active (%RU32 frames)\n", pStream->u8SD, cfPosAdjust));
341 }
342 }
343
344 LogFunc(("[SD%RU8] cfPosAdjust=%RU32, cFragments=%RU8\n", pStream->u8SD, cfPosAdjust, cFragments));
345
346 /*
347 * Set up data transfer transfer stuff.
348 */
349
350 /* Calculate the fragment size the guest OS expects interrupt delivery at. */
351 pStream->State.cbTransferSize = pStream->u32CBL / cFragments;
352 Assert(pStream->State.cbTransferSize);
353 Assert(pStream->State.cbTransferSize % pStream->State.cbFrameSize == 0);
354
355 /* Calculate the bytes we need to transfer to / from the stream's DMA per iteration.
356 * This is bound to the device's Hz rate and thus to the (virtual) timing the device expects. */
357 pStream->State.cbTransferChunk = (pStream->State.Cfg.Props.uHz / pThis->u16TimerHz) * pStream->State.cbFrameSize;
358 Assert(pStream->State.cbTransferChunk);
359 Assert(pStream->State.cbTransferChunk % pStream->State.cbFrameSize == 0);
360
361 /* Make sure that the transfer chunk does not exceed the overall transfer size. */
362 if (pStream->State.cbTransferChunk > pStream->State.cbTransferSize)
363 pStream->State.cbTransferChunk = pStream->State.cbTransferSize;
364
365 pStream->State.cbTransferProcessed = 0;
366 pStream->State.cTransferPendingInterrupts = 0;
367 pStream->State.cbDMALeft = 0;
368
369 const uint64_t cTicksPerHz = TMTimerGetFreq(pStream->pTimer) / pThis->u16TimerHz;
370
371 /* Calculate the timer ticks per byte for this stream. */
372 pStream->State.cTicksPerByte = cTicksPerHz / pStream->State.cbTransferChunk;
373 Assert(pStream->State.cTicksPerByte);
374
375 /* Calculate timer ticks per transfer. */
376 pStream->State.cTransferTicks = pStream->State.cbTransferChunk * pStream->State.cTicksPerByte;
377 Assert(pStream->State.cTransferTicks);
378
379 /* Initialize the transfer timestamps. */
380 pStream->State.tsTransferLast = 0;
381 pStream->State.tsTransferNext = 0;
382
383 LogFunc(("[SD%RU8] Timer %uHz (%RU64 ticks per Hz), cTicksPerByte=%RU64, cbTransferChunk=%RU32, cTransferTicks=%RU64, " \
384 "cbTransferSize=%RU32\n",
385 pStream->u8SD, pThis->u16TimerHz, cTicksPerHz, pStream->State.cTicksPerByte,
386 pStream->State.cbTransferChunk, pStream->State.cTransferTicks, pStream->State.cbTransferSize));
387
388 /* Make sure to also update the stream's DMA counter (based on its current LPIB value). */
389 hdaStreamSetPosition(pStream, HDA_STREAM_REG(pThis, LPIB, pStream->u8SD));
390
391#ifdef LOG_ENABLED
392 hdaBDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
393#endif
394 }
395
396 if (RT_FAILURE(rc))
397 LogRel(("HDA: Initializing stream #%RU8 failed with %Rrc\n", pStream->u8SD, rc));
398
399 return rc;
400}
401
402/**
403 * Resets an HDA stream.
404 *
405 * @param pThis HDA state.
406 * @param pStream HDA stream to reset.
407 * @param uSD Stream descriptor (SD) number to use for this stream.
408 */
409void hdaStreamReset(PHDASTATE pThis, PHDASTREAM pStream, uint8_t uSD)
410{
411 AssertPtrReturnVoid(pThis);
412 AssertPtrReturnVoid(pStream);
413 AssertReturnVoid(uSD < HDA_MAX_STREAMS);
414
415# ifdef VBOX_STRICT
416 AssertReleaseMsg(!pStream->State.fRunning, ("[SD%RU8] Cannot reset stream while in running state\n", uSD));
417# endif
418
419 LogFunc(("[SD%RU8]: Reset\n", uSD));
420
421 /*
422 * Set reset state.
423 */
424 Assert(ASMAtomicReadBool(&pStream->State.fInReset) == false); /* No nested calls. */
425 ASMAtomicXchgBool(&pStream->State.fInReset, true);
426
427 /*
428 * Second, initialize the registers.
429 */
430 HDA_STREAM_REG(pThis, STS, uSD) = HDA_SDSTS_FIFORDY;
431 /* According to the ICH6 datasheet, 0x40000 is the default value for stream descriptor register 23:20
432 * bits are reserved for stream number 18.2.33, resets SDnCTL except SRST bit. */
433 HDA_STREAM_REG(pThis, CTL, uSD) = 0x40000 | (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_SRST);
434 /* ICH6 defines default values (120 bytes for input and 192 bytes for output descriptors) of FIFO size. 18.2.39. */
435 HDA_STREAM_REG(pThis, FIFOS, uSD) = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? HDA_SDIFIFO_120B : HDA_SDOFIFO_192B;
436 /* See 18.2.38: Always defaults to 0x4 (32 bytes). */
437 HDA_STREAM_REG(pThis, FIFOW, uSD) = HDA_SDFIFOW_32B;
438 HDA_STREAM_REG(pThis, LPIB, uSD) = 0;
439 HDA_STREAM_REG(pThis, CBL, uSD) = 0;
440 HDA_STREAM_REG(pThis, LVI, uSD) = 0;
441 HDA_STREAM_REG(pThis, FMT, uSD) = 0;
442 HDA_STREAM_REG(pThis, BDPU, uSD) = 0;
443 HDA_STREAM_REG(pThis, BDPL, uSD) = 0;
444
445#ifdef HDA_USE_DMA_ACCESS_HANDLER
446 hdaStreamUnregisterDMAHandlers(pThis, pStream);
447#endif
448
449 /* Assign the default mixer sink to the stream. */
450 pStream->pMixSink = hdaGetDefaultSink(pThis, uSD);
451
452 pStream->State.tsTransferLast = 0;
453 pStream->State.tsTransferNext = 0;
454
455 RT_ZERO(pStream->State.BDLE);
456 pStream->State.uCurBDLE = 0;
457
458 if (pStream->State.pCircBuf)
459 RTCircBufReset(pStream->State.pCircBuf);
460
461 /* Reset stream map. */
462 hdaStreamMapReset(&pStream->State.Mapping);
463
464 /* (Re-)initialize the stream with current values. */
465 int rc2 = hdaStreamInit(pStream, uSD);
466 AssertRC(rc2);
467
468 /* Reset the stream's period. */
469 hdaStreamPeriodReset(&pStream->State.Period);
470
471#ifdef DEBUG
472 pStream->Dbg.cReadsTotal = 0;
473 pStream->Dbg.cbReadTotal = 0;
474 pStream->Dbg.tsLastReadNs = 0;
475 pStream->Dbg.cWritesTotal = 0;
476 pStream->Dbg.cbWrittenTotal = 0;
477 pStream->Dbg.cWritesHz = 0;
478 pStream->Dbg.cbWrittenHz = 0;
479 pStream->Dbg.tsWriteSlotBegin = 0;
480#endif
481
482 /* Report that we're done resetting this stream. */
483 HDA_STREAM_REG(pThis, CTL, uSD) = 0;
484
485 LogFunc(("[SD%RU8] Reset\n", uSD));
486
487 /* Exit reset mode. */
488 ASMAtomicXchgBool(&pStream->State.fInReset, false);
489}
490
491/**
492 * Enables or disables an HDA audio stream.
493 *
494 * @returns IPRT status code.
495 * @param pStream HDA stream to enable or disable.
496 * @param fEnable Whether to enable or disble the stream.
497 */
498int hdaStreamEnable(PHDASTREAM pStream, bool fEnable)
499{
500 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
501
502 LogFunc(("[SD%RU8]: fEnable=%RTbool, pMixSink=%p\n", pStream->u8SD, fEnable, pStream->pMixSink));
503
504 int rc = VINF_SUCCESS;
505
506 if (!pStream->pMixSink) /* Stream attached to a sink? */
507 {
508 AssertMsgFailed(("Stream #%RU8 not has no mixer sink attached\n", pStream->u8SD));
509 return VERR_WRONG_ORDER;
510 }
511
512 AUDMIXSINKCMD enmCmd = fEnable
513 ? AUDMIXSINKCMD_ENABLE : AUDMIXSINKCMD_DISABLE;
514
515 /* First, enable or disable the stream and the stream's sink, if any. */
516 if (pStream->pMixSink->pMixSink)
517 rc = AudioMixerSinkCtl(pStream->pMixSink->pMixSink, enmCmd);
518
519 if ( RT_SUCCESS(rc)
520 && pStream->Dbg.Runtime.fEnabled)
521 {
522 Assert(DrvAudioHlpPCMPropsAreValid(&pStream->State.Cfg.Props));
523
524 if (fEnable)
525 {
526 if (!DrvAudioHlpFileIsOpen(pStream->Dbg.Runtime.pFileStream))
527 {
528 int rc2 = DrvAudioHlpFileOpen(pStream->Dbg.Runtime.pFileStream, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
529 &pStream->State.Cfg.Props);
530 AssertRC(rc2);
531 }
532
533 if (!DrvAudioHlpFileIsOpen(pStream->Dbg.Runtime.pFileDMA))
534 {
535 int rc2 = DrvAudioHlpFileOpen(pStream->Dbg.Runtime.pFileDMA, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
536 &pStream->State.Cfg.Props);
537 AssertRC(rc2);
538 }
539 }
540 }
541
542 if (RT_SUCCESS(rc))
543 {
544 pStream->State.fRunning = fEnable;
545 }
546
547 LogFunc(("[SD%RU8] rc=%Rrc\n", pStream->u8SD, rc));
548 return rc;
549}
550
551uint32_t hdaStreamGetPosition(PHDASTATE pThis, PHDASTREAM pStream)
552{
553 return HDA_STREAM_REG(pThis, LPIB, pStream->u8SD);
554}
555
556/**
557 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
558 * updating its associated LPIB register and DMA position buffer (if enabled).
559 *
560 * @param pStream HDA stream to update read / write position for.
561 * @param u32LPIB Absolute position (in bytes) to set current read / write position to.
562 */
563void hdaStreamSetPosition(PHDASTREAM pStream, uint32_t u32LPIB)
564{
565 AssertPtrReturnVoid(pStream);
566
567 Log3Func(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
568 pStream->u8SD, u32LPIB, pStream->pHDAState->fDMAPosition));
569
570 /* Update LPIB in any case. */
571 HDA_STREAM_REG(pStream->pHDAState, LPIB, pStream->u8SD) = u32LPIB;
572
573 /* Do we need to tell the current DMA position? */
574 if (pStream->pHDAState->fDMAPosition)
575 {
576 int rc2 = PDMDevHlpPCIPhysWrite(pStream->pHDAState->CTX_SUFF(pDevIns),
577 pStream->pHDAState->u64DPBase + (pStream->u8SD * 2 * sizeof(uint32_t)),
578 (void *)&u32LPIB, sizeof(uint32_t));
579 AssertRC(rc2);
580 }
581}
582
583/**
584 * Retrieves the available size of (buffered) audio data (in bytes) of a given HDA stream.
585 *
586 * @returns Available data (in bytes).
587 * @param pStream HDA stream to retrieve size for.
588 */
589uint32_t hdaStreamGetUsed(PHDASTREAM pStream)
590{
591 AssertPtrReturn(pStream, 0);
592
593 if (!pStream->State.pCircBuf)
594 return 0;
595
596 return (uint32_t)RTCircBufUsed(pStream->State.pCircBuf);
597}
598
599/**
600 * Retrieves the free size of audio data (in bytes) of a given HDA stream.
601 *
602 * @returns Free data (in bytes).
603 * @param pStream HDA stream to retrieve size for.
604 */
605uint32_t hdaStreamGetFree(PHDASTREAM pStream)
606{
607 AssertPtrReturn(pStream, 0);
608
609 if (!pStream->State.pCircBuf)
610 return 0;
611
612 return (uint32_t)RTCircBufFree(pStream->State.pCircBuf);
613}
614
615/**
616 * Returns whether a next transfer for a given stream is scheduled or not.
617 * This takes pending stream interrupts into account as well as the next scheduled
618 * transfer timestamp.
619 *
620 * @returns True if a next transfer is scheduled, false if not.
621 * @param pStream HDA stream to retrieve schedule status for.
622 */
623bool hdaStreamTransferIsScheduled(PHDASTREAM pStream)
624{
625 if (!pStream)
626 return false;
627
628 AssertPtrReturn(pStream->pHDAState, false);
629
630 const uint64_t tsNow = TMTimerGet(pStream->pTimer);
631
632 const bool fScheduled = pStream->State.fRunning
633 && ( pStream->State.cTransferPendingInterrupts
634 || pStream->State.tsTransferNext > tsNow);
635
636#ifdef LOG_ENABLED
637 if (fScheduled)
638 {
639 if (pStream->State.cTransferPendingInterrupts)
640 Log3Func(("[SD%RU8] Scheduled (%RU8 IRQs pending)\n",
641 pStream->u8SD, pStream->State.cTransferPendingInterrupts));
642 else
643 Log3Func(("[SD%RU8] Scheduled in %RU64\n",
644 pStream->u8SD, pStream->State.tsTransferNext - tsNow));
645 }
646#endif
647
648 return fScheduled;
649}
650
651/**
652 * Returns the (virtual) clock timestamp of the next transfer, if any.
653 * Will return 0 if no new transfer is scheduled.
654 *
655 * @returns The (virtual) clock timestamp of the next transfer.
656 * @param pStream HDA stream to retrieve timestamp for.
657 */
658uint64_t hdaStreamTransferGetNext(PHDASTREAM pStream)
659{
660 return pStream->State.tsTransferNext;
661}
662
663/**
664 * Writes audio data from a mixer sink into an HDA stream's DMA buffer.
665 *
666 * @returns IPRT status code.
667 * @param pStream HDA stream to write to.
668 * @param pvBuf Data buffer to write.
669 * If NULL, silence will be written.
670 * @param cbBuf Number of bytes of data buffer to write.
671 * @param pcbWritten Number of bytes written. Optional.
672 */
673int hdaStreamWrite(PHDASTREAM pStream, const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
674{
675 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
676 /* pvBuf is optional. */
677 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
678 /* pcbWritten is optional. */
679
680 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
681 AssertPtr(pCircBuf);
682
683 int rc = VINF_SUCCESS;
684
685 uint32_t cbWrittenTotal = 0;
686 uint32_t cbLeft = RT_MIN(cbBuf, (uint32_t)RTCircBufFree(pCircBuf));
687
688 while (cbLeft)
689 {
690 void *pvDst;
691 size_t cbDst;
692
693 RTCircBufAcquireWriteBlock(pCircBuf, cbLeft, &pvDst, &cbDst);
694
695 if (cbDst)
696 {
697 if (pvBuf)
698 {
699 memcpy(pvDst, (uint8_t *)pvBuf + cbWrittenTotal, cbDst);
700 }
701 else /* Send silence. */
702 {
703 /** @todo Use a sample spec for "silence" based on the PCM parameters.
704 * For now we ASSUME that silence equals NULLing the data. */
705 RT_BZERO(pvDst, cbDst);
706 }
707
708 if (pStream->Dbg.Runtime.fEnabled)
709 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileStream, pvDst, cbDst, 0 /* fFlags */);
710 }
711
712 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
713
714 if (RT_FAILURE(rc))
715 break;
716
717 Assert(cbLeft >= (uint32_t)cbDst);
718 cbLeft -= (uint32_t)cbDst;
719
720 cbWrittenTotal += (uint32_t)cbDst;
721 }
722
723 Log3Func(("cbWrittenTotal=%RU32\n", cbWrittenTotal));
724
725 if (pcbWritten)
726 *pcbWritten = cbWrittenTotal;
727
728 return rc;
729}
730
731
732/**
733 * Reads audio data from an HDA stream's DMA buffer and writes into a specified mixer sink.
734 *
735 * @returns IPRT status code.
736 * @param pStream HDA stream to read audio data from.
737 * @param cbToRead Number of bytes to read.
738 * @param pcbRead Number of bytes read. Optional.
739 */
740int hdaStreamRead(PHDASTREAM pStream, uint32_t cbToRead, uint32_t *pcbRead)
741{
742 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
743 AssertReturn(cbToRead, VERR_INVALID_PARAMETER);
744 /* pcbWritten is optional. */
745
746 PHDAMIXERSINK pSink = pStream->pMixSink;
747 if (!pSink)
748 {
749 AssertMsgFailed(("[SD%RU8]: Can't read from a stream with no sink attached\n", pStream->u8SD));
750
751 if (pcbRead)
752 *pcbRead = 0;
753 return VINF_SUCCESS;
754 }
755
756 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
757 AssertPtr(pCircBuf);
758
759 int rc = VINF_SUCCESS;
760
761 uint32_t cbReadTotal = 0;
762 uint32_t cbLeft = RT_MIN(cbToRead, (uint32_t)RTCircBufUsed(pCircBuf));
763
764 while (cbLeft)
765 {
766 void *pvSrc;
767 size_t cbSrc;
768
769 uint32_t cbWritten = 0;
770
771 RTCircBufAcquireReadBlock(pCircBuf, cbLeft, &pvSrc, &cbSrc);
772
773 if (cbSrc)
774 {
775 if (pStream->Dbg.Runtime.fEnabled)
776 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileStream, pvSrc, cbSrc, 0 /* fFlags */);
777
778 rc = AudioMixerSinkWrite(pSink->pMixSink, AUDMIXOP_COPY, pvSrc, (uint32_t)cbSrc, &cbWritten);
779 AssertRC(rc);
780
781 Assert(cbSrc >= cbWritten);
782 Log2Func(("[SD%RU8]: %zu/%zu bytes read\n", pStream->u8SD, cbWritten, cbSrc));
783 }
784
785 RTCircBufReleaseReadBlock(pCircBuf, cbWritten);
786
787 if (RT_FAILURE(rc))
788 break;
789
790 Assert(cbLeft >= cbWritten);
791 cbLeft -= cbWritten;
792
793 cbReadTotal += cbWritten;
794 }
795
796 if (pcbRead)
797 *pcbRead = cbReadTotal;
798
799 return rc;
800}
801
802/**
803 * Transfers data of an HDA stream according to its usage (input / output).
804 *
805 * For an SDO (output) stream this means reading DMA data from the device to
806 * the HDA stream's internal FIFO buffer.
807 *
808 * For an SDI (input) stream this is reading audio data from the HDA stream's
809 * internal FIFO buffer and writing it as DMA data to the device.
810 *
811 * @returns IPRT status code.
812 * @param pStream HDA stream to update.
813 * @param cbToProcessMax How much data (in bytes) to process as maximum.
814 */
815int hdaStreamTransfer(PHDASTREAM pStream, uint32_t cbToProcessMax)
816{
817 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
818
819 hdaStreamLock(pStream);
820
821 PHDASTATE pThis = pStream->pHDAState;
822 AssertPtr(pThis);
823
824 PHDASTREAMPERIOD pPeriod = &pStream->State.Period;
825 if (!hdaStreamPeriodLock(pPeriod))
826 return VERR_ACCESS_DENIED;
827
828 bool fProceed = true;
829
830 /* Stream not running? */
831 if (!pStream->State.fRunning)
832 {
833 Log3Func(("[SD%RU8] Not running\n", pStream->u8SD));
834 fProceed = false;
835 }
836 else if (HDA_STREAM_REG(pThis, STS, pStream->u8SD) & HDA_SDSTS_BCIS)
837 {
838 Log3Func(("[SD%RU8] BCIS bit set\n", pStream->u8SD));
839 fProceed = false;
840 }
841
842 if (!fProceed)
843 {
844 hdaStreamPeriodUnlock(pPeriod);
845 hdaStreamUnlock(pStream);
846 return VINF_SUCCESS;
847 }
848
849 const uint64_t tsNow = TMTimerGet(pStream->pTimer);
850
851 if (!pStream->State.tsTransferLast)
852 pStream->State.tsTransferLast = tsNow;
853
854#ifdef DEBUG
855 const int64_t iTimerDelta = tsNow - pStream->State.tsTransferLast;
856 Log3Func(("[SD%RU8] Time now=%RU64, last=%RU64 -> %RI64 ticks delta\n",
857 pStream->u8SD, tsNow, pStream->State.tsTransferLast, iTimerDelta));
858#endif
859
860 pStream->State.tsTransferLast = tsNow;
861
862 /* Sanity checks. */
863 Assert(pStream->u8SD < HDA_MAX_STREAMS);
864 Assert(pStream->u64BDLBase);
865 Assert(pStream->u32CBL);
866 Assert(pStream->u16FIFOS);
867
868 /* State sanity checks. */
869 Assert(ASMAtomicReadBool(&pStream->State.fInReset) == false);
870
871 int rc = VINF_SUCCESS;
872
873 /* Fetch first / next BDL entry. */
874 PHDABDLE pBDLE = &pStream->State.BDLE;
875 if (hdaBDLEIsComplete(pBDLE))
876 {
877 rc = hdaBDLEFetch(pThis, pBDLE, pStream->u64BDLBase, pStream->State.uCurBDLE);
878 AssertRC(rc);
879 }
880
881 uint32_t cbToProcess = RT_MIN(pStream->State.cbTransferSize - pStream->State.cbTransferProcessed,
882 pStream->State.cbTransferChunk);
883
884 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbToProcessMax=%RU32\n", pStream->u8SD, cbToProcess, cbToProcessMax));
885
886 if (cbToProcess > cbToProcessMax)
887 {
888 if (pStream->State.Cfg.enmDir == PDMAUDIODIR_IN)
889 LogRelMax2(64, ("HDA: Warning: FIFO underflow for stream #%RU8 (still %RU32 bytes needed)\n",
890 pStream->u8SD, cbToProcess - cbToProcessMax));
891 else
892 LogRelMax2(64, ("HDA: Warning: FIFO overflow for stream #%RU8 (%RU32 bytes outstanding)\n",
893 pStream->u8SD, cbToProcess - cbToProcessMax));
894
895 LogFunc(("[SD%RU8] Warning: Limiting transfer (cbToProcess=%RU32, cbToProcessMax=%RU32)\n",
896 pStream->u8SD, cbToProcess, cbToProcessMax));
897
898 /* Never process more than a stream currently can handle. */
899 cbToProcess = cbToProcessMax;
900 }
901
902 uint32_t cbProcessed = 0;
903 uint32_t cbLeft = cbToProcess;
904
905 uint8_t abChunk[HDA_FIFO_MAX + 1];
906 while (cbLeft)
907 {
908 /* Limit the chunk to the stream's FIFO size and what's left to process. */
909 uint32_t cbChunk = RT_MIN(cbLeft, pStream->u16FIFOS);
910
911 /* Limit the chunk to the remaining data of the current BDLE. */
912 cbChunk = RT_MIN(cbChunk, pBDLE->Desc.u32BufSize - pBDLE->State.u32BufOff);
913
914 /* If there are position adjustment frames left to be processed,
915 * make sure that we process them first as a whole. */
916 if (pStream->State.cPosAdjustFramesLeft)
917 cbChunk = RT_MIN(cbChunk, uint32_t(pStream->State.cPosAdjustFramesLeft * pStream->State.cbFrameSize));
918
919 Log3Func(("[SD%RU8] cbChunk=%RU32, cPosAdjustFramesLeft=%RU16\n",
920 pStream->u8SD, cbChunk, pStream->State.cPosAdjustFramesLeft));
921
922 if (!cbChunk)
923 break;
924
925 uint32_t cbDMA = 0;
926 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
927
928 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN) /* Input (SDI). */
929 {
930 STAM_PROFILE_START(&pThis->StatIn, a);
931
932 uint32_t cbDMAWritten = 0;
933 uint32_t cbDMAToWrite = cbChunk;
934
935 /** @todo Do we need interleaving streams support here as well?
936 * Never saw anything else besides mono/stereo mics (yet). */
937 while (cbDMAToWrite)
938 {
939 void *pvBuf; size_t cbBuf;
940 RTCircBufAcquireReadBlock(pCircBuf, cbDMAToWrite, &pvBuf, &cbBuf);
941
942 if ( !cbBuf
943 && !RTCircBufUsed(pCircBuf))
944 break;
945
946 memcpy(abChunk + cbDMAWritten, pvBuf, cbBuf);
947
948 RTCircBufReleaseReadBlock(pCircBuf, cbBuf);
949
950 Assert(cbDMAToWrite >= cbBuf);
951 cbDMAToWrite -= (uint32_t)cbBuf;
952 cbDMAWritten += (uint32_t)cbBuf;
953 Assert(cbDMAWritten <= cbChunk);
954 }
955
956 if (cbDMAToWrite)
957 {
958 LogRel2(("HDA: FIFO underflow for stream #%RU8 (%RU32 bytes outstanding)\n", pStream->u8SD, cbDMAToWrite));
959
960 Assert(cbChunk == cbDMAWritten + cbDMAToWrite);
961 memset((uint8_t *)abChunk + cbDMAWritten, 0, cbDMAToWrite);
962 cbDMAWritten = cbChunk;
963 }
964
965 rc = hdaDMAWrite(pThis, pStream, abChunk, cbDMAWritten, &cbDMA /* pcbWritten */);
966 if (RT_FAILURE(rc))
967 LogRel(("HDA: Writing to stream #%RU8 DMA failed with %Rrc\n", pStream->u8SD, rc));
968
969 STAM_PROFILE_STOP(&pThis->StatIn, a);
970 }
971 else if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
972 {
973 STAM_PROFILE_START(&pThis->StatOut, a);
974
975 rc = hdaDMARead(pThis, pStream, abChunk, cbChunk, &cbDMA /* pcbRead */);
976 if (RT_SUCCESS(rc))
977 {
978#ifndef VBOX_WITH_HDA_AUDIO_INTERLEAVING_STREAMS_SUPPORT
979 /*
980 * Most guests don't use different stream frame sizes than
981 * the default one, so save a bit of CPU time and don't go into
982 * the frame extraction code below.
983 *
984 * Only macOS guests need the frame extraction branch below at the moment AFAIK.
985 */
986 if (pStream->State.cbFrameSize == HDA_FRAME_SIZE)
987 {
988 uint32_t cbDMARead = 0;
989 uint32_t cbDMALeft = RT_MIN(cbDMA, (uint32_t)RTCircBufFree(pCircBuf));
990
991 while (cbDMALeft)
992 {
993 void *pvBuf; size_t cbBuf;
994 RTCircBufAcquireWriteBlock(pCircBuf, cbDMALeft, &pvBuf, &cbBuf);
995
996 if (cbBuf)
997 {
998 memcpy(pvBuf, abChunk + cbDMARead, cbBuf);
999 cbDMARead += (uint32_t)cbBuf;
1000 cbDMALeft -= (uint32_t)cbBuf;
1001 }
1002
1003 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1004 }
1005 }
1006 else
1007 {
1008 /**
1009 * The following code extracts the required audio stream (channel) data
1010 * of non-interleaved *and* interleaved audio streams.
1011 *
1012 * We by default only support 2 channels with 16-bit samples (HDA_FRAME_SIZE),
1013 * but an HDA audio stream can have interleaved audio data of multiple audio
1014 * channels in such a single stream ("AA,AA,AA vs. AA,BB,AA,BB").
1015 *
1016 * So take this into account by just handling the first channel in such a stream ("A")
1017 * and just discard the other channel's data.
1018 *
1019 * @todo Optimize this stuff -- copying only one frame a time is expensive.
1020 */
1021 uint32_t cbDMARead = pStream->State.cbDMALeft ? pStream->State.cbFrameSize - pStream->State.cbDMALeft : 0;
1022 uint32_t cbDMALeft = RT_MIN(cbDMA, (uint32_t)RTCircBufFree(pCircBuf));
1023
1024 while (cbDMALeft >= pStream->State.cbFrameSize)
1025 {
1026 void *pvBuf; size_t cbBuf;
1027 RTCircBufAcquireWriteBlock(pCircBuf, HDA_FRAME_SIZE, &pvBuf, &cbBuf);
1028
1029 AssertBreak(cbDMARead <= sizeof(abChunk));
1030
1031 if (cbBuf)
1032 memcpy(pvBuf, abChunk + cbDMARead, cbBuf);
1033
1034 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1035
1036 Assert(cbDMALeft >= pStream->State.cbFrameSize);
1037 cbDMALeft -= pStream->State.cbFrameSize;
1038 cbDMARead += pStream->State.cbFrameSize;
1039 }
1040
1041 pStream->State.cbDMALeft = cbDMALeft;
1042 Assert(pStream->State.cbDMALeft < pStream->State.cbFrameSize);
1043 }
1044
1045 const size_t cbFree = RTCircBufFree(pCircBuf);
1046 if (!cbFree)
1047 LogRel2(("HDA: FIFO of stream #%RU8 full, discarding audio data\n", pStream->u8SD));
1048#else
1049 /** @todo This needs making use of HDAStreamMap + HDAStreamChannel. */
1050# error "Implement reading interleaving streams support here."
1051#endif
1052 }
1053 else
1054 LogRel(("HDA: Reading from stream #%RU8 DMA failed with %Rrc\n", pStream->u8SD, rc));
1055
1056 STAM_PROFILE_STOP(&pThis->StatOut, a);
1057 }
1058
1059 else /** @todo Handle duplex streams? */
1060 AssertFailed();
1061
1062 if (cbDMA)
1063 {
1064 /* We always increment the position of DMA buffer counter because we're always reading
1065 * into an intermediate buffer. */
1066 pBDLE->State.u32BufOff += (uint32_t)cbDMA;
1067 Assert(pBDLE->State.u32BufOff <= pBDLE->Desc.u32BufSize);
1068
1069 /* Are we done doing the position adjustment?
1070 * Only then do the transfer accounting .*/
1071 if (pStream->State.cPosAdjustFramesLeft == 0)
1072 {
1073 Assert(cbLeft >= cbDMA);
1074 cbLeft -= cbDMA;
1075
1076 cbProcessed += cbDMA;
1077 }
1078
1079 /**
1080 * Update the stream's current position.
1081 * Do this as accurate and close to the actual data transfer as possible.
1082 * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
1083 */
1084 uint32_t cbStreamPos = hdaStreamGetPosition(pThis, pStream);
1085 if (cbStreamPos == pStream->u32CBL)
1086 cbStreamPos = 0;
1087
1088 hdaStreamSetPosition(pStream, cbStreamPos + cbDMA);
1089 }
1090
1091 if (hdaBDLEIsComplete(pBDLE))
1092 {
1093 Log3Func(("[SD%RU8] Complete: %R[bdle]\n", pStream->u8SD, pBDLE));
1094
1095 /* Does the current BDLE require an interrupt to be sent? */
1096 if ( hdaBDLENeedsInterrupt(pBDLE)
1097 /* Are we done doing the position adjustment?
1098 * It can happen that a BDLE which is handled while doing the
1099 * position adjustment requires an interrupt on completion (IOC) being set.
1100 *
1101 * In such a case we need to skip such an interrupt and just move on. */
1102 && pStream->State.cPosAdjustFramesLeft == 0)
1103 {
1104 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL register is set
1105 * we need to generate an interrupt.
1106 */
1107 if (HDA_STREAM_REG(pThis, CTL, pStream->u8SD) & HDA_SDCTL_IOCE)
1108 {
1109 pStream->State.cTransferPendingInterrupts++;
1110
1111 AssertMsg(pStream->State.cTransferPendingInterrupts <= 32,
1112 ("Too many pending interrupts (%RU8) for stream #%RU8\n",
1113 pStream->State.cTransferPendingInterrupts, pStream->u8SD));
1114 }
1115 }
1116
1117 if (pStream->State.uCurBDLE == pStream->u16LVI)
1118 {
1119 pStream->State.uCurBDLE = 0;
1120 }
1121 else
1122 pStream->State.uCurBDLE++;
1123
1124 /* Fetch the next BDLE entry. */
1125 hdaBDLEFetch(pThis, pBDLE, pStream->u64BDLBase, pStream->State.uCurBDLE);
1126 }
1127
1128 /* Do the position adjustment accounting. */
1129 pStream->State.cPosAdjustFramesLeft -= RT_MIN(pStream->State.cPosAdjustFramesLeft, cbDMA / pStream->State.cbFrameSize);
1130
1131 if (RT_FAILURE(rc))
1132 break;
1133 }
1134
1135 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbProcessed=%RU32, cbLeft=%RU32, %R[bdle], rc=%Rrc\n",
1136 pStream->u8SD, cbToProcess, cbProcessed, cbLeft, pBDLE, rc));
1137
1138 /* Sanity. */
1139 Assert(cbProcessed == cbToProcess);
1140 Assert(cbLeft == 0);
1141
1142 /* Only do the data accounting if we don't have to do any position
1143 * adjustment anymore. */
1144 if (pStream->State.cPosAdjustFramesLeft == 0)
1145 {
1146 hdaStreamPeriodInc(pPeriod, RT_MIN(cbProcessed / pStream->State.cbFrameSize, hdaStreamPeriodGetRemainingFrames(pPeriod)));
1147
1148 pStream->State.cbTransferProcessed += cbProcessed;
1149 }
1150
1151 /* Make sure that we never report more stuff processed than initially announced. */
1152 if (pStream->State.cbTransferProcessed > pStream->State.cbTransferSize)
1153 pStream->State.cbTransferProcessed = pStream->State.cbTransferSize;
1154
1155 uint32_t cbTransferLeft = pStream->State.cbTransferSize - pStream->State.cbTransferProcessed;
1156 bool fTransferComplete = !cbTransferLeft;
1157 uint64_t tsTransferNext = 0;
1158
1159 if (fTransferComplete)
1160 {
1161 /**
1162 * Try updating the wall clock.
1163 *
1164 * Note 1) Only certain guests (like Linux' snd_hda_intel) rely on the WALCLK register
1165 * in order to determine the correct timing of the sound device. Other guests
1166 * like Windows 7 + 10 (or even more exotic ones like Haiku) will completely
1167 * ignore this.
1168 *
1169 * Note 2) When updating the WALCLK register too often / early (or even in a non-monotonic
1170 * fashion) this *will* upset guest device drivers and will completely fuck up the
1171 * sound output. Running VLC on the guest will tell!
1172 */
1173 const bool fWalClkSet = hdaWalClkSet(pThis,
1174 hdaWalClkGetCurrent(pThis)
1175 + hdaStreamPeriodFramesToWalClk(pPeriod, pStream->State.cbTransferProcessed / pStream->State.cbFrameSize),
1176 false /* fForce */);
1177 RT_NOREF(fWalClkSet);
1178 }
1179
1180 /* Does the period have any interrupts outstanding? */
1181 if (pStream->State.cTransferPendingInterrupts)
1182 {
1183 Log3Func(("[SD%RU8] Scheduling interrupt\n", pStream->u8SD));
1184
1185 /**
1186 * Set the stream's BCIS bit.
1187 *
1188 * Note: This only must be done if the whole period is complete, and not if only
1189 * one specific BDL entry is complete (if it has the IOC bit set).
1190 *
1191 * This will otherwise confuses the guest when it 1) deasserts the interrupt,
1192 * 2) reads SDSTS (with BCIS set) and then 3) too early reads a (wrong) WALCLK value.
1193 *
1194 * snd_hda_intel on Linux will tell.
1195 */
1196 HDA_STREAM_REG(pThis, STS, pStream->u8SD) |= HDA_SDSTS_BCIS;
1197
1198 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1199 * ending / beginning a period. */
1200#ifndef DEBUG
1201 hdaProcessInterrupt(pThis);
1202#else
1203 hdaProcessInterrupt(pThis, __FUNCTION__);
1204#endif
1205 }
1206 else /* Transfer still in-flight -- schedule the next timing slot. */
1207 {
1208 uint32_t cbTransferNext = cbTransferLeft;
1209
1210 /* No data left to transfer anymore or do we have more data left
1211 * than we can transfer per timing slot? Clamp. */
1212 if ( !cbTransferNext
1213 || cbTransferNext > pStream->State.cbTransferChunk)
1214 {
1215 cbTransferNext = pStream->State.cbTransferChunk;
1216 }
1217
1218 tsTransferNext = tsNow + (cbTransferNext * pStream->State.cTicksPerByte);
1219
1220 /**
1221 * If the current transfer is complete, reset our counter.
1222 *
1223 * This can happen for examlpe if the guest OS (like macOS) sets up
1224 * big BDLEs without IOC bits set (but for the last one) and the
1225 * transfer is complete before we reach such a BDL entry.
1226 */
1227 if (fTransferComplete)
1228 pStream->State.cbTransferProcessed = 0;
1229 }
1230
1231 /* If we need to do another transfer, (re-)arm the device timer. */
1232 if (tsTransferNext) /* Can be 0 if no next transfer is needed. */
1233 {
1234 Log3Func(("[SD%RU8] Scheduling timer\n", pStream->u8SD));
1235
1236 TMTimerUnlock(pStream->pTimer);
1237
1238 LogFunc(("Timer set SD%RU8\n", pStream->u8SD));
1239 hdaTimerSet(pStream->pHDAState, pStream, tsTransferNext, false /* fForce */);
1240
1241 TMTimerLock(pStream->pTimer, VINF_SUCCESS);
1242
1243 pStream->State.tsTransferNext = tsTransferNext;
1244 }
1245
1246 pStream->State.tsTransferLast = tsNow;
1247
1248 Log3Func(("[SD%RU8] cbTransferLeft=%RU32 -- %RU32/%RU32\n",
1249 pStream->u8SD, cbTransferLeft, pStream->State.cbTransferProcessed, pStream->State.cbTransferSize));
1250 Log3Func(("[SD%RU8] fTransferComplete=%RTbool, cTransferPendingInterrupts=%RU8\n",
1251 pStream->u8SD, fTransferComplete, pStream->State.cTransferPendingInterrupts));
1252 Log3Func(("[SD%RU8] tsNow=%RU64, tsTransferNext=%RU64 (in %RU64 ticks)\n",
1253 pStream->u8SD, tsNow, tsTransferNext, tsTransferNext - tsNow));
1254
1255 hdaStreamPeriodUnlock(pPeriod);
1256 hdaStreamUnlock(pStream);
1257
1258 return VINF_SUCCESS;
1259}
1260
1261/**
1262 * Updates a HDA stream by doing its required data transfers.
1263 * The host sink(s) set the overall pace.
1264 *
1265 * This routine is called by both, the synchronous and the asynchronous, implementations.
1266 *
1267 * @param pStream HDA stream to update.
1268 * @param fInTimer Whether to this function was called from the timer
1269 * context or an asynchronous I/O stream thread (if supported).
1270 */
1271void hdaStreamUpdate(PHDASTREAM pStream, bool fInTimer)
1272{
1273 if (!pStream)
1274 return;
1275
1276 PAUDMIXSINK pSink = NULL;
1277 if ( pStream->pMixSink
1278 && pStream->pMixSink->pMixSink)
1279 {
1280 pSink = pStream->pMixSink->pMixSink;
1281 }
1282
1283 if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
1284 return;
1285
1286 int rc2;
1287
1288 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1289 {
1290 /* Is the HDA stream ready to be written (guest output data) to? If so, by how much? */
1291 const uint32_t cbFree = hdaStreamGetFree(pStream);
1292
1293 if ( fInTimer
1294 && cbFree)
1295 {
1296 Log3Func(("[SD%RU8] cbFree=%RU32\n", pStream->u8SD, cbFree));
1297
1298 /* Do the DMA transfer. */
1299 rc2 = hdaStreamTransfer(pStream, cbFree);
1300 AssertRC(rc2);
1301 }
1302
1303 /* How much (guest output) data is available at the moment for the HDA stream? */
1304 uint32_t cbUsed = hdaStreamGetUsed(pStream);
1305
1306#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1307 if ( fInTimer
1308 && cbUsed)
1309 {
1310 rc2 = hdaStreamAsyncIONotify(pStream);
1311 AssertRC(rc2);
1312 }
1313 else
1314 {
1315#endif
1316 const uint32_t cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1317
1318 /* Do not write more than the sink can hold at the moment.
1319 * The host sets the overall pace. */
1320 if (cbUsed > cbSinkWritable)
1321 cbUsed = cbSinkWritable;
1322
1323 if (cbUsed)
1324 {
1325 /* Read (guest output) data and write it to the stream's sink. */
1326 rc2 = hdaStreamRead(pStream, cbUsed, NULL /* pcbRead */);
1327 AssertRC(rc2);
1328 }
1329
1330 /* When running synchronously, update the associated sink here.
1331 * Otherwise this will be done in the stream's dedicated async I/O thread. */
1332 rc2 = AudioMixerSinkUpdate(pSink);
1333 AssertRC(rc2);
1334
1335#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1336 }
1337#endif
1338 }
1339 else /* Input (SDI). */
1340 {
1341#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1342 if (!fInTimer)
1343 {
1344#endif
1345 rc2 = AudioMixerSinkUpdate(pSink);
1346 AssertRC(rc2);
1347
1348 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1349 uint32_t cbReadable = AudioMixerSinkGetReadable(pSink);
1350
1351 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1352 const uint32_t cbFree = hdaStreamGetFree(pStream);
1353
1354 Log3Func(("[SD%RU8] cbReadable=%RU32, cbFree=%RU32\n", pStream->u8SD, cbReadable, cbFree));
1355
1356 /* Do not write more than the sink can hold at the moment.
1357 * The host sets the overall pace. */
1358 if (cbReadable > cbFree)
1359 cbReadable = cbFree;
1360
1361 if (cbReadable)
1362 {
1363 uint8_t abFIFO[HDA_FIFO_MAX + 1];
1364 while (cbReadable)
1365 {
1366 uint32_t cbRead;
1367 rc2 = AudioMixerSinkRead(pSink, AUDMIXOP_COPY,
1368 abFIFO, RT_MIN(cbReadable, (uint32_t)sizeof(abFIFO)), &cbRead);
1369 AssertRCBreak(rc2);
1370
1371 if (!cbRead)
1372 {
1373 AssertMsgFailed(("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbReadable));
1374 break;
1375 }
1376
1377 /* Write (guest input) data to the stream which was read from stream's sink before. */
1378 uint32_t cbWritten;
1379 rc2 = hdaStreamWrite(pStream, abFIFO, cbRead, &cbWritten);
1380 AssertRCBreak(rc2);
1381
1382 if (!cbWritten)
1383 {
1384 AssertFailed(); /* Should never happen, as we know how much we can write. */
1385 break;
1386 }
1387
1388 Assert(cbReadable >= cbRead);
1389 cbReadable -= cbRead;
1390 }
1391 }
1392 #if 0
1393 else /* Send silence as input. */
1394 {
1395 cbReadable = pStream->State.cbTransferSize - pStream->State.cbTransferProcessed;
1396
1397 Log3Func(("[SD%RU8] Sending silence (%RU32 bytes)\n", pStream->u8SD, cbReadable));
1398
1399 if (cbReadable)
1400 {
1401 rc2 = hdaStreamWrite(pStream, NULL /* Silence */, cbReadable, NULL /* pcbWritten */);
1402 AssertRC(rc2);
1403 }
1404 }
1405 #endif
1406#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1407 }
1408 else /* fInTimer */
1409 {
1410#endif
1411 const uint64_t tsNow = RTTimeMilliTS();
1412 static uint64_t s_lasti = 0;
1413 if (s_lasti == 0)
1414 s_lasti = tsNow;
1415
1416 if (tsNow - s_lasti >= 10) /** @todo Fix this properly. */
1417 {
1418 rc2 = hdaStreamAsyncIONotify(pStream);
1419 AssertRC(rc2);
1420
1421 s_lasti = tsNow;
1422 }
1423
1424 const uint32_t cbToTransfer = hdaStreamGetUsed(pStream);
1425 if (cbToTransfer)
1426 {
1427 rc2 = hdaStreamTransfer(pStream, cbToTransfer);
1428 AssertRC(rc2);
1429 }
1430#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1431 }
1432#endif
1433 }
1434}
1435
1436/**
1437 * Locks an HDA stream for serialized access.
1438 *
1439 * @returns IPRT status code.
1440 * @param pStream HDA stream to lock.
1441 */
1442void hdaStreamLock(PHDASTREAM pStream)
1443{
1444 AssertPtrReturnVoid(pStream);
1445 int rc2 = RTCritSectEnter(&pStream->CritSect);
1446 AssertRC(rc2);
1447}
1448
1449/**
1450 * Unlocks a formerly locked HDA stream.
1451 *
1452 * @returns IPRT status code.
1453 * @param pStream HDA stream to unlock.
1454 */
1455void hdaStreamUnlock(PHDASTREAM pStream)
1456{
1457 AssertPtrReturnVoid(pStream);
1458 int rc2 = RTCritSectLeave(&pStream->CritSect);
1459 AssertRC(rc2);
1460}
1461
1462/**
1463 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1464 * updating its associated LPIB register and DMA position buffer (if enabled).
1465 *
1466 * @returns Set LPIB value.
1467 * @param pStream HDA stream to update read / write position for.
1468 * @param u32LPIB New LPIB (position) value to set.
1469 */
1470uint32_t hdaStreamUpdateLPIB(PHDASTREAM pStream, uint32_t u32LPIB)
1471{
1472 AssertPtrReturn(pStream, 0);
1473
1474 AssertMsg(u32LPIB <= pStream->u32CBL,
1475 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStream->u8SD, u32LPIB, pStream->u32CBL));
1476
1477 const PHDASTATE pThis = pStream->pHDAState;
1478
1479 u32LPIB = RT_MIN(u32LPIB, pStream->u32CBL);
1480
1481 LogFlowFunc(("[SD%RU8]: LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
1482 pStream->u8SD, u32LPIB, pThis->fDMAPosition));
1483
1484 /* Update LPIB in any case. */
1485 HDA_STREAM_REG(pThis, LPIB, pStream->u8SD) = u32LPIB;
1486
1487 /* Do we need to tell the current DMA position? */
1488 if (pThis->fDMAPosition)
1489 {
1490 int rc2 = PDMDevHlpPCIPhysWrite(pThis->CTX_SUFF(pDevIns),
1491 pThis->u64DPBase + (pStream->u8SD * 2 * sizeof(uint32_t)),
1492 (void *)&u32LPIB, sizeof(uint32_t));
1493 AssertRC(rc2);
1494 }
1495
1496 return u32LPIB;
1497}
1498
1499# ifdef HDA_USE_DMA_ACCESS_HANDLER
1500/**
1501 * Registers access handlers for a stream's BDLE DMA accesses.
1502 *
1503 * @returns true if registration was successful, false if not.
1504 * @param pStream HDA stream to register BDLE access handlers for.
1505 */
1506bool hdaStreamRegisterDMAHandlers(PHDASTREAM pStream)
1507{
1508 /* At least LVI and the BDL base must be set. */
1509 if ( !pStream->u16LVI
1510 || !pStream->u64BDLBase)
1511 {
1512 return false;
1513 }
1514
1515 hdaStreamUnregisterDMAHandlers(pStream);
1516
1517 LogFunc(("Registering ...\n"));
1518
1519 int rc = VINF_SUCCESS;
1520
1521 /*
1522 * Create BDLE ranges.
1523 */
1524
1525 struct BDLERANGE
1526 {
1527 RTGCPHYS uAddr;
1528 uint32_t uSize;
1529 } arrRanges[16]; /** @todo Use a define. */
1530
1531 size_t cRanges = 0;
1532
1533 for (uint16_t i = 0; i < pStream->u16LVI + 1; i++)
1534 {
1535 HDABDLE BDLE;
1536 rc = hdaBDLEFetch(pThis, &BDLE, pStream->u64BDLBase, i /* Index */);
1537 if (RT_FAILURE(rc))
1538 break;
1539
1540 bool fAddRange = true;
1541 BDLERANGE *pRange;
1542
1543 if (cRanges)
1544 {
1545 pRange = &arrRanges[cRanges - 1];
1546
1547 /* Is the current range a direct neighbor of the current BLDE? */
1548 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAdr)
1549 {
1550 /* Expand the current range by the current BDLE's size. */
1551 pRange->uSize += BDLE.Desc.u32BufSize;
1552
1553 /* Adding a new range in this case is not needed anymore. */
1554 fAddRange = false;
1555
1556 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
1557 }
1558 }
1559
1560 /* Do we need to add a new range? */
1561 if ( fAddRange
1562 && cRanges < RT_ELEMENTS(arrRanges))
1563 {
1564 pRange = &arrRanges[cRanges];
1565
1566 pRange->uAddr = BDLE.Desc.u64BufAdr;
1567 pRange->uSize = BDLE.Desc.u32BufSize;
1568
1569 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
1570
1571 cRanges++;
1572 }
1573 }
1574
1575 LogFunc(("%zu ranges total\n", cRanges));
1576
1577 /*
1578 * Register all ranges as DMA access handlers.
1579 */
1580
1581 for (size_t i = 0; i < cRanges; i++)
1582 {
1583 BDLERANGE *pRange = &arrRanges[i];
1584
1585 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
1586 if (!pHandler)
1587 {
1588 rc = VERR_NO_MEMORY;
1589 break;
1590 }
1591
1592 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
1593
1594 pHandler->pStream = pStream; /* Save a back reference to the owner. */
1595
1596 char szDesc[32];
1597 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
1598
1599 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
1600 hdaDMAAccessHandler,
1601 NULL, NULL, NULL,
1602 NULL, NULL, NULL,
1603 szDesc, &pHandler->hAccessHandlerType);
1604 AssertRCBreak(rc2);
1605
1606 pHandler->BDLEAddr = pRange->uAddr;
1607 pHandler->BDLESize = pRange->uSize;
1608
1609 /* Get first and last pages of the BDLE range. */
1610 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
1611 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
1612
1613 /* Calculate the region size (in pages). */
1614 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
1615
1616 pHandler->GCPhysFirst = pgFirst;
1617 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
1618
1619 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
1620 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
1621 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
1622 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
1623
1624 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1625 pHandler->GCPhysFirst, pHandler->GCPhysLast,
1626 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
1627 szDesc);
1628 AssertRCBreak(rc2);
1629
1630 pHandler->fRegistered = true;
1631 }
1632
1633 LogFunc(("Registration ended with rc=%Rrc\n", rc));
1634
1635 return RT_SUCCESS(rc);
1636}
1637
1638/**
1639 * Unregisters access handlers of a stream's BDLEs.
1640 *
1641 * @param pStream HDA stream to unregister BDLE access handlers for.
1642 */
1643void hdaStreamUnregisterDMAHandlers(PHDASTREAM pStream)
1644{
1645 LogFunc(("\n"));
1646
1647 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
1648 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
1649 {
1650 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
1651 continue;
1652
1653 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
1654 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
1655
1656 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1657 pHandler->GCPhysFirst);
1658 AssertRC(rc2);
1659
1660 RTListNodeRemove(&pHandler->Node);
1661
1662 RTMemFree(pHandler);
1663 pHandler = NULL;
1664 }
1665
1666 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
1667}
1668# endif /* HDA_USE_DMA_ACCESS_HANDLER */
1669
1670# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1671/**
1672 * Asynchronous I/O thread for a HDA stream.
1673 * This will do the heavy lifting work for us as soon as it's getting notified by another thread.
1674 *
1675 * @returns IPRT status code.
1676 * @param hThreadSelf Thread handle.
1677 * @param pvUser User argument. Must be of type PHDASTREAMTHREADCTX.
1678 */
1679DECLCALLBACK(int) hdaStreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
1680{
1681 PHDASTREAMTHREADCTX pCtx = (PHDASTREAMTHREADCTX)pvUser;
1682 AssertPtr(pCtx);
1683
1684 PHDASTREAM pStream = pCtx->pStream;
1685 AssertPtr(pStream);
1686
1687 PHDASTREAMSTATEAIO pAIO = &pCtx->pStream->State.AIO;
1688
1689 ASMAtomicXchgBool(&pAIO->fStarted, true);
1690
1691 RTThreadUserSignal(hThreadSelf);
1692
1693 LogFunc(("[SD%RU8]: Started\n", pStream->u8SD));
1694
1695 for (;;)
1696 {
1697 int rc2 = RTSemEventWait(pAIO->Event, RT_INDEFINITE_WAIT);
1698 if (RT_FAILURE(rc2))
1699 break;
1700
1701 if (ASMAtomicReadBool(&pAIO->fShutdown))
1702 break;
1703
1704 rc2 = RTCritSectEnter(&pAIO->CritSect);
1705 if (RT_SUCCESS(rc2))
1706 {
1707 if (!pAIO->fEnabled)
1708 {
1709 RTCritSectLeave(&pAIO->CritSect);
1710 continue;
1711 }
1712
1713 hdaStreamUpdate(pStream, false /* fInTimer */);
1714
1715 int rc3 = RTCritSectLeave(&pAIO->CritSect);
1716 AssertRC(rc3);
1717 }
1718
1719 AssertRC(rc2);
1720 }
1721
1722 LogFunc(("[SD%RU8]: Ended\n", pStream->u8SD));
1723
1724 ASMAtomicXchgBool(&pAIO->fStarted, false);
1725
1726 return VINF_SUCCESS;
1727}
1728
1729/**
1730 * Creates the async I/O thread for a specific HDA audio stream.
1731 *
1732 * @returns IPRT status code.
1733 * @param pStream HDA audio stream to create the async I/O thread for.
1734 */
1735int hdaStreamAsyncIOCreate(PHDASTREAM pStream)
1736{
1737 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1738
1739 int rc;
1740
1741 if (!ASMAtomicReadBool(&pAIO->fStarted))
1742 {
1743 pAIO->fShutdown = false;
1744
1745 rc = RTSemEventCreate(&pAIO->Event);
1746 if (RT_SUCCESS(rc))
1747 {
1748 rc = RTCritSectInit(&pAIO->CritSect);
1749 if (RT_SUCCESS(rc))
1750 {
1751 HDASTREAMTHREADCTX Ctx = { pStream->pHDAState, pStream };
1752
1753 char szThreadName[64];
1754 RTStrPrintf2(szThreadName, sizeof(szThreadName), "hdaAIO%RU8", pStream->u8SD);
1755
1756 rc = RTThreadCreate(&pAIO->Thread, hdaStreamAsyncIOThread, &Ctx,
1757 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, szThreadName);
1758 if (RT_SUCCESS(rc))
1759 rc = RTThreadUserWait(pAIO->Thread, 10 * 1000 /* 10s timeout */);
1760 }
1761 }
1762 }
1763 else
1764 rc = VINF_SUCCESS;
1765
1766 LogFunc(("[SD%RU8]: Returning %Rrc\n", pStream->u8SD, rc));
1767 return rc;
1768}
1769
1770/**
1771 * Destroys the async I/O thread of a specific HDA audio stream.
1772 *
1773 * @returns IPRT status code.
1774 * @param pStream HDA audio stream to destroy the async I/O thread for.
1775 */
1776int hdaStreamAsyncIODestroy(PHDASTREAM pStream)
1777{
1778 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1779
1780 if (!ASMAtomicReadBool(&pAIO->fStarted))
1781 return VINF_SUCCESS;
1782
1783 ASMAtomicWriteBool(&pAIO->fShutdown, true);
1784
1785 int rc = hdaStreamAsyncIONotify(pStream);
1786 AssertRC(rc);
1787
1788 int rcThread;
1789 rc = RTThreadWait(pAIO->Thread, 30 * 1000 /* 30s timeout */, &rcThread);
1790 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
1791
1792 if (RT_SUCCESS(rc))
1793 {
1794 rc = RTCritSectDelete(&pAIO->CritSect);
1795 AssertRC(rc);
1796
1797 rc = RTSemEventDestroy(pAIO->Event);
1798 AssertRC(rc);
1799
1800 pAIO->fStarted = false;
1801 pAIO->fShutdown = false;
1802 pAIO->fEnabled = false;
1803 }
1804
1805 LogFunc(("[SD%RU8]: Returning %Rrc\n", pStream->u8SD, rc));
1806 return rc;
1807}
1808
1809/**
1810 * Lets the stream's async I/O thread know that there is some data to process.
1811 *
1812 * @returns IPRT status code.
1813 * @param pStream HDA stream to notify async I/O thread for.
1814 */
1815int hdaStreamAsyncIONotify(PHDASTREAM pStream)
1816{
1817 return RTSemEventSignal(pStream->State.AIO.Event);
1818}
1819
1820/**
1821 * Locks the async I/O thread of a specific HDA audio stream.
1822 *
1823 * @param pStream HDA stream to lock async I/O thread for.
1824 */
1825void hdaStreamAsyncIOLock(PHDASTREAM pStream)
1826{
1827 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1828
1829 if (!ASMAtomicReadBool(&pAIO->fStarted))
1830 return;
1831
1832 int rc2 = RTCritSectEnter(&pAIO->CritSect);
1833 AssertRC(rc2);
1834}
1835
1836/**
1837 * Unlocks the async I/O thread of a specific HDA audio stream.
1838 *
1839 * @param pStream HDA stream to unlock async I/O thread for.
1840 */
1841void hdaStreamAsyncIOUnlock(PHDASTREAM pStream)
1842{
1843 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1844
1845 if (!ASMAtomicReadBool(&pAIO->fStarted))
1846 return;
1847
1848 int rc2 = RTCritSectLeave(&pAIO->CritSect);
1849 AssertRC(rc2);
1850}
1851
1852/**
1853 * Enables (resumes) or disables (pauses) the async I/O thread.
1854 *
1855 * @param pStream HDA stream to enable/disable async I/O thread for.
1856 * @param fEnable Whether to enable or disable the I/O thread.
1857 *
1858 * @remarks Does not do locking.
1859 */
1860void hdaStreamAsyncIOEnable(PHDASTREAM pStream, bool fEnable)
1861{
1862 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1863 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
1864}
1865# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
1866
1867#endif /* IN_RING3 */
1868
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