aboutsummaryrefslogtreecommitdiffstats
path: root/Alc/backends/qsa.cpp
blob: b40b5b6be26f50ed5496de3478b965ba4acb1029 (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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
/**
 * OpenAL cross platform audio library
 * Copyright (C) 2011-2013 by authors.
 * This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the
 *  Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * Or go to http://www.gnu.org/copyleft/lgpl.html
 */

#include "config.h"

#include "backends/qsa.h"

#include <stdlib.h>
#include <stdio.h>
#include <sched.h>
#include <errno.h>
#include <memory.h>

#include <memory>
#include <algorithm>

#include "alMain.h"
#include "alu.h"
#include "threads.h"

#include <sys/select.h>
#include <sys/asoundlib.h>
#include <sys/neutrino.h>


namespace {

struct qsa_data {
    snd_pcm_t* pcmHandle{nullptr};
    int audio_fd{-1};

    snd_pcm_channel_setup_t  csetup{};
    snd_pcm_channel_params_t cparams{};

    ALvoid* buffer{nullptr};
    ALsizei size{0};

    std::atomic<ALenum> mKillNow{AL_TRUE};
    althrd_t thread;
};

struct DevMap {
    ALCchar* name;
    int card;
    int dev;
};

al::vector<DevMap> DeviceNameMap;
al::vector<DevMap> CaptureNameMap;

constexpr ALCchar qsaDevice[] = "QSA Default";

constexpr struct {
    int32_t format;
} formatlist[] = {
    {SND_PCM_SFMT_FLOAT_LE},
    {SND_PCM_SFMT_S32_LE},
    {SND_PCM_SFMT_U32_LE},
    {SND_PCM_SFMT_S16_LE},
    {SND_PCM_SFMT_U16_LE},
    {SND_PCM_SFMT_S8},
    {SND_PCM_SFMT_U8},
    {0},
};

constexpr struct {
    int32_t rate;
} ratelist[] = {
    {192000},
    {176400},
    {96000},
    {88200},
    {48000},
    {44100},
    {32000},
    {24000},
    {22050},
    {16000},
    {12000},
    {11025},
    {8000},
    {0},
};

constexpr struct {
    int32_t channels;
} channellist[] = {
    {8},
    {7},
    {6},
    {4},
    {2},
    {1},
    {0},
};

void deviceList(int type, al::vector<DevMap> *devmap)
{
    snd_ctl_t* handle;
    snd_pcm_info_t pcminfo;
    int max_cards, card, err, dev;
    DevMap entry;
    char name[1024];
    struct snd_ctl_hw_info info;

    max_cards = snd_cards();
    if(max_cards < 0)
        return;

    std::for_each(devmap->begin(), devmap->end(),
        [](const DevMap &entry) -> void
        { free(entry.name); }
    );
    devmap->clear();

    entry.name = strdup(qsaDevice);
    entry.card = 0;
    entry.dev = 0;
    devmap->push_back(entry);

    for(card = 0;card < max_cards;card++)
    {
        if((err=snd_ctl_open(&handle, card)) < 0)
            continue;

        if((err=snd_ctl_hw_info(handle, &info)) < 0)
        {
            snd_ctl_close(handle);
            continue;
        }

        for(dev = 0;dev < (int)info.pcmdevs;dev++)
        {
            if((err=snd_ctl_pcm_info(handle, dev, &pcminfo)) < 0)
                continue;

            if((type==SND_PCM_CHANNEL_PLAYBACK && (pcminfo.flags&SND_PCM_INFO_PLAYBACK)) ||
               (type==SND_PCM_CHANNEL_CAPTURE && (pcminfo.flags&SND_PCM_INFO_CAPTURE)))
            {
                snprintf(name, sizeof(name), "%s [%s] (hw:%d,%d)", info.name, pcminfo.name, card, dev);
                entry.name = strdup(name);
                entry.card = card;
                entry.dev = dev;

                devmap->push_back(entry);
                TRACE("Got device \"%s\", card %d, dev %d\n", name, card, dev);
            }
        }
        snd_ctl_close(handle);
    }
}


/* Wrappers to use an old-style backend with the new interface. */
struct PlaybackWrapper final : public ALCbackend {
    std::unique_ptr<qsa_data> ExtraData;
};

static void PlaybackWrapper_Construct(PlaybackWrapper *self, ALCdevice *device);
static void PlaybackWrapper_Destruct(PlaybackWrapper *self);
static ALCenum PlaybackWrapper_open(PlaybackWrapper *self, const ALCchar *name);
static ALCboolean PlaybackWrapper_reset(PlaybackWrapper *self);
static ALCboolean PlaybackWrapper_start(PlaybackWrapper *self);
static void PlaybackWrapper_stop(PlaybackWrapper *self);
static DECLARE_FORWARD2(PlaybackWrapper, ALCbackend, ALCenum, captureSamples, void*, ALCuint)
static DECLARE_FORWARD(PlaybackWrapper, ALCbackend, ALCuint, availableSamples)
static DECLARE_FORWARD(PlaybackWrapper, ALCbackend, ClockLatency, getClockLatency)
static DECLARE_FORWARD(PlaybackWrapper, ALCbackend, void, lock)
static DECLARE_FORWARD(PlaybackWrapper, ALCbackend, void, unlock)
DECLARE_DEFAULT_ALLOCATORS(PlaybackWrapper)
DEFINE_ALCBACKEND_VTABLE(PlaybackWrapper);


FORCE_ALIGN static int qsa_proc_playback(void *ptr)
{
    PlaybackWrapper *self = static_cast<PlaybackWrapper*>(ptr);
    ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
    qsa_data *data = self->ExtraData;
    snd_pcm_channel_status_t status;
    struct sched_param param;
    struct timeval timeout;
    char* write_ptr;
    fd_set wfds;
    ALint len;
    int sret;

    SetRTPriority();
    althrd_setname(MIXER_THREAD_NAME);

    /* Increase default 10 priority to 11 to avoid jerky sound */
    SchedGet(0, 0, &param);
    param.sched_priority=param.sched_curpriority+1;
    SchedSet(0, 0, SCHED_NOCHANGE, &param);

    const ALint frame_size = FrameSizeFromDevFmt(
        device->FmtChans, device->FmtType, device->mAmbiOrder
    );

    PlaybackWrapper_lock(self);
    while(!data->mKillNow.load(std::memory_order_acquire))
    {
        FD_ZERO(&wfds);
        FD_SET(data->audio_fd, &wfds);
        timeout.tv_sec=2;
        timeout.tv_usec=0;

        /* Select also works like time slice to OS */
        PlaybackWrapper_unlock(self);
        sret = select(data->audio_fd+1, NULL, &wfds, NULL, &timeout);
        PlaybackWrapper_lock(self);
        if(sret == -1)
        {
            ERR("select error: %s\n", strerror(errno));
            aluHandleDisconnect(device, "Failed waiting for playback buffer: %s", strerror(errno));
            break;
        }
        if(sret == 0)
        {
            ERR("select timeout\n");
            continue;
        }

        len = data->size;
        write_ptr = static_cast<char*>(data->buffer);
        aluMixData(device, write_ptr, len/frame_size);
        while(len>0 && !data->mKillNow.load(std::memory_order_acquire))
        {
            int wrote = snd_pcm_plugin_write(data->pcmHandle, write_ptr, len);
            if(wrote <= 0)
            {
                if(errno==EAGAIN || errno==EWOULDBLOCK)
                    continue;

                memset(&status, 0, sizeof(status));
                status.channel = SND_PCM_CHANNEL_PLAYBACK;

                snd_pcm_plugin_status(data->pcmHandle, &status);

                /* we need to reinitialize the sound channel if we've underrun the buffer */
                if(status.status == SND_PCM_STATUS_UNDERRUN ||
                   status.status == SND_PCM_STATUS_READY)
                {
                    if(snd_pcm_plugin_prepare(data->pcmHandle, SND_PCM_CHANNEL_PLAYBACK) < 0)
                    {
                        aluHandleDisconnect(device, "Playback recovery failed");
                        break;
                    }
                }
            }
            else
            {
                write_ptr += wrote;
                len -= wrote;
            }
        }
    }
    PlaybackWrapper_unlock(self);

    return 0;
}

/************/
/* Playback */
/************/

static ALCenum qsa_open_playback(PlaybackWrapper *self, const ALCchar* deviceName)
{
    ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
    int card, dev;
    int status;

    std::unique_ptr<qsa_data> data{new qsa_data{}};
    data->mKillNow.store(AL_TRUE, std::memory_order_relaxed);

    if(!deviceName)
        deviceName = qsaDevice;

    if(strcmp(deviceName, qsaDevice) == 0)
        status = snd_pcm_open_preferred(&data->pcmHandle, &card, &dev, SND_PCM_OPEN_PLAYBACK);
    else
    {
        if(DeviceNameMap.empty())
            deviceList(SND_PCM_CHANNEL_PLAYBACK, &DeviceNameMap);

        auto iter = std::find_if(DeviceNameMap.begin(), DeviceNameMap.end(),
            [deviceName](const DevMap &entry) -> bool
            { return entry.name && strcmp(deviceName, entry.name) == 0; }
        );
        if(iter == DeviceNameMap.cend())
            return ALC_INVALID_DEVICE;

        status = snd_pcm_open(&data->pcmHandle, iter->card, iter->dev, SND_PCM_OPEN_PLAYBACK);
    }

    if(status < 0)
        return ALC_INVALID_DEVICE;

    data->audio_fd = snd_pcm_file_descriptor(data->pcmHandle, SND_PCM_CHANNEL_PLAYBACK);
    if(data->audio_fd < 0)
    {
        snd_pcm_close(data->pcmHandle);
        return ALC_INVALID_DEVICE;
    }

    device->DeviceName = deviceName;
    self->ExtraData = std::move(data);

    return ALC_NO_ERROR;
}

static void qsa_close_playback(PlaybackWrapper *self)
{
    qsa_data *data = self->ExtraData.get();

    if (data->buffer!=NULL)
    {
        free(data->buffer);
        data->buffer=NULL;
    }

    snd_pcm_close(data->pcmHandle);

    self->ExtraData = nullptr;
}

static ALCboolean qsa_reset_playback(PlaybackWrapper *self)
{
    ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
    qsa_data *data = self->ExtraData.get();
    int32_t format=-1;

    switch(device->FmtType)
    {
        case DevFmtByte:
             format=SND_PCM_SFMT_S8;
             break;
        case DevFmtUByte:
             format=SND_PCM_SFMT_U8;
             break;
        case DevFmtShort:
             format=SND_PCM_SFMT_S16_LE;
             break;
        case DevFmtUShort:
             format=SND_PCM_SFMT_U16_LE;
             break;
        case DevFmtInt:
             format=SND_PCM_SFMT_S32_LE;
             break;
        case DevFmtUInt:
             format=SND_PCM_SFMT_U32_LE;
             break;
        case DevFmtFloat:
             format=SND_PCM_SFMT_FLOAT_LE;
             break;
    }

    /* we actually don't want to block on writes */
    snd_pcm_nonblock_mode(data->pcmHandle, 1);
    /* Disable mmap to control data transfer to the audio device */
    snd_pcm_plugin_set_disable(data->pcmHandle, PLUGIN_DISABLE_MMAP);
    snd_pcm_plugin_set_disable(data->pcmHandle, PLUGIN_DISABLE_BUFFER_PARTIAL_BLOCKS);

    // configure a sound channel
    memset(&data->cparams, 0, sizeof(data->cparams));
    data->cparams.channel=SND_PCM_CHANNEL_PLAYBACK;
    data->cparams.mode=SND_PCM_MODE_BLOCK;
    data->cparams.start_mode=SND_PCM_START_FULL;
    data->cparams.stop_mode=SND_PCM_STOP_STOP;

    data->cparams.buf.block.frag_size=device->UpdateSize *
        FrameSizeFromDevFmt(device->FmtChans, device->FmtType, device->mAmbiOrder);
    data->cparams.buf.block.frags_max=device->NumUpdates;
    data->cparams.buf.block.frags_min=device->NumUpdates;

    data->cparams.format.interleave=1;
    data->cparams.format.rate=device->Frequency;
    data->cparams.format.voices=ChannelsFromDevFmt(device->FmtChans, device->mAmbiOrder);
    data->cparams.format.format=format;

    if ((snd_pcm_plugin_params(data->pcmHandle, &data->cparams))<0)
    {
        int original_rate=data->cparams.format.rate;
        int original_voices=data->cparams.format.voices;
        int original_format=data->cparams.format.format;
        int it;
        int jt;

        for (it=0; it<1; it++)
        {
            /* Check for second pass */
            if (it==1)
            {
                original_rate=ratelist[0].rate;
                original_voices=channellist[0].channels;
                original_format=formatlist[0].format;
            }

            do {
                /* At first downgrade sample format */
                jt=0;
                do {
                    if (formatlist[jt].format==data->cparams.format.format)
                    {
                        data->cparams.format.format=formatlist[jt+1].format;
                        break;
                    }
                    if (formatlist[jt].format==0)
                    {
                        data->cparams.format.format=0;
                        break;
                    }
                    jt++;
                } while(1);

                if (data->cparams.format.format==0)
                {
                    data->cparams.format.format=original_format;

                    /* At secod downgrade sample rate */
                    jt=0;
                    do {
                        if (ratelist[jt].rate==data->cparams.format.rate)
                        {
                            data->cparams.format.rate=ratelist[jt+1].rate;
                            break;
                        }
                        if (ratelist[jt].rate==0)
                        {
                            data->cparams.format.rate=0;
                            break;
                        }
                        jt++;
                    } while(1);

                    if (data->cparams.format.rate==0)
                    {
                        data->cparams.format.rate=original_rate;
                        data->cparams.format.format=original_format;

                        /* At third downgrade channels number */
                        jt=0;
                        do {
                            if(channellist[jt].channels==data->cparams.format.voices)
                            {
                                data->cparams.format.voices=channellist[jt+1].channels;
                                break;
                            }
                            if (channellist[jt].channels==0)
                            {
                                data->cparams.format.voices=0;
                                break;
                            }
                           jt++;
                        } while(1);
                    }

                    if (data->cparams.format.voices==0)
                    {
                        break;
                    }
                }

                data->cparams.buf.block.frag_size=device->UpdateSize*
                    data->cparams.format.voices*
                    snd_pcm_format_width(data->cparams.format.format)/8;
                data->cparams.buf.block.frags_max=device->NumUpdates;
                data->cparams.buf.block.frags_min=device->NumUpdates;
                if ((snd_pcm_plugin_params(data->pcmHandle, &data->cparams))<0)
                {
                    continue;
                }
                else
                {
                    break;
                }
            } while(1);

            if (data->cparams.format.voices!=0)
            {
                break;
            }
        }

        if (data->cparams.format.voices==0)
        {
            return ALC_FALSE;
        }
    }

    if ((snd_pcm_plugin_prepare(data->pcmHandle, SND_PCM_CHANNEL_PLAYBACK))<0)
    {
        return ALC_FALSE;
    }

    memset(&data->csetup, 0, sizeof(data->csetup));
    data->csetup.channel=SND_PCM_CHANNEL_PLAYBACK;
    if (snd_pcm_plugin_setup(data->pcmHandle, &data->csetup)<0)
    {
        return ALC_FALSE;
    }

    /* now fill back to the our AL device */
    device->Frequency=data->cparams.format.rate;

    switch (data->cparams.format.voices)
    {
        case 1:
             device->FmtChans=DevFmtMono;
             break;
        case 2:
             device->FmtChans=DevFmtStereo;
             break;
        case 4:
             device->FmtChans=DevFmtQuad;
             break;
        case 6:
             device->FmtChans=DevFmtX51;
             break;
        case 7:
             device->FmtChans=DevFmtX61;
             break;
        case 8:
             device->FmtChans=DevFmtX71;
             break;
        default:
             device->FmtChans=DevFmtMono;
             break;
    }

    switch (data->cparams.format.format)
    {
        case SND_PCM_SFMT_S8:
             device->FmtType=DevFmtByte;
             break;
        case SND_PCM_SFMT_U8:
             device->FmtType=DevFmtUByte;
             break;
        case SND_PCM_SFMT_S16_LE:
             device->FmtType=DevFmtShort;
             break;
        case SND_PCM_SFMT_U16_LE:
             device->FmtType=DevFmtUShort;
             break;
        case SND_PCM_SFMT_S32_LE:
             device->FmtType=DevFmtInt;
             break;
        case SND_PCM_SFMT_U32_LE:
             device->FmtType=DevFmtUInt;
             break;
        case SND_PCM_SFMT_FLOAT_LE:
             device->FmtType=DevFmtFloat;
             break;
        default:
             device->FmtType=DevFmtShort;
             break;
    }

    SetDefaultChannelOrder(device);

    device->UpdateSize=data->csetup.buf.block.frag_size/
        FrameSizeFromDevFmt(device->FmtChans, device->FmtType, device->mAmbiOrder);
    device->NumUpdates=data->csetup.buf.block.frags;

    data->size=data->csetup.buf.block.frag_size;
    data->buffer=malloc(data->size);
    if (!data->buffer)
    {
        return ALC_FALSE;
    }

    return ALC_TRUE;
}

static ALCboolean qsa_start_playback(PlaybackWrapper *self)
{
    qsa_data *data = self->ExtraData.get();

    data->mKillNow.store(AL_FALSE, std::memory_order_release);
    if(althrd_create(&data->thread, qsa_proc_playback, self) != althrd_success)
        return ALC_FALSE;

    return ALC_TRUE;
}

static void qsa_stop_playback(PlaybackWrapper *self)
{
    qsa_data *data = self->ExtraData.get();
    int res;

    if(data->mKillNow.exchange(AL_TRUE, std::memory_order_acq_rel))
        return;
    althrd_join(data->thread, &res);
}


static void PlaybackWrapper_Construct(PlaybackWrapper *self, ALCdevice *device)
{
    new (self) PlaybackWrapper{};
    ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
    SET_VTABLE2(PlaybackWrapper, ALCbackend, self);

    self->ExtraData = NULL;
}

static void PlaybackWrapper_Destruct(PlaybackWrapper *self)
{
    if(self->ExtraData)
        qsa_close_playback(self);

    ALCbackend_Destruct(STATIC_CAST(ALCbackend, self));
    self->~PlaybackWrapper();
}

static ALCenum PlaybackWrapper_open(PlaybackWrapper *self, const ALCchar *name)
{
    return qsa_open_playback(self, name);
}

static ALCboolean PlaybackWrapper_reset(PlaybackWrapper *self)
{
    return qsa_reset_playback(self);
}

static ALCboolean PlaybackWrapper_start(PlaybackWrapper *self)
{
    return qsa_start_playback(self);
}

static void PlaybackWrapper_stop(PlaybackWrapper *self)
{
    qsa_stop_playback(self);
}



/***********/
/* Capture */
/***********/

struct CaptureWrapper final : public ALCbackend {
    std::unique_ptr<qsa_data> ExtraData;
};

static void CaptureWrapper_Construct(CaptureWrapper *self, ALCdevice *device);
static void CaptureWrapper_Destruct(CaptureWrapper *self);
static ALCenum CaptureWrapper_open(CaptureWrapper *self, const ALCchar *name);
static DECLARE_FORWARD(CaptureWrapper, ALCbackend, ALCboolean, reset)
static ALCboolean CaptureWrapper_start(CaptureWrapper *self);
static void CaptureWrapper_stop(CaptureWrapper *self);
static ALCenum CaptureWrapper_captureSamples(CaptureWrapper *self, void *buffer, ALCuint samples);
static ALCuint CaptureWrapper_availableSamples(CaptureWrapper *self);
static DECLARE_FORWARD(CaptureWrapper, ALCbackend, ClockLatency, getClockLatency)
static DECLARE_FORWARD(CaptureWrapper, ALCbackend, void, lock)
static DECLARE_FORWARD(CaptureWrapper, ALCbackend, void, unlock)
DECLARE_DEFAULT_ALLOCATORS(CaptureWrapper)
DEFINE_ALCBACKEND_VTABLE(CaptureWrapper);


static ALCenum qsa_open_capture(CaptureWrapper *self, const ALCchar *deviceName)
{
    ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
    int card, dev;
    int format=-1;
    int status;

    std::unique_ptr<qsa_data> data{new qsa_data{}};

    if(!deviceName)
        deviceName = qsaDevice;

    if(strcmp(deviceName, qsaDevice) == 0)
        status = snd_pcm_open_preferred(&data->pcmHandle, &card, &dev, SND_PCM_OPEN_CAPTURE);
    else
    {
        if(CaptureNameMap.empty())
            deviceList(SND_PCM_CHANNEL_CAPTURE, &CaptureNameMap);

        auto iter = std::find_if(CaptureNameMap.cbegin(), CaptureNameMap.cend(),
            [deviceName](const DevMap &entry) -> bool
            { return entry.name && strcmp(deviceName, entry.name) == 0; }
        );
        if(iter == CaptureNameMap.cend())
            return ALC_INVALID_DEVICE;

        status = snd_pcm_open(&data->pcmHandle, iter->card, iter->dev, SND_PCM_OPEN_CAPTURE);
    }

    if(status < 0)
        return ALC_INVALID_DEVICE;

    data->audio_fd = snd_pcm_file_descriptor(data->pcmHandle, SND_PCM_CHANNEL_CAPTURE);
    if(data->audio_fd < 0)
    {
        snd_pcm_close(data->pcmHandle);
        return ALC_INVALID_DEVICE;
    }

    device->DeviceName = deviceName;

    switch (device->FmtType)
    {
        case DevFmtByte:
             format=SND_PCM_SFMT_S8;
             break;
        case DevFmtUByte:
             format=SND_PCM_SFMT_U8;
             break;
        case DevFmtShort:
             format=SND_PCM_SFMT_S16_LE;
             break;
        case DevFmtUShort:
             format=SND_PCM_SFMT_U16_LE;
             break;
        case DevFmtInt:
             format=SND_PCM_SFMT_S32_LE;
             break;
        case DevFmtUInt:
             format=SND_PCM_SFMT_U32_LE;
             break;
        case DevFmtFloat:
             format=SND_PCM_SFMT_FLOAT_LE;
             break;
    }

    /* we actually don't want to block on reads */
    snd_pcm_nonblock_mode(data->pcmHandle, 1);
    /* Disable mmap to control data transfer to the audio device */
    snd_pcm_plugin_set_disable(data->pcmHandle, PLUGIN_DISABLE_MMAP);

    /* configure a sound channel */
    memset(&data->cparams, 0, sizeof(data->cparams));
    data->cparams.mode=SND_PCM_MODE_BLOCK;
    data->cparams.channel=SND_PCM_CHANNEL_CAPTURE;
    data->cparams.start_mode=SND_PCM_START_GO;
    data->cparams.stop_mode=SND_PCM_STOP_STOP;

    data->cparams.buf.block.frag_size=device->UpdateSize*
        FrameSizeFromDevFmt(device->FmtChans, device->FmtType, device->mAmbiOrder);
    data->cparams.buf.block.frags_max=device->NumUpdates;
    data->cparams.buf.block.frags_min=device->NumUpdates;

    data->cparams.format.interleave=1;
    data->cparams.format.rate=device->Frequency;
    data->cparams.format.voices=ChannelsFromDevFmt(device->FmtChans, device->mAmbiOrder);
    data->cparams.format.format=format;

    if(snd_pcm_plugin_params(data->pcmHandle, &data->cparams) < 0)
    {
        snd_pcm_close(data->pcmHandle);
        return ALC_INVALID_VALUE;
    }

    self->ExtraData = std::move(data);

    return ALC_NO_ERROR;
}

static void qsa_close_capture(CaptureWrapper *self)
{
    qsa_data *data = self->ExtraData.get();

    if (data->pcmHandle!=nullptr)
        snd_pcm_close(data->pcmHandle);
    data->pcmHandle = nullptr

    self->ExtraData = nullptr;
}

static void qsa_start_capture(CaptureWrapper *self)
{
    qsa_data *data = self->ExtraData.get();
    int rstatus;

    if ((rstatus=snd_pcm_plugin_prepare(data->pcmHandle, SND_PCM_CHANNEL_CAPTURE))<0)
    {
        ERR("capture prepare failed: %s\n", snd_strerror(rstatus));
        return;
    }

    memset(&data->csetup, 0, sizeof(data->csetup));
    data->csetup.channel=SND_PCM_CHANNEL_CAPTURE;
    if ((rstatus=snd_pcm_plugin_setup(data->pcmHandle, &data->csetup))<0)
    {
        ERR("capture setup failed: %s\n", snd_strerror(rstatus));
        return;
    }

    snd_pcm_capture_go(data->pcmHandle);
}

static void qsa_stop_capture(CaptureWrapper *self)
{
    qsa_data *data = self->ExtraData.get();
    snd_pcm_capture_flush(data->pcmHandle);
}

static ALCuint qsa_available_samples(CaptureWrapper *self)
{
    ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
    qsa_data *data = self->ExtraData.get();
    snd_pcm_channel_status_t status;
    ALint frame_size = FrameSizeFromDevFmt(device->FmtChans, device->FmtType, device->mAmbiOrder);
    ALint free_size;
    int rstatus;

    memset(&status, 0, sizeof (status));
    status.channel=SND_PCM_CHANNEL_CAPTURE;
    snd_pcm_plugin_status(data->pcmHandle, &status);
    if ((status.status==SND_PCM_STATUS_OVERRUN) ||
        (status.status==SND_PCM_STATUS_READY))
    {
        if ((rstatus=snd_pcm_plugin_prepare(data->pcmHandle, SND_PCM_CHANNEL_CAPTURE))<0)
        {
            ERR("capture prepare failed: %s\n", snd_strerror(rstatus));
            aluHandleDisconnect(device, "Failed capture recovery: %s", snd_strerror(rstatus));
            return 0;
        }

        snd_pcm_capture_go(data->pcmHandle);
        return 0;
    }

    free_size=data->csetup.buf.block.frag_size*data->csetup.buf.block.frags;
    free_size-=status.free;

    return free_size/frame_size;
}

static ALCenum qsa_capture_samples(CaptureWrapper *self, ALCvoid *buffer, ALCuint samples)
{
    ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
    qsa_data *data = self->ExtraData.get();
    char* read_ptr;
    snd_pcm_channel_status_t status;
    fd_set rfds;
    int selectret;
    struct timeval timeout;
    int bytes_read;
    ALint frame_size=FrameSizeFromDevFmt(device->FmtChans, device->FmtType, device->mAmbiOrder);
    ALint len=samples*frame_size;
    int rstatus;

    read_ptr = static_cast<char*>(buffer);

    while (len>0)
    {
        FD_ZERO(&rfds);
        FD_SET(data->audio_fd, &rfds);
        timeout.tv_sec=2;
        timeout.tv_usec=0;

        /* Select also works like time slice to OS */
        bytes_read=0;
        selectret=select(data->audio_fd+1, &rfds, NULL, NULL, &timeout);
        switch (selectret)
        {
            case -1:
                 aluHandleDisconnect(device, "Failed to check capture samples");
                 return ALC_INVALID_DEVICE;
            case 0:
                 break;
            default:
                 if (FD_ISSET(data->audio_fd, &rfds))
                 {
                     bytes_read=snd_pcm_plugin_read(data->pcmHandle, read_ptr, len);
                     break;
                 }
                 break;
        }

        if (bytes_read<=0)
        {
            if ((errno==EAGAIN) || (errno==EWOULDBLOCK))
            {
                continue;
            }

            memset(&status, 0, sizeof (status));
            status.channel=SND_PCM_CHANNEL_CAPTURE;
            snd_pcm_plugin_status(data->pcmHandle, &status);

            /* we need to reinitialize the sound channel if we've overrun the buffer */
            if ((status.status==SND_PCM_STATUS_OVERRUN) ||
                (status.status==SND_PCM_STATUS_READY))
            {
                if ((rstatus=snd_pcm_plugin_prepare(data->pcmHandle, SND_PCM_CHANNEL_CAPTURE))<0)
                {
                    ERR("capture prepare failed: %s\n", snd_strerror(rstatus));
                    aluHandleDisconnect(device, "Failed capture recovery: %s",
                                        snd_strerror(rstatus));
                    return ALC_INVALID_DEVICE;
                }
                snd_pcm_capture_go(data->pcmHandle);
            }
        }
        else
        {
            read_ptr+=bytes_read;
            len-=bytes_read;
        }
    }

    return ALC_NO_ERROR;
}


static void CaptureWrapper_Construct(CaptureWrapper *self, ALCdevice *device)
{
    new (self) CaptureWrapper{};
    ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
    SET_VTABLE2(CaptureWrapper, ALCbackend, self);
}

static void CaptureWrapper_Destruct(CaptureWrapper *self)
{
    if(self->ExtraData)
        qsa_close_capture(self);

    ALCbackend_Destruct(STATIC_CAST(ALCbackend, self));
    self->~CaptureWrapper();
}

static ALCenum CaptureWrapper_open(CaptureWrapper *self, const ALCchar *name)
{
    return qsa_open_capture(self, name);
}

static ALCboolean CaptureWrapper_start(CaptureWrapper *self)
{
    qsa_start_capture(self);
    return ALC_TRUE;
}

static void CaptureWrapper_stop(CaptureWrapper *self)
{
    qsa_stop_capture(self);
}

static ALCenum CaptureWrapper_captureSamples(CaptureWrapper *self, void *buffer, ALCuint samples)
{
    return qsa_capture_samples(self, buffer, samples);
}

static ALCuint CaptureWrapper_availableSamples(CaptureWrapper *self)
{
    return qsa_available_samples(self);
}

} // namespace


bool QSABackendFactory::init()
{ return true; }

void QSABackendFactory::deinit()
{
    std::for_each(DeviceNameMap.begin(), DeviceNameMap.end(),
        [](DevMap &entry) -> void { free(entry.name); }
    );
    DeviceNameMap.clear();

    std::for_each(CaptureNameMap.begin(), CaptureNameMap.end(),
        [](DevMap &entry) -> void { free(entry.name); }
    );
    CaptureNameMap.clear();
}

bool QSABackendFactory::querySupport(ALCbackend_Type type)
{ return (type == ALCbackend_Playback || type == ALCbackend_Capture); }

void QSABackendFactory::probe(enum DevProbe type, std::string *outnames)
{
    auto add_device = [outnames](const DevMap &entry) -> void
    {
        const char *n = entry.name;
        if(n && n[0])
            outnames->append(n, strlen(n)+1);
    };

    switch (type)
    {
        case ALL_DEVICE_PROBE:
            deviceList(SND_PCM_CHANNEL_PLAYBACK, &DeviceNameMap);
            std::for_each(DeviceNameMap.cbegin(), DeviceNameMap.cend(), add_device);
            break;
        case CAPTURE_DEVICE_PROBE:
            deviceList(SND_PCM_CHANNEL_CAPTURE, &CaptureNameMap);
            std::for_each(CaptureNameMap.cbegin(), CaptureNameMap.cend(), add_device);
            break;
    }
}

ALCbackend *QSABackendFactory::createBackend(ALCdevice *device, ALCbackend_Type type)
{
    if(type == ALCbackend_Playback)
    {
        PlaybackWrapper *backend;
        NEW_OBJ(backend, PlaybackWrapper)(device);
        if(!backend) return NULL;
        return STATIC_CAST(ALCbackend, backend);
    }
    if(type == ALCbackend_Capture)
    {
        CaptureWrapper *backend;
        NEW_OBJ(backend, CaptureWrapper)(device);
        if(!backend) return NULL;
        return STATIC_CAST(ALCbackend, backend);
    }

    return NULL;
}

BackendFactory &QSABackendFactory::getFactory()
{
    static QSABackendFactory factory{};
    return factory;
}