summaryrefslogtreecommitdiff
path: root/src/VBox/Devices/Audio/filteraudio.c
blob: 9c3a2e3f302e4ab56b376a100a685f943faacc10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
/* $Id: filteraudio.c $ */
/** @file
 * VBox audio devices: filter driver, which sits between the host audio driver
 * and the virtual audio device and intercept all host driver operations.
 *
 * The filter is used mostly for remote audio input.
 */

/*
 * Copyright (C) 2010-2011 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#define LOG_GROUP LOG_GROUP_DEV_AUDIO
#include <VBox/log.h>
#include <iprt/asm.h>
#include <iprt/mem.h>
#include <iprt/cdefs.h>

#define AUDIO_CAP "filteraudio"
#include "vl_vbox.h"
#include "audio.h"
#include "audio_int.h"

#define FILTER_EXTENSIVE_LOGGING

/*******************************************************************************
 *
 * IO Ring Buffer section
 *
 ******************************************************************************/

/* Implementation of a lock free ring buffer which could be used in a multi
 * threaded environment. Note that only the acquire, release and getter
 * functions are threading aware. So don't use reset if the ring buffer is
 * still in use. */
typedef struct IORINGBUFFER
{
    /* The current read position in the buffer */
    uint32_t uReadPos;
    /* The current write position in the buffer */
    uint32_t uWritePos;
    /* How much space of the buffer is currently in use */
    volatile uint32_t cBufferUsed;
    /* How big is the buffer */
    uint32_t cBufSize;
    /* The buffer itself */
    char *pBuffer;
} IORINGBUFFER;
/* Pointer to an ring buffer structure */
typedef IORINGBUFFER* PIORINGBUFFER;


static void IORingBufferCreate(PIORINGBUFFER *ppBuffer, uint32_t cbSize)
{
    PIORINGBUFFER pTmpBuffer;

    AssertPtr(ppBuffer);

    *ppBuffer = NULL;
    pTmpBuffer = RTMemAllocZ(sizeof(IORINGBUFFER));
    if (pTmpBuffer)
    {
        pTmpBuffer->pBuffer = RTMemAlloc(cbSize);
        if(pTmpBuffer->pBuffer)
        {
            pTmpBuffer->cBufSize = cbSize;
            *ppBuffer = pTmpBuffer;
        }
        else
            RTMemFree(pTmpBuffer);
    }
}

static void IORingBufferDestroy(PIORINGBUFFER pBuffer)
{
    if (pBuffer)
    {
        if (pBuffer->pBuffer)
            RTMemFree(pBuffer->pBuffer);
        RTMemFree(pBuffer);
    }
}

DECL_FORCE_INLINE(void) IORingBufferReset(PIORINGBUFFER pBuffer)
{
    AssertPtr(pBuffer);

    pBuffer->uReadPos = 0;
    pBuffer->uWritePos = 0;
    pBuffer->cBufferUsed = 0;
}

DECL_FORCE_INLINE(uint32_t) IORingBufferFree(PIORINGBUFFER pBuffer)
{
    AssertPtr(pBuffer);
    return pBuffer->cBufSize - ASMAtomicReadU32(&pBuffer->cBufferUsed);
}

DECL_FORCE_INLINE(uint32_t) IORingBufferUsed(PIORINGBUFFER pBuffer)
{
    AssertPtr(pBuffer);
    return ASMAtomicReadU32(&pBuffer->cBufferUsed);
}

DECL_FORCE_INLINE(uint32_t) IORingBufferSize(PIORINGBUFFER pBuffer)
{
    AssertPtr(pBuffer);
    return pBuffer->cBufSize;
}

static void IORingBufferAquireReadBlock(PIORINGBUFFER pBuffer, uint32_t cReqSize, char **ppStart, uint32_t *pcSize)
{
    uint32_t uUsed = 0;
    uint32_t uSize = 0;

    AssertPtr(pBuffer);

    *ppStart = 0;
    *pcSize = 0;

    /* How much is in use? */
    uUsed = ASMAtomicReadU32(&pBuffer->cBufferUsed);
    if (uUsed > 0)
    {
        /* Get the size out of the requested size, the read block till the end
         * of the buffer & the currently used size. */
        uSize = RT_MIN(cReqSize, RT_MIN(pBuffer->cBufSize - pBuffer->uReadPos, uUsed));
        if (uSize > 0)
        {
            /* Return the pointer address which point to the current read
             * position. */
            *ppStart = pBuffer->pBuffer + pBuffer->uReadPos;
            *pcSize = uSize;
        }
    }
}

DECL_FORCE_INLINE(void) IORingBufferReleaseReadBlock(PIORINGBUFFER pBuffer, uint32_t cSize)
{
    AssertPtr(pBuffer);

    /* Split at the end of the buffer. */
    pBuffer->uReadPos = (pBuffer->uReadPos + cSize) % pBuffer->cBufSize;

    ASMAtomicSubU32(&pBuffer->cBufferUsed, cSize);
}

static void IORingBufferAquireWriteBlock(PIORINGBUFFER pBuffer, uint32_t cReqSize, char **ppStart, uint32_t *pcSize)
{
    uint32_t uFree;
    uint32_t uSize;

    AssertPtr(pBuffer);

    *ppStart = 0;
    *pcSize = 0;

    /* How much is free? */
    uFree = pBuffer->cBufSize - ASMAtomicReadU32(&pBuffer->cBufferUsed);
    if (uFree > 0)
    {
        /* Get the size out of the requested size, the write block till the end
         * of the buffer & the currently free size. */
        uSize = RT_MIN(cReqSize, RT_MIN(pBuffer->cBufSize - pBuffer->uWritePos, uFree));
        if (uSize > 0)
        {
            /* Return the pointer address which point to the current write
             * position. */
            *ppStart = pBuffer->pBuffer + pBuffer->uWritePos;
            *pcSize = uSize;
        }
    }
}

DECL_FORCE_INLINE(void) IORingBufferReleaseWriteBlock(PIORINGBUFFER pBuffer, uint32_t cSize)
{
    AssertPtr(pBuffer);

    /* Split at the end of the buffer. */
    pBuffer->uWritePos = (pBuffer->uWritePos + cSize) % pBuffer->cBufSize;

    ASMAtomicAddU32(&pBuffer->cBufferUsed, cSize);
}

/*******************************************************************************
 *
 * Global structures section
 *
 ******************************************************************************/

/* Initialization status indicator used for the recreation of the AudioUnits. */
#define CA_STATUS_UNINIT    UINT32_C(0) /* The device is uninitialized */
#define CA_STATUS_IN_INIT   UINT32_C(1) /* The device is currently initializing */
#define CA_STATUS_INIT      UINT32_C(2) /* The device is initialized */
#define CA_STATUS_IN_UNINIT UINT32_C(3) /* The device is currently uninitializing */

struct
{
    struct audio_driver *pDrv;
    void *pDrvOpaque;
} filter_conf =
{
    INIT_FIELD(.pDrv =) NULL,
    INIT_FIELD(.pDrvOpaque =) NULL
};

/*
 * filterVoiceOut and filterVoiceIn are allocated at the end of the original driver HWVoice structure:
 * {
 *    HWVoiceOut;
 *    OriginalDriverHWVoiceData;
 *    filterVoiceOut;
 * }
 */
typedef struct filterVoiceOut
{
    /* HW voice input structure, which prepends the filterVoiceOut. */
    HWVoiceOut *phw;

    /* A ring buffer for transferring data to the playback thread */
    PIORINGBUFFER pBuf;

    /* Initialization status tracker. Used when some of the device parameters
     * or the device itself is changed during the runtime. */
    volatile uint32_t status;

    /* Whether the output stream is used by the filter. */
    bool fIntercepted;

    /* Whether this stream is active. */
    bool fIsRunning;

    /* Sniffer level context for this audio output stream. */
    void *pvOutputCtx;
} filterVoiceOut;

typedef struct filterVoiceIn
{
    /* HW voice input structure, which prepends the filterVoiceIn. */
    HWVoiceIn *phw;

    /* A temporary position value. */
    uint32_t rpos;

    /* A ring buffer for transferring data from the recording thread */
    PIORINGBUFFER pBuf;

    /* Initialization status tracker. Used when some of the device parameters
     * or the device itself is changed during the runtime. */
    volatile uint32_t status;

    /* the stream has been successfully initialized by host. */
    bool fHostOK;

    /* Whether the input stream is used by the filter. */
    bool fIntercepted;

    /* Whether this stream is active. */
    bool fIsRunning;

    /* Sniffer level context for this audio input stream. */
    void *pvInputCtx;
} filterVoiceIn;

#ifdef FILTER_EXTENSIVE_LOGGING
# define CA_EXT_DEBUG_LOG(a) Log(a)
#else
# define CA_EXT_DEBUG_LOG(a) do {} while(0)
#endif

/*******************************************************************************
 *
 * CoreAudio output section
 *
 ******************************************************************************/

/* We need some forward declarations */
static int filteraudio_run_out(HWVoiceOut *hw);
static int filteraudio_write(SWVoiceOut *sw, void *buf, int len);
static int filteraudio_ctl_out(HWVoiceOut *hw, int cmd, ...);
static void filteraudio_fini_out(HWVoiceOut *hw);
static int filteraudio_init_out(HWVoiceOut *hw, audsettings_t *as);
static int caInitOutput(HWVoiceOut *hw);
static void caReinitOutput(HWVoiceOut *hw);

static int fltInitOutput(filterVoiceOut *pVoice)
{
    uint32_t cFrames; /* default frame count */
    uint32_t cSamples; /* samples count */

    ASMAtomicXchgU32(&pVoice->status, CA_STATUS_IN_INIT);

    cFrames = 2048;

    /* Create the internal ring buffer. */
    cSamples = cFrames * pVoice->phw->info.nchannels;
    IORingBufferCreate(&pVoice->pBuf, cSamples << pVoice->phw->info.shift);
    if (!RT_VALID_PTR(pVoice->pBuf))
    {
        LogRel(("FilterAudio: [Output] Failed to create internal ring buffer\n"));
        return -1;
    }

    if (   pVoice->phw->samples != 0
        && pVoice->phw->samples != (int32_t)cSamples)
        LogRel(("FilterAudio: [Output] Warning! After recreation, the CoreAudio ring buffer doesn't has the same size as the device buffer (%RU32 vs. %RU32).\n", cSamples, (uint32_t)pVoice->phw->samples));
    ASMAtomicXchgU32(&pVoice->status, CA_STATUS_INIT);

    Log(("FilterAudio: [Output] Frame count: %RU32\n", cFrames));

    return 0;
}

static int filteraudio_run_out(HWVoiceOut *phw)
{
    uint32_t csAvail = 0;
    uint32_t cbToWrite = 0;
    uint32_t csToWrite = 0;
    uint32_t csWritten = 0;
    char *pcDst = NULL;
    st_sample_t *psSrc = NULL;

    filterVoiceOut *pVoice = (filterVoiceOut *)((uint8_t *)phw + filter_conf.pDrv->voice_size_out);

    if (!pVoice->fIntercepted)
    {
        return filter_conf.pDrv->pcm_ops->run_out(phw);
    }

    /* We return the live count in the case we are not initialized. This should
     * prevent any under runs. */
    if (ASMAtomicReadU32(&pVoice->status) != CA_STATUS_INIT)
        return audio_pcm_hw_get_live_out(pVoice->phw);

    /* Make sure the device is running */
    filteraudio_ctl_out(pVoice->phw, VOICE_ENABLE);

    /* How much space is available in the ring buffer */
    csAvail = IORingBufferFree(pVoice->pBuf) >> pVoice->phw->info.shift; /* bytes -> samples */

    /* How much data is available. Use the smaller size of the too. */
    csAvail = RT_MIN(csAvail, (uint32_t)audio_pcm_hw_get_live_out(pVoice->phw));

    CA_EXT_DEBUG_LOG(("FilterAudio: [Output] Start writing buffer with %RU32 samples (%RU32 bytes)\n", csAvail, csAvail << pVoice->phw->info.shift));

    /* Iterate as long as data is available */
    while (csWritten < csAvail)
    {
        /* How much is left? Split request at the end of our samples buffer. */
        csToWrite = RT_MIN(csAvail - csWritten, (uint32_t)(pVoice->phw->samples - pVoice->phw->rpos));
        cbToWrite = csToWrite << pVoice->phw->info.shift; /* samples -> bytes */
        CA_EXT_DEBUG_LOG(("FilterAudio: [Output] Try writing %RU32 samples (%RU32 bytes)\n", csToWrite, cbToWrite));

        /* Try to acquire the necessary space from the ring buffer. */
        IORingBufferAquireWriteBlock(pVoice->pBuf, cbToWrite, &pcDst, &cbToWrite);

        /* How much to we get? */
        csToWrite = cbToWrite >> pVoice->phw->info.shift;
        CA_EXT_DEBUG_LOG(("FilterAudio: [Output] There is space for %RU32 samples (%RU32 bytes) available\n", csToWrite, cbToWrite));

        /* Break if nothing is free anymore. */
        if (RT_UNLIKELY(cbToWrite == 0))
            break;

        /* Copy the data from our mix buffer to the ring buffer. */
        psSrc = pVoice->phw->mix_buf + pVoice->phw->rpos;
        pVoice->phw->clip((uint8_t*)pcDst, psSrc, csToWrite);

        /* Release the ring buffer, so the read thread could start reading this data. */
        IORingBufferReleaseWriteBlock(pVoice->pBuf, cbToWrite);

        pVoice->phw->rpos = (pVoice->phw->rpos + csToWrite) % pVoice->phw->samples;

        /* How much have we written so far. */
        csWritten += csToWrite;
    }

    CA_EXT_DEBUG_LOG(("FilterAudio: [Output] Finished writing buffer with %RU32 samples (%RU32 bytes)\n", csWritten, csWritten << pVoice->phw->info.shift));

    /* Return the count of samples we have processed. */
    return csWritten;
}

static int filteraudio_write(SWVoiceOut *sw, void *buf, int len)
{
    /* Every host backend just calls the generic function, so no need to forward. */
    return audio_pcm_sw_write (sw, buf, len);
}

static int filteraudio_ctl_out(HWVoiceOut *phw, int cmd, ...)
{
    uint32_t status;

    filterVoiceOut *pVoice = (filterVoiceOut *)((uint8_t *)phw + filter_conf.pDrv->voice_size_out);

    if (!pVoice->fIntercepted)
    {
        /* Note: audio.c does not use variable parameters '...', so ok to forward only 'phw' and 'cmd'. */
        return filter_conf.pDrv->pcm_ops->ctl_out(phw, cmd);
    }

    status = ASMAtomicReadU32(&pVoice->status);
    if (!(status == CA_STATUS_INIT))
        return 0;

    switch (cmd)
    {
        case VOICE_ENABLE:
            {
                /* Only start the device if it is actually stopped */
                if (!pVoice->fIsRunning)
                {
                    IORingBufferReset(pVoice->pBuf);
                    filter_output_begin(&pVoice->pvOutputCtx, &pVoice->phw->info, pVoice->phw->samples);
                }
                break;
            }
        case VOICE_DISABLE:
            {
                /* Only stop the device if it is actually running */
                if (pVoice->fIsRunning)
                {
                    filter_output_end(pVoice->pvOutputCtx);
                }
                break;
            }
    }
    return 0;
}

static void filteraudio_fini_out(HWVoiceOut *phw)
{
    int rc = 0;
    uint32_t status;

    filterVoiceOut *pVoice = (filterVoiceOut *)((uint8_t *)phw + filter_conf.pDrv->voice_size_out);

    if (!pVoice->fIntercepted)
    {
        filter_conf.pDrv->pcm_ops->fini_out(phw);
        return;
    }

    status = ASMAtomicReadU32(&pVoice->status);
    if (!(status == CA_STATUS_INIT))
        return;

    rc = filteraudio_ctl_out(phw, VOICE_DISABLE);
    if (RT_LIKELY(rc == 0))
    {
        ASMAtomicXchgU32(&pVoice->status, CA_STATUS_IN_UNINIT);
        IORingBufferDestroy(pVoice->pBuf);
        pVoice->pBuf = NULL;
        ASMAtomicXchgU32(&pVoice->status, CA_STATUS_UNINIT);
    }
    else
        LogRel(("FilterAudio: [Output] Failed to stop playback (%RI32)\n", rc));
}

static int filteraudio_init_out(HWVoiceOut *phw, audsettings_t *as)
{
    int rc = 0;

    filterVoiceOut *pVoice = (filterVoiceOut *)((uint8_t *)phw + filter_conf.pDrv->voice_size_out);

    if (!filter_output_intercepted())
    {
        pVoice->fIntercepted = false;
        return filter_conf.pDrv->pcm_ops->init_out(phw, as);
    }

    /* Output is not tested and is not used currently */
    AssertFailed();
    return -1;

    ASMAtomicXchgU32(&pVoice->status, CA_STATUS_UNINIT);

    pVoice->fIntercepted = true;
    pVoice->phw = phw;
    pVoice->phw->samples = 0;

    /* Initialize the hardware info section with the audio settings */
    audio_pcm_init_info(&pVoice->phw->info, as);

    rc = fltInitOutput(pVoice);
    if (RT_UNLIKELY(rc != 0))
        return rc;

    /* The samples have to correspond to the internal ring buffer size. */
    pVoice->phw->samples = (IORingBufferSize(pVoice->pBuf) >> pVoice->phw->info.shift) / pVoice->phw->info.nchannels;

    Log(("FilterAudio: [Output] HW samples: %d\n", pVoice->phw->samples));

    return 0;
}

/*******************************************************************************
 *
 * FilterAudio input section
 *
 ******************************************************************************/

/*
 * Callback to feed audio input buffer. Samples format is be the same as
 * in the voice. The caller prepares st_sample_t.
 *
 * @param cbSamples Size of pvSamples array in bytes.
 * @param pvSamples Points to an array of samples.
 *
 * @return IPRT status code.
 */
static DECLCALLBACK(int) fltRecordingCallback(void* pvCallback,
                                              uint32_t cbSamples,
                                              const void *pvSamples)
{
    int rc = VINF_SUCCESS;
    uint32_t csAvail = 0;
    uint32_t csToWrite = 0;
    uint32_t cbToWrite = 0;
    uint32_t csWritten = 0;
    char *pcDst = NULL;

    filterVoiceIn *pVoice = (filterVoiceIn *)pvCallback;

    Assert((cbSamples % sizeof(st_sample_t)) == 0);

    if (!pVoice->fIsRunning)
        return VINF_SUCCESS;

    /* If nothing is pending return immediately. */
    if (cbSamples == 0)
        return VINF_SUCCESS;

    /* How much space is free in the ring buffer? */
    csAvail = IORingBufferFree(pVoice->pBuf) / sizeof(st_sample_t); /* bytes -> samples */

    /* How much space is used in the audio buffer. Use the smaller size of the too. */
    csAvail = RT_MIN(csAvail, cbSamples / sizeof(st_sample_t));

    CA_EXT_DEBUG_LOG(("FilterAudio: [Input] Start writing buffer with %RU32 samples (%RU32 bytes)\n", csAvail, csAvail * sizeof(st_sample_t)));

    /* Iterate as long as data is available */
    while(csWritten < csAvail)
    {
        /* How much is left? */
        csToWrite = csAvail - csWritten;
        cbToWrite = csToWrite * sizeof(st_sample_t);
        CA_EXT_DEBUG_LOG(("FilterAudio: [Input] Try writing %RU32 samples (%RU32 bytes)\n", csToWrite, cbToWrite));

        /* Try to acquire the necessary space from the ring buffer. */
        IORingBufferAquireWriteBlock(pVoice->pBuf, cbToWrite, &pcDst, &cbToWrite);

        /* How much do we get? */
        csToWrite = cbToWrite / sizeof(st_sample_t);
        CA_EXT_DEBUG_LOG(("FilterAudio: [Input] There is space for %RU32 samples (%RU32 bytes) available\n", csToWrite, cbToWrite));

        /* Break if nothing is free anymore. */
        if (RT_UNLIKELY(csToWrite == 0))
            break;

        /* Copy the data from the audio buffer to the ring buffer. */
        memcpy(pcDst, (uint8_t *)pvSamples + (csWritten * sizeof(st_sample_t)), cbToWrite);

        /* Release the ring buffer, so the main thread could start reading this data. */
        IORingBufferReleaseWriteBlock(pVoice->pBuf, cbToWrite);

        csWritten += csToWrite;
    }

    CA_EXT_DEBUG_LOG(("FilterAudio: [Input] Finished writing buffer with %RU32 samples (%RU32 bytes)\n", csWritten, csWritten * sizeof(st_sample_t)));

    return rc;
}

static int filteraudio_run_in(HWVoiceIn *phw)
{
    uint32_t csAvail = 0;
    uint32_t cbToRead = 0;
    uint32_t csToRead = 0;
    uint32_t csReads = 0;
    char *pcSrc;
    st_sample_t *psDst;
    filterVoiceIn *pVoice;

    if (!filter_conf.pDrv)
    {
        AssertFailed();
        return -1;
    }

    pVoice = (filterVoiceIn *)((uint8_t *)phw + filter_conf.pDrv->voice_size_in);

    if (!pVoice->fIntercepted)
    {
        if (!pVoice->fHostOK)
        {
            /* Host did not initialize the voice. */
            Log(("FilterAudio: [Input]: run_in voice %p (hw %p) not available on host\n", pVoice, pVoice->phw));
            return -1;
        }

        Log(("FilterAudio: [Input]: forwarding run_in for voice %p (hw %p)\n", pVoice, pVoice->phw));
        return filter_conf.pDrv->pcm_ops->run_in(phw);
    }

    Log(("FilterAudio: [Input]: run_in for voice %p (hw %p)\n", pVoice, pVoice->phw));

    if (!pVoice->fIsRunning)
        return 0;

    /* How much space is used in the ring buffer? */
    csAvail = IORingBufferUsed(pVoice->pBuf) / sizeof(st_sample_t); /* bytes -> samples */

    /* How much space is available in the mix buffer. Use the smaller size of the too. */
    csAvail = RT_MIN(csAvail, (uint32_t)(pVoice->phw->samples - audio_pcm_hw_get_live_in (pVoice->phw)));
    CA_EXT_DEBUG_LOG(("FilterAudio: [Input] Start reading buffer with %RU32 samples (%RU32 bytes)\n", csAvail, csAvail * sizeof(st_sample_t)));

    /* Iterate as long as data is available */
    while (csReads < csAvail)
    {
        /* How much is left? Split request at the end of our samples buffer. */
        csToRead = RT_MIN(csAvail - csReads, (uint32_t)(pVoice->phw->samples - pVoice->phw->wpos));
        cbToRead = csToRead * sizeof(st_sample_t);
        CA_EXT_DEBUG_LOG(("FilterAudio: [Input] Try reading %RU32 samples (%RU32 bytes)\n", csToRead, cbToRead));

        /* Try to acquire the necessary block from the ring buffer. */
        IORingBufferAquireReadBlock(pVoice->pBuf, cbToRead, &pcSrc, &cbToRead);

        /* How much to we get? */
        csToRead = cbToRead / sizeof(st_sample_t);
        CA_EXT_DEBUG_LOG(("FilterAudio: [Input] There are %RU32 samples (%RU32 bytes) available\n", csToRead, cbToRead));

        /* Break if nothing is used anymore. */
        if (csToRead == 0)
            break;

        /* Copy the data from our ring buffer to the mix buffer. */
        psDst = pVoice->phw->conv_buf + pVoice->phw->wpos;
        memcpy(psDst, pcSrc, cbToRead);

        /* Release the read buffer, so it could be used for new data. */
        IORingBufferReleaseReadBlock(pVoice->pBuf, cbToRead);

        pVoice->phw->wpos = (pVoice->phw->wpos + csToRead) % pVoice->phw->samples;

        /* How much have we reads so far. */
        csReads += csToRead;
    }

    CA_EXT_DEBUG_LOG(("FilterAudio: [Input] Finished reading buffer with %RU32 samples (%RU32 bytes)\n", csReads, csReads * sizeof(st_sample_t)));

    return csReads;
}

static int filteraudio_read(SWVoiceIn *sw, void *buf, int size)
{
    /* Every host backend just calls the generic function, so no need to forward. */
    return audio_pcm_sw_read (sw, buf, size);
}

static int filteraudio_ctl_in(HWVoiceIn *phw, int cmd, ...)
{
    int rc = VINF_SUCCESS;
    filterVoiceIn *pVoice;

    if (!filter_conf.pDrv)
    {
        AssertFailed();
        return -1;
    }

    pVoice = (filterVoiceIn *)((uint8_t *)phw + filter_conf.pDrv->voice_size_in);

    if (cmd == VOICE_ENABLE)
    {
        /* Decide who will provide input audio: filter or host driver. */
        if (!filter_input_intercepted())
        {
            if (!pVoice->fHostOK)
            {
                /* Host did not initialize the voice. */
                Log(("FilterAudio: [Input]: ctl_in ENABLE voice %p (hw %p) not available on host\n", pVoice, pVoice->phw));
                return -1;
            }

            /* Note: audio.c does not use variable parameters '...', so ok to forward only 'phw' and 'cmd'. */
            Log(("FilterAudio: [Input]: forwarding ctl_in ENABLE for voice %p (hw %p)\n", pVoice, pVoice->phw));
            return filter_conf.pDrv->pcm_ops->ctl_in(phw, cmd);
        }

        /* The filter will use this voice. */
        Log(("FilterAudio: [Input]: ctl_in ENABLE for voice %p (hw %p), cmd %d\n", pVoice, pVoice->phw, cmd));

        if (ASMAtomicReadU32(&pVoice->status) != CA_STATUS_INIT)
            return -1;

        /* Only start the device if it is actually stopped */
        if (!pVoice->fIsRunning)
        {
            IORingBufferReset(pVoice->pBuf);

            /* Sniffer will inform us on a second thread for new incoming audio data.
             * Therefore register an callback function, which will process the new data.
             * */
            rc = filter_input_begin(&pVoice->pvInputCtx, fltRecordingCallback, pVoice, pVoice->phw, pVoice->phw->samples);
            if (RT_SUCCESS(rc))
            {
                pVoice->fIsRunning = true;

                /* Remember that this voice is used by the filter. */
                pVoice->fIntercepted = true;
            }
        }
        if (RT_FAILURE(rc))
        {
            LogRel(("FilterAudio: [Input] Failed to start recording (%Rrc)\n", rc));
            return -1;
        }
    }
    else if (cmd == VOICE_DISABLE)
    {
        if (ASMAtomicReadU32(&pVoice->status) != CA_STATUS_INIT)
            return -1;

        /* Check if the voice has been intercepted. */
        if (!pVoice->fIntercepted)
        {
            if (!pVoice->fHostOK)
            {
                /* Host did not initialize the voice. Theoretically should not happen, because
                 * audio.c should not disable a voice which has not been enabled at all.
                 */
                Log(("FilterAudio: [Input]: ctl_in DISABLE voice %p (hw %p) not available on host\n", pVoice, pVoice->phw));
                return -1;
            }

            /* Note: audio.c does not use variable parameters '...', so ok to forward only 'phw' and 'cmd'. */
            Log(("FilterAudio: [Input]: forwarding ctl_in DISABLE for voice %p (hw %p)\n", pVoice, pVoice->phw));
            return filter_conf.pDrv->pcm_ops->ctl_in(phw, cmd);
        }

        /* The filter used this voice. */
        Log(("FilterAudio: [Input]: ctl_in DISABLE for voice %p (hw %p), cmd %d\n", pVoice, pVoice->phw, cmd));

        /* Only stop the device if it is actually running */
        if (pVoice->fIsRunning)
        {
            pVoice->fIsRunning = false;
            /* Tell the sniffer to not to use this context anymore. */
            filter_input_end(pVoice->pvInputCtx);
        }

        /* This voice is no longer used by the filter. */
        pVoice->fIntercepted = false;
    }
    else
    {
        return -1; /* Unknown command. */
    }

    return 0;
}

static void filteraudio_fini_in(HWVoiceIn *phw)
{
    int ret = -1;
    filterVoiceIn *pVoice;

    if (!filter_conf.pDrv)
    {
        AssertFailed();
        return;
    }

    pVoice = (filterVoiceIn *)((uint8_t *)phw + filter_conf.pDrv->voice_size_in);

    /* Uninitialize both host and filter parts of the voice. */
    if (pVoice->fHostOK)
    {
        /* Uninit host part only if it was initialized by host. */
        Log(("FilterAudio: [Input]: forwarding fini_in for voice %p (hw %p)\n", pVoice, pVoice->phw));
        filter_conf.pDrv->pcm_ops->fini_in(phw);
    }

    Log(("FilterAudio: [Input]: fini_in for voice %p (hw %p)\n", pVoice, pVoice->phw));

    if (ASMAtomicReadU32(&pVoice->status) != CA_STATUS_INIT)
        return;

    /* If this voice is intercepted by filter, try to stop it. */
    if (pVoice->fIntercepted)
    {
        ret = filteraudio_ctl_in(phw, VOICE_DISABLE);
    }
    else
    {
        ret = 0;
    }

    if (RT_LIKELY(ret == 0))
    {
        ASMAtomicWriteU32(&pVoice->status, CA_STATUS_IN_UNINIT);
        IORingBufferDestroy(pVoice->pBuf);
        pVoice->pBuf = NULL;
        pVoice->rpos = 0;
        ASMAtomicWriteU32(&pVoice->status, CA_STATUS_UNINIT);
    }
    else
        LogRel(("FilterAudio: [Input] Failed to stop recording (%RI32)\n", ret));
}

static int filteraudio_init_in(HWVoiceIn *phw, audsettings_t *as)
{
    int hostret = -1;
    filterVoiceIn *pVoice;

    if (!filter_conf.pDrv)
    {
        AssertFailed();
        return -1;
    }

    pVoice = (filterVoiceIn *)((uint8_t *)phw + filter_conf.pDrv->voice_size_in);

    /* Initialize both host and filter parts of the voice. */
    Log(("FilterAudio: [Input]: forwarding init_in for voice %p (hw %p)\n", pVoice, pVoice->phw));
    hostret = filter_conf.pDrv->pcm_ops->init_in(phw, as);

    Log(("FilterAudio: [Input]: init_in for voice %p (hw %p), hostret = %d\n", pVoice, pVoice->phw, hostret));

    ASMAtomicWriteU32(&pVoice->status, CA_STATUS_UNINIT);

    pVoice->phw = phw;
    pVoice->rpos = 0;
    pVoice->pBuf = NULL;
    pVoice->fHostOK = (hostret == 0);
    pVoice->fIntercepted = false;
    pVoice->fIsRunning = false;
    pVoice->pvInputCtx = NULL;

    if (!pVoice->fHostOK)
    {
        /* Initialize required fields of the common part of the voice. */
        pVoice->phw->samples = 2048;

        /* Initialize the hardware info section with the audio settings */
        audio_pcm_init_info(&pVoice->phw->info, as);
    }

    ASMAtomicWriteU32(&pVoice->status, CA_STATUS_IN_INIT);

    /* Create the internal ring buffer. */
    IORingBufferCreate(&pVoice->pBuf, pVoice->phw->samples * sizeof(st_sample_t));

    if (!RT_VALID_PTR(pVoice->pBuf))
    {
        LogRel(("FilterAudio: [Input] Failed to create internal ring buffer\n"));
        return -1;
    }

    ASMAtomicWriteU32(&pVoice->status, CA_STATUS_INIT);

    Log(("FilterAudio: [Input] HW samples: %d\n", pVoice->phw->samples));
    return 0;
}

/*******************************************************************************
 *
 * FilterAudio global section
 *
 ******************************************************************************/

static void *filteraudio_audio_init(void)
{
    /* This is not supposed to be called. */
    Log(("FilterAudio: Init\n"));
    AssertFailed();
    return NULL;
}

static void filteraudio_audio_fini(void *opaque)
{
    Log(("FilterAudio: Init fini %p\n", opaque));
    /* Forward to the host driver. */
    Assert(opaque == filter_conf.pDrvOpaque);
    if (filter_conf.pDrv)
    {
        filter_conf.pDrv->fini(opaque);
        filter_conf.pDrv = NULL;
        filter_conf.pDrvOpaque = NULL;
    }
}

static struct audio_pcm_ops filteraudio_pcm_ops =
{
    filteraudio_init_out,
    filteraudio_fini_out,
    filteraudio_run_out,
    filteraudio_write,
    filteraudio_ctl_out,

    filteraudio_init_in,
    filteraudio_fini_in,
    filteraudio_run_in,
    filteraudio_read,
    filteraudio_ctl_in
};

static struct audio_driver filteraudio_audio_driver =
{
    INIT_FIELD(name           =) "filteraudio",
    INIT_FIELD(descr          =)
    "FilterAudio: filter driver between host audio and virtual device",
    INIT_FIELD(options        =) NULL,
    INIT_FIELD(init           =) filteraudio_audio_init,
    INIT_FIELD(fini           =) filteraudio_audio_fini,
    INIT_FIELD(pcm_ops        =) &filteraudio_pcm_ops,
    INIT_FIELD(can_be_default =) 1,
    INIT_FIELD(max_voices_out =) 1,
    INIT_FIELD(max_voices_in  =) 1,
    INIT_FIELD(voice_size_out =) sizeof(filterVoiceOut),
    INIT_FIELD(voice_size_in  =) sizeof(filterVoiceIn)
};

struct audio_driver *filteraudio_install(struct audio_driver *pDrv, void *pDrvOpaque)
{
    Log(("FilterAudio: [Install]: intercepting driver [%s]\n", pDrv->name));

    /* Modify the audio driver structure to be like the original driver. */
    filteraudio_audio_driver.name           = pDrv->name;
    filteraudio_audio_driver.descr          = pDrv->descr;
    filteraudio_audio_driver.options        = pDrv->options;
    filteraudio_audio_driver.can_be_default = pDrv->can_be_default;
    filteraudio_audio_driver.max_voices_out = pDrv->max_voices_out;
    filteraudio_audio_driver.max_voices_in  = pDrv->max_voices_in;
    filteraudio_audio_driver.voice_size_out = pDrv->voice_size_out + sizeof(filterVoiceOut);
    filteraudio_audio_driver.voice_size_in  = pDrv->voice_size_in + sizeof(filterVoiceIn);

    filter_conf.pDrv = pDrv;
    filter_conf.pDrvOpaque = pDrvOpaque;

    return &filteraudio_audio_driver;
}

int filteraudio_is_host_voice_in_ok(struct audio_driver *pDrv, HWVoiceIn *phw)
{
    filterVoiceIn *pVoice;

    if (pDrv != &filteraudio_audio_driver)
    {
        /* This is not the driver for which the filter was installed.
         * The filter has no idea and assumes that if the voice
         * is not NULL then it is a valid host voice.
         */
        return (phw != NULL);
    }

    if (!filter_conf.pDrv)
    {
        AssertFailed();
        return (phw != NULL);
    }

    pVoice = (filterVoiceIn *)((uint8_t *)phw + filter_conf.pDrv->voice_size_in);

    return pVoice->fHostOK;
}

int filteraudio_is_host_voice_out_ok(struct audio_driver *pDrv, HWVoiceOut *phw)
{
    /* Output is not yet implemented and there are no filter voices.
     * The filter has no idea and assumes that if the voice
     * is not NULL then it is a valid host voice.
     *
     * @todo: similar to filteraudio_is_host_voice_in_ok
     */
    NOREF(pDrv);
    return (phw != NULL);
}