File: auddev_win32.c

package info (click to toggle)
rat 4.2.20-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 2,888 kB
  • ctags: 3,655
  • sloc: ansic: 36,042; sh: 3,481; tcl: 2,740; makefile: 293
file content (1640 lines) | stat: -rw-r--r-- 54,309 bytes parent folder | download
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
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
/*
 * FILE:	auddev_win32.c
 *
 * Reworked by Orion Hodson from RAT 3.0 code.
 *
 * Assorted fixes and multilingual comments from Michael Wallbaum 
 * <wallbaum@informatik.rwth-aachen.de>
 *
 * Copyright (c) 1995-2001 University College London
 * All rights reserved.
 */
 
#ifndef HIDE_SOURCE_STRINGS
static const char cvsid[] = 
	"$Id: auddev_win32.c,v 1.79 2001/01/08 20:29:50 ucaccsp Exp $";
#endif /* HIDE_SOURCE_STRINGS */

#ifdef WIN32

#include "config_win32.h"
#include "audio.h"
#include "debug.h"
#include "memory.h"
#include "auddev_win32.h"
#include "audio_types.h"
#include "audio_fmt.h"
#include "util.h"
#include "mmsystem.h"

#define MAX_DEVICE_GAIN 0xffff
#define rat_to_device(x)	(((x) * MAX_DEVICE_GAIN / MAX_AMP) << 16 | ((x) * MAX_DEVICE_GAIN / MAX_AMP))
#define device_to_rat(x)	((x & 0xffff) * MAX_AMP / MAX_DEVICE_GAIN)

#define W32SDK_MAX_DEVICES 5
static  int have_probed[W32SDK_MAX_DEVICES];
static  int w32sdk_probe_formats(audio_desc_t ad);

static int  error = 0;
static char errorText[MAXERRORLENGTH];
static int  nLoopGain = 100;
#define     MAX_DEV_NAME 64

static UINT mapAudioDescToMixerID(audio_desc_t ad);

/* mcd_elem_t is a node used to store control state so 
 * we can restore mixer controls when device closes.
 */

typedef struct s_mcd_elem {
        MIXERCONTROLDETAILS *pmcd;
        struct s_mcd_elem   *next;
} mcd_elem_t;

static mcd_elem_t *control_list;

#define MIX_ERR_LEN 32
#define MIX_MAX_CTLS 8
#define MIX_MAX_GAIN 100

static int32_t	play_vol, rec_vol;
static HMIXER   hMixer;

static DWORD    dwRecLineID, dwVolLineID; 

static audio_port_details_t *input_ports, *loop_ports;
static int                   n_input_ports, n_loop_ports;
static int iport; /* Current input port */

/* Macro to convert macro name to string so we diagnose controls and error  */
/* codes.                                                                   */ 
#define CASE_STRING(x) case x: return #x

/* DEBUGGING FUNCTIONS ******************************************************/

static const char *
mixGetErrorText(MMRESULT mmr)
{
#ifndef NDEBUG
        switch (mmr) {
        CASE_STRING(MMSYSERR_NOERROR);     
        CASE_STRING(MIXERR_INVALLINE);     
        CASE_STRING(MIXERR_INVALCONTROL);  
        CASE_STRING(MIXERR_INVALVALUE);    
        CASE_STRING(WAVERR_BADFORMAT);     
        CASE_STRING(MMSYSERR_BADDEVICEID); 
        CASE_STRING(MMSYSERR_INVALFLAG);   
        CASE_STRING(MMSYSERR_INVALHANDLE); 
        CASE_STRING(MMSYSERR_INVALPARAM);  
        CASE_STRING(MMSYSERR_NODRIVER);
        default:
                return "Undefined Error";
        }
#endif /* NDEBUG */
        return "Mixer Error.";
}

static const char *
mixGetControlType(DWORD dwCtlType)
{
#ifndef NDEBUG
        switch(dwCtlType) {
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_CUSTOM);        
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_BOOLEANMETER);  
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_SIGNEDMETER);   
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_PEAKMETER);     
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_UNSIGNEDMETER); 
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_BOOLEAN);       
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_ONOFF);         
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_MUTE);          
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_MONO);          
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_LOUDNESS);      
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_STEREOENH);     
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_BUTTON);        
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_DECIBELS);      
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_SIGNED);        
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_UNSIGNED);      
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_PERCENT);       
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_SLIDER);        
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_PAN);           
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_QSOUNDPAN);     
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_FADER);         
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_VOLUME);        
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_BASS);          
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_TREBLE);        
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_EQUALIZER);     
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_SINGLESELECT);  
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_MUX);           
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT);
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_MIXER);         
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_MICROTIME);     
        CASE_STRING(MIXERCONTROL_CONTROLTYPE_MILLITIME);    
        }
#endif /* NDEBUG */
        return "Unknown";
}

static void
mixerDumpLineInfo(HMIXEROBJ hMix, DWORD dwLineID)
{
        MIXERLINECONTROLS mlc;
        LPMIXERCONTROL    pmc;
        MIXERLINE ml;
        MMRESULT  mmr;
        UINT      i;
        
        /* Determine number of controls */
        ml.cbStruct = sizeof(ml);
        ml.dwLineID = dwLineID;
        
        mmr = mixerGetLineInfo((HMIXEROBJ)hMix, &ml, MIXER_GETLINEINFOF_LINEID | MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg(mixGetErrorText(mmr));
                return;
        }
        
        pmc = (LPMIXERCONTROL)xmalloc(sizeof(MIXERCONTROL)*ml.cControls);
        mlc.cbStruct  = sizeof(MIXERLINECONTROLS);
        mlc.cbmxctrl  = sizeof(MIXERCONTROL);
        mlc.pamxctrl  = pmc;
        mlc.cControls = ml.cControls;
        mlc.dwLineID  = dwLineID;
        
        mmr = mixerGetLineControls((HMIXEROBJ)hMix, &mlc, MIXER_GETLINECONTROLSF_ALL | MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg(mixGetErrorText(mmr));
                xfree(pmc);
                return;
        }
        
        for(i = 0; i < ml.cControls; i++) {
                debug_msg("- %u %s\t\t %s\n", i, pmc[i].szName, mixGetControlType(pmc[i].dwControlType));
        }
        xfree(pmc);
}

/* Code for saving control states when claiming device, so we can restore the 
 * config when we release the device.  Lots of request for this 
 */

int
mcd_elem_add_control(mcd_elem_t **pplist, MIXERCONTROLDETAILS *pmcd)
{
        mcd_elem_t *elem;
        
        elem = (mcd_elem_t*)xmalloc(sizeof(mcd_elem_t));
        if (elem) {
                elem->pmcd = pmcd;
                elem->next = *pplist;
                *pplist    = elem;
                return TRUE;
        }
        return FALSE;
}

MIXERCONTROLDETAILS*
mcd_elem_get_control(mcd_elem_t **pplist)
{
        MIXERCONTROLDETAILS *pmcd;
        mcd_elem_t *elem;
        
        elem = *pplist;
        if (elem) {
                pmcd    = elem->pmcd;
                *pplist = elem->next;
                xfree(elem);
                return pmcd;
        }
        return NULL;
}

void
mixRestoreControls(UINT uMix, mcd_elem_t **pplist)
{
        MIXERCONTROLDETAILS *pmcd;
        MMRESULT mmr;

        return;

        while((pmcd = mcd_elem_get_control(pplist)) != NULL) {
                mmr = mixerSetControlDetails((HMIXEROBJ)uMix, pmcd, MIXER_OBJECTF_MIXER);
                xfree(pmcd->paDetails);
                xfree(pmcd);
                if (mmr != MMSYSERR_NOERROR) {
                        debug_msg("mixerSetControlDetails: %s\n", mixGetErrorText(mmr));
                        continue;
                }
        }
        assert(*pplist == NULL);
}

void
mixSaveLine(UINT uMix, MIXERLINE *pml, mcd_elem_t **pplist)
{
        MIXERCONTROLDETAILS *pmcd;
        MIXERLINECONTROLS mlc;
        MIXERCONTROL     *pmc;
        MMRESULT          mmr;
        UINT              i;
        
        /* Retrieve control types */
        pmc = (MIXERCONTROL*)xmalloc(sizeof(MIXERCONTROL)*pml->cControls);
        
        mlc.cbStruct  = sizeof(mlc);
        mlc.dwLineID  = pml->dwLineID;
        mlc.cControls = pml->cControls;
        mlc.pamxctrl  = pmc;
        mlc.cbmxctrl  = sizeof(MIXERCONTROL);
        
        debug_msg("Saving %s\n", pml->szName);

        mmr = mixerGetLineControls((HMIXEROBJ)uMix, &mlc, MIXER_GETLINECONTROLSF_ALL | MIXER_OBJECTF_MIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("mixerGetLineControls: %s\n", mixGetErrorText(mmr));
                xfree(pmc);
                return;
        }
        
        for(i = 0; i < pml->cControls; i++) {
                DWORD itemCnt, itemSz;
                if (pmc[i].cMultipleItems == 0) {
                        itemCnt = 1;	
                } else {
                        itemCnt = pmc[i].cMultipleItems;
                } 
                
                switch(pmc[i].dwControlType & MIXERCONTROL_CT_UNITS_MASK) {
                        /* Our application on affects boolean types (mute, on/off) and unsigned (vol) */
                case MIXERCONTROL_CT_UNITS_BOOLEAN:
                        itemSz = sizeof(MIXERCONTROLDETAILS_BOOLEAN);
                        break;
                case MIXERCONTROL_CT_UNITS_UNSIGNED:
                        itemSz = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
                        break;
                default:
                        debug_msg("not done %s\n", pmc[i].szName);
                        continue;
                }
                pmcd = (MIXERCONTROLDETAILS*)xmalloc(sizeof(MIXERCONTROLDETAILS));
                pmcd->cbStruct       = sizeof(MIXERCONTROLDETAILS);
                pmcd->cMultipleItems = pmc[i].cMultipleItems;
                pmcd->dwControlID    = pmc[i].dwControlID;
                pmcd->cChannels      = 1;
                pmcd->paDetails      = (void*)xmalloc(itemSz * itemCnt);
                pmcd->cbDetails      = itemSz;
                
                mmr = mixerGetControlDetails((HMIXEROBJ)uMix, pmcd, MIXER_GETCONTROLDETAILSF_VALUE | MIXER_OBJECTF_MIXER);
                if (mmr != MMSYSERR_NOERROR) {
                        debug_msg("mixerGetControlDetails: %s\n", mixGetErrorText(mmr));
                        continue;
                }
                mcd_elem_add_control(pplist, pmcd);
        }
        xfree(pmc);
}


void
mixSaveControls(UINT uMix, mcd_elem_t **pplist)
{
        MIXERLINE ml, sml;
        MIXERCAPS mc;
        MMRESULT  mmr;
        UINT i,j;
        
        mmr = mixerGetDevCaps(uMix, &mc, sizeof(mc));
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("mixerGetDevCaps: %s\n", mixGetErrorText(mmr));
                return;
        }
        
        for(i = 0; i < mc.cDestinations; i++) {
                memset(&ml, 0, sizeof(ml));
                ml.cbStruct      = sizeof(ml);
                ml.dwDestination = i;
                mmr = mixerGetLineInfo((HMIXEROBJ)uMix, &ml, MIXER_OBJECTF_MIXER | MIXER_GETLINEINFOF_DESTINATION); 
                if (mmr != MMSYSERR_NOERROR) {
                        debug_msg("mixerGetLineInfo: %s\n", mixGetErrorText(mmr));
                        continue;
                }
                mixSaveLine(uMix, &ml, pplist);
                for (j = 0; j < ml.cConnections; j++) {
                        memset(&sml, 0, sizeof(sml));
                        sml.cbStruct = sizeof(sml);
                        sml.dwSource = j;
                        mmr = mixerGetLineInfo((HMIXEROBJ)uMix, &sml, MIXER_OBJECTF_MIXER | MIXER_GETLINEINFOF_SOURCE); 
                        if (mmr != MMSYSERR_NOERROR) {
                                debug_msg("mixerGetLineInfo: %s\n", mixGetErrorText(mmr));
                                continue;
                        }
                        mixSaveLine(uMix, &sml, pplist);
                }
        }
}

/* CODE FOR CONTROLLING INPUT AND OUTPUT (LOOPBACK) LINES *******************
 * NOTE: the control of input lines and output lines is slightly different
 * because most card manufacturers put the volume and mute controls for output
 * as controls on the same output line.  The selection of the input lines is
 * controlled on the MUX control actually on the recording source, and the
 * volume control is on a line for the the input port.  To match the input 
 * select and the volume control we use the name of the line the volume
 * control is assigned to, and this ties in with the names on the MUX.  This
 * seems to be the only sensible way to correlate the two and it isn't in
 * the msdn library documentation.  I wasted a fair amount of time, trying
 * to match the name of the volume control and names in the MUX list, and
 * got this to work for all but one card.
 */

/* mixGetInputInfo - attempt to find corresponding wavein index
* for mixer uMix and corresponding destination line of mixer.  
* Returns TRUE if successful.
*/

int mixGetInputInfo(UINT uMix, UINT *puWavIn, DWORD *pdwLineID)
{
        UINT i, nWavIn;
        MIXERLINE  ml;
        MMRESULT   mmr;
        WAVEINCAPS wic;
        MIXERCAPS  mc;
        
        mmr = mixerGetDevCaps(uMix, &mc, sizeof(mc));
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("mixerGetDevCaps: %s\n", mixGetErrorText(mmr));
                return FALSE;
        }
        
        nWavIn = waveInGetNumDevs();
        for(i = 0; i < nWavIn; i++) {
                mmr = waveInGetDevCaps(i, &wic, sizeof(wic));
                if (mmr != MMSYSERR_NOERROR) {
                        debug_msg("waveInGetDevCaps: %s\n", mixGetErrorText(mmr));
                        continue;
                }
                
                ml.cbStruct       = sizeof(ml);
                ml.Target.dwType  = MIXERLINE_TARGETTYPE_WAVEIN;
                strncpy(ml.Target.szPname, wic.szPname, MAXPNAMELEN);
                ml.Target.vDriverVersion = wic.vDriverVersion;
                ml.Target.wMid    = wic.wMid;
                ml.Target.wPid    = wic.wPid;
                
                mmr = mixerGetLineInfo((HMIXEROBJ)uMix, &ml, MIXER_OBJECTF_MIXER | MIXER_GETLINEINFOF_TARGETTYPE);
                if (mmr == MMSYSERR_NOERROR) {
                        *puWavIn          = i;
                        *pdwLineID = ml.dwLineID;
                        debug_msg("Input: %s(%d - %d)\n", ml.szName, ml.dwDestination, ml.dwLineID);
                        return TRUE;
                } else {
                        debug_msg("mixerGetLineInfo (ignore this error): %s\n", mixGetErrorText(mmr));
                }
        }
        return FALSE;
}

/* mixGetOutputInfo - attempt to find corresponding waveout index
 * and corresponding destination line of mixer.  Returns TRUE if
 * successful.
 */
int 
mixGetOutputInfo(UINT uMix, UINT *puWavOut, DWORD *pdwLineID)
{
        UINT i, nWavOut;
        MIXERLINE  ml;
        MMRESULT   mmr;
        WAVEOUTCAPS woc;
        MIXERCAPS  mc;
        
        mmr = mixerGetDevCaps(uMix, &mc, sizeof(mc));
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("mixerGetDevCaps: %s\n", mixGetErrorText(mmr));
                return FALSE;
        }
        
        nWavOut = waveOutGetNumDevs();
        for(i = 0; i < nWavOut; i++) {
                mmr = waveOutGetDevCaps(i, &woc, sizeof(woc));
                if (mmr != MMSYSERR_NOERROR) {
                        debug_msg("waveOutGetDevCaps: %s\n", mixGetErrorText(mmr));
                        continue;
                }
                ml.cbStruct       = sizeof(ml);
                ml.Target.dwType  = MIXERLINE_TARGETTYPE_WAVEOUT;
                strncpy(ml.Target.szPname, woc.szPname, MAXPNAMELEN);
                ml.Target.vDriverVersion = woc.vDriverVersion;
                ml.Target.wMid    = woc.wMid;
                ml.Target.wPid    = woc.wPid;
                
                mmr = mixerGetLineInfo((HMIXEROBJ)uMix, &ml, MIXER_OBJECTF_MIXER | MIXER_GETLINEINFOF_TARGETTYPE);
                if (mmr == MMSYSERR_NOERROR) {
                        *puWavOut  = i;
                        *pdwLineID = ml.dwLineID;
                        debug_msg("Output: %s(%d - %d)\n", ml.szName, ml.dwDestination, ml.dwLineID);
                        return TRUE;
                } 
        }
        return FALSE;
}

/* mixerEnableInputLine - enables the input line whose name starts with beginning of portname.  
 * We cannot just use the port index like we do for volume because the mute controls are
 * not necessarily in the same order as the volume controls (grrr!).  The only card
 * that we have seen where this is necessary is the Winnov Videum AV, but there are
 * bound to be others.
 * Muting for input lines on the toplevel control (Rec, or whatever driver happens to call it).
 * It usually has a single control a MUX/Mixer that has "multiple items", one mute for
 * each input line.  Depending on the control type it may be legal to have multiple input
 * lines enabled, or just one.  So mixerEnableInputLine disables all lines other than
 * one selected.
 */

static int
mixerEnableInputLine(HMIXEROBJ hMix, char *portname)
{
        MIXERCONTROLDETAILS_BOOLEAN *mcdbState;
        MIXERCONTROLDETAILS_LISTTEXT *mcdlText;
        MIXERCONTROLDETAILS mcd;
        MIXERLINECONTROLS mlc;
        MIXERCONTROL mc;
        MIXERLINE ml;
        MMRESULT  mmr;
        UINT      i, matchLine;
        
        ml.cbStruct = sizeof(ml);
        ml.dwLineID = dwRecLineID;
        
        mmr = mixerGetLineInfo(hMix, &ml, MIXER_GETLINEINFOF_LINEID|MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("mixerGetLineInfo: %s\n", mixGetErrorText(mmr));
        }
        
        /* Get Mixer/MUX control information (need control id to set and get control details) */
        mlc.cbStruct      = sizeof(mlc);
        mlc.dwLineID      = ml.dwLineID;
        mlc.pamxctrl      = &mc;
        mlc.cbmxctrl      = sizeof(mc);
        
        mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX; /* Single Select */
        mmr = mixerGetLineControls(hMix, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE|MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MIXER; /* Multiple Select */
                mmr = mixerGetLineControls(hMix, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE|MIXER_OBJECTF_HMIXER);
                if (mmr != MMSYSERR_NOERROR) {
                        debug_msg("mixerGetLineControls: %s\n", mixGetErrorText(mmr));
                        return FALSE;
                }
        }
        
        mcd.cbStruct    = sizeof(mcd);
        mcd.dwControlID = mc.dwControlID;
        mcd.cChannels   = 1;
        mcd.cMultipleItems = mc.cMultipleItems;
        mcdlText = (MIXERCONTROLDETAILS_LISTTEXT*)xmalloc(sizeof(MIXERCONTROLDETAILS_LISTTEXT)*mc.cMultipleItems);        
        mcd.paDetails = mcdlText;
        mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_LISTTEXT);
        mmr = mixerGetControlDetails(hMix, &mcd, MIXER_GETCONTROLDETAILSF_LISTTEXT | MIXER_OBJECTF_MIXER);
        
        matchLine = 0;
        for(i = 0; i < mcd.cMultipleItems; i++) {
                if (!strcmp(mcdlText[i].szName, portname)) {
                        matchLine = i;
                        break;
                }
        }
        xfree(mcdlText);

        /* Now get control itself */
        mcd.cbStruct    = sizeof(mcd);
        mcd.dwControlID = mc.dwControlID;
        mcd.cChannels   = 1;
        mcd.cMultipleItems = mc.cMultipleItems;
        mcdbState = (MIXERCONTROLDETAILS_BOOLEAN*)xmalloc(sizeof(MIXERCONTROLDETAILS_BOOLEAN)*mc.cMultipleItems);        
        mcd.paDetails = mcdbState;
        mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN);
        
        mmr = mixerGetControlDetails(hMix, &mcd, MIXER_GETCONTROLDETAILSF_VALUE|MIXER_OBJECTF_MIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("mixerGetControlDetails: %s\n", mixGetErrorText(mmr));
                xfree(mcdbState);
                return FALSE;
        }
        
        for(i = 0; i < mcd.cMultipleItems; i++) {
                if (i == matchLine) {
                        mcdbState[i].fValue = TRUE;
                } else {
                        mcdbState[i].fValue = FALSE;
                }
        }
        
        mmr = mixerSetControlDetails(hMix, &mcd, MIXER_OBJECTF_MIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("mixerSetControlDetails: %s\n", mixGetErrorText(mmr));
                xfree(mcdbState);
                return FALSE;
        }
        
        xfree(mcdbState);
        return TRUE;
}

static int
mixerEnableOutputLine(HMIXEROBJ hMix, DWORD dwLineID, int state)
{
        MIXERCONTROLDETAILS_BOOLEAN mcdbState;
        MIXERCONTROLDETAILS mcd;
        MIXERLINECONTROLS mlc;
        MIXERCONTROL      mc;
        MMRESULT          mmr;
        
        mlc.cbStruct      = sizeof(mlc);
        mlc.pamxctrl      = &mc;
        mlc.cbmxctrl      = sizeof(MIXERCONTROL);
        mlc.dwLineID      = dwLineID;
        mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE;
        
        mmr = mixerGetLineControls(hMix, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE | MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                mlc.cbStruct      = sizeof(mlc);
                mlc.pamxctrl      = &mc;
                mlc.cbmxctrl      = sizeof(MIXERCONTROL);
                mlc.dwLineID      = dwLineID;
                mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_ONOFF;
                mmr = mixerGetLineControls(hMix, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE | MIXER_OBJECTF_HMIXER);
                if (mmr != MMSYSERR_NOERROR) {
                        debug_msg("Could not get mute control for line 0x%08x: %s\n", 
                                dwLineID,
                                mixGetErrorText(mmr));
                        mixerDumpLineInfo(hMix, dwLineID);
                        return FALSE;
                }
        }
        
        mcd.cbStruct       = sizeof(mcd);
        mcd.dwControlID    = mc.dwControlID;
        mcd.cChannels      = 1;
        mcd.cMultipleItems = mc.cMultipleItems;
        mcd.cbDetails      = sizeof(MIXERCONTROLDETAILS_BOOLEAN);
        mcd.paDetails      = &mcdbState;
        mcdbState.fValue   = !((UINT)state);
        
        mmr = mixerSetControlDetails((HMIXEROBJ)hMix, &mcd, MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("Could not set mute state for line 0x%08x\n", dwLineID);
                return FALSE;
        }
        return TRUE;
}

/* MixerSetLineGain - sets gain of line (range 0-MIX_MAX_GAIN) */
static int
mixerSetLineGain(HMIXEROBJ hMix, DWORD dwLineID, int gain)
{
        MIXERCONTROLDETAILS_UNSIGNED mcduGain;
        MIXERCONTROLDETAILS mcd;
        MIXERLINECONTROLS mlc;
        MIXERCONTROL      mc;
        MMRESULT          mmr;
        
        mlc.cbStruct      = sizeof(mlc);
        mlc.pamxctrl      = &mc;
        mlc.cbmxctrl      = sizeof(MIXERCONTROL);
        mlc.dwLineID      = dwLineID;
        mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
        
        mmr = mixerGetLineControls(hMix, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE | MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("Could not volume control for line 0x%08x: %s\n", 
                        dwLineID,
                        mixGetErrorText(mmr));
                return FALSE;        
        }
        
        mcd.cbStruct       = sizeof(mcd);
        mcd.dwControlID    = mc.dwControlID;
        mcd.cChannels      = 1;
        mcd.cMultipleItems = mc.cMultipleItems;
        mcd.cbDetails      = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
        mcd.paDetails      = &mcduGain;
        mcduGain.dwValue   = ((mc.Bounds.dwMaximum - mc.Bounds.dwMinimum) * gain)/MIX_MAX_GAIN;
        
        mmr = mixerSetControlDetails((HMIXEROBJ)hMix, &mcd, MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("Could not set gain for line 0x%08x: %s\n", dwLineID, mixGetErrorText(mmr));
                return FALSE;
        }
        return TRUE;
}

/* MixerGetLineGain - returns gain of line (range 0-MIX_MAX_GAIN) */
static int
mixerGetLineGain(HMIXEROBJ hMix, DWORD dwLineID)
{
        MIXERCONTROLDETAILS_UNSIGNED mcduGain;
        MIXERCONTROLDETAILS mcd;
        MIXERLINECONTROLS mlc;
        MIXERCONTROL      mc;
        MMRESULT          mmr;
        
        mlc.cbStruct      = sizeof(mlc);
        mlc.pamxctrl      = &mc;
        mlc.cbmxctrl      = sizeof(MIXERCONTROL);
        mlc.dwLineID      = dwLineID;
        mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
        
        mmr = mixerGetLineControls(hMix, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE | MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("Could not find volume control for line 0x%08x\n", dwLineID);
                return 0;        
        }
        
        mcd.cbStruct       = sizeof(mcd);
        mcd.dwControlID    = mc.dwControlID;
        mcd.cChannels      = 1;
        mcd.cMultipleItems = mc.cMultipleItems;
        mcd.cbDetails      = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
        mcd.paDetails      = &mcduGain;
        
        mmr = mixerGetControlDetails((HMIXEROBJ)hMix, &mcd, MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("Could not get gain for line 0x%08x\n", dwLineID);
                return 0;
        }
        return (int)(mcduGain.dwValue * MIX_MAX_GAIN / (mc.Bounds.dwMaximum - mc.Bounds.dwMinimum));
}

static int
mixerGetLineName(HMIXEROBJ hMix, DWORD dwLineID, char *szName, UINT uLen)
{
        MIXERLINE           ml;
        MIXERLINECONTROLS   mlc;
        MIXERCONTROL        mc;
        MMRESULT            mmr;
        
        mlc.cbStruct      = sizeof(mlc);
        mlc.pamxctrl      = &mc;
        mlc.cbmxctrl      = sizeof(MIXERCONTROL);
        mlc.dwLineID      = dwLineID;
        mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
/*        
        mmr = mixerGetLineControls(hMix, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE | MIXER_OBJECTF_HMIXER);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("Could not find volume control for line 0x%08x: %s\n", dwLineID, mixGetErrorText(mmr));
                return FALSE;        
        }
*/
        memset(&ml,0, sizeof(MIXERLINE));
        ml.cbStruct = sizeof(MIXERLINE);
        ml.dwLineID = dwLineID;
        mmr = mixerGetLineInfo(hMix, &ml, MIXER_GETLINEINFOF_LINEID);
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("poo");
        }
        debug_msg("line name %s\n", ml.szName);
        strncpy(szName, ml.szName, uLen);
        return TRUE;
}

/* MixQueryControls: Get all line names and id's, fill into ppapd, and return number of lines */
static int
mixQueryControls(HMIXEROBJ hMix, DWORD dwLineID, audio_port_details_t** ppapd)
{
        MIXERCAPS mc;
        MIXERLINE mlt, mlc;
        audio_port_details_t *papd;
        MMRESULT mmr;
        UINT     i;
        
        /* Videum bug work around - Videum does not fill in number of connections if
         * called using MIXER_GETLINEINFOF_LINEID.  This is the only driver with this problem, 
         * but this seems to work in all cases.
         */        
        mixerGetDevCaps((UINT)hMix, &mc, sizeof(mc));
        for(i = 0; i < mc.cDestinations; i++) {
                memset(&mlt, 0, sizeof(mlt));
                mlt.cbStruct = sizeof(mlt);
                mlt.dwDestination = i;
                mmr = mixerGetLineInfo(hMix, &mlt, MIXER_GETLINEINFOF_DESTINATION);
                if (mmr != MMSYSERR_NOERROR) {
                        debug_msg("mixerGetLineInfo: %s\n", mixGetErrorText(mmr));
                        continue;
                }
                if (mlt.dwLineID == dwLineID) {
                        break;
                }
        }
        
        papd = (audio_port_details_t*)xmalloc(sizeof(audio_port_details_t)*mlt.cConnections);
        if (papd == NULL) {
                return 0;
        }
        
        mixerDumpLineInfo((HMIXEROBJ)hMix, mlt.dwLineID);
        
        for(i = 0; i < mlt.cConnections; i++) {
                memcpy(&mlc, &mlt, sizeof(mlc));
                mlc.dwSource = i;
                mmr = mixerGetLineInfo((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINEINFOF_SOURCE|MIXER_OBJECTF_HMIXER);
                if (mmr != MMSYSERR_NOERROR) {
                        xfree(papd);
                        return 0;
                }
                strncpy(papd[i].name, mlc.szName, AUDIO_PORT_NAME_LENGTH);
                papd[i].port = mlc.dwLineID;
        }
        
        *ppapd = papd;
        return (int)mlt.cConnections;
}

/* XXX make_microphone_first_port is a hack to make microphone 
 * the first (default) port.  Of course this only works for
 * english language drivers...
 */

static int
make_microphone_first_port(audio_port_details_t *ports, int n_ports)
{
        audio_port_details_t tmp;
        int i;
        
        for(i = 1; i < n_ports; i++) {
                if (!strncasecmp("mic", ports[i].name, 3) ||
                    !strncasecmp("mik", ports[i].name, 3)) {
                        memcpy(&tmp, ports + i, sizeof(tmp));
                        memcpy(ports + i , ports, sizeof(ports[0]));
                        memcpy(ports, &tmp, sizeof(ports[0]));
                        return TRUE;
                }
        }

        return FALSE;
}

static int 
mixSetup(UINT uMixer)
{
        MIXERCAPS mc;
        MMRESULT  res;
        
        if (hMixer)  {mixerClose(hMixer);  hMixer  = 0;}
        
        res = mixerOpen(&hMixer, uMixer, (unsigned long)NULL, (unsigned long)NULL, MIXER_OBJECTF_MIXER);
        if (res != MMSYSERR_NOERROR) {
                debug_msg("mixerOpen failed: %s\n", mixGetErrorText(res));
                return FALSE;
        }
        
        res = mixerGetDevCaps((UINT)hMixer, &mc, sizeof(mc));
        if (res != MMSYSERR_NOERROR) {
                debug_msg("mixerGetDevCaps failed: %s\n", mixGetErrorText(res));
                return FALSE;
        }
        
        if (mc.cDestinations < 2) {
                debug_msg("mixer does not have 2 destinations?\n");
                return FALSE;
        }
        
        if (input_ports != NULL) {
                xfree(input_ports);
                input_ports   = NULL;
                n_input_ports = 0;
        }
        
        n_input_ports = mixQueryControls((HMIXEROBJ)hMixer, dwRecLineID, &input_ports);
        debug_msg("Input ports %d\n", n_input_ports);
        if (n_input_ports == 0) {
                return FALSE;
        }
        
        make_microphone_first_port(input_ports, n_input_ports);

        if (loop_ports != NULL) {
                xfree(loop_ports);
                loop_ports   = NULL;
                n_loop_ports = 0;
        }
        
        n_loop_ports = mixQueryControls((HMIXEROBJ)hMixer, dwVolLineID, &loop_ports);
        debug_msg("Loop ports %d\n", n_loop_ports);
        if (n_loop_ports == 0) {
                return 0;
        }
        return TRUE;
}

/* Global variables used by read and write processing                                    */
static int blksz;
static int nblks;
static int smplsz;

/* AUDIO OUTPUT RELATED FN's                                                             */
static HWAVEOUT	shWaveOut;         /* Handle for wave output                             */
static WAVEHDR *whWriteHdrs;       /* Pointer to blovk of wavehdr's alloced for writing  */
static u_char  *lpWriteData;       /* Pointer to raw audio data buffer                   */

static int
w32sdk_audio_open_out(UINT uId, WAVEFORMATEX *pwfx)
{
        MMRESULT        mmr;
        int		i;
        
        if (shWaveOut) {
                return (TRUE);
        }
        
        mmr = waveOutOpen(&shWaveOut, uId, pwfx, 0, 0, CALLBACK_NULL);
        if (mmr != MMSYSERR_NOERROR) {
                waveOutGetErrorText(mmr, errorText, sizeof(errorText));
                debug_msg("waveOutOpen: (%d) %s\n", mmr, errorText);
                return (FALSE);
        }
        
        if (lpWriteData != NULL) {
                xfree(lpWriteData);
        }
        lpWriteData = (u_char*)xmalloc(nblks * blksz);
        memset(lpWriteData, 0, nblks * blksz);
        
        if (whWriteHdrs != NULL) {
                xfree(whWriteHdrs);
        }
        whWriteHdrs = (WAVEHDR*)xmalloc(sizeof(WAVEHDR)*nblks);
        memset(whWriteHdrs, 0, sizeof(WAVEHDR)*nblks);

        for (i = 0; i < nblks; i++) {
                whWriteHdrs[i].dwFlags        = 0;
                whWriteHdrs[i].dwBufferLength = blksz;
                whWriteHdrs[i].lpData         = lpWriteData + i * blksz;
                whWriteHdrs[i].dwUser         = i; /* For debugging purposes */
                mmr = waveOutPrepareHeader(shWaveOut, &whWriteHdrs[i], sizeof(WAVEHDR));
                whWriteHdrs[i].dwFlags |= WHDR_DONE; /* Mark buffer as done - used to find free buffers */
		assert(mmr == MMSYSERR_NOERROR);
        }

        return (TRUE);
}

static void
w32sdk_audio_close_out()
{
        int i;
        
        if (shWaveOut == 0) {
                return;
        }
        
	waveOutReset(shWaveOut);
        
	for (i = 0; i < nblks; i++) {
                if (whWriteHdrs[i].dwFlags & WHDR_PREPARED) {
                        waveOutUnprepareHeader(shWaveOut, &whWriteHdrs[i], sizeof(WAVEHDR));
                }
        }
        
	waveOutClose(shWaveOut);
        
	xfree(whWriteHdrs); whWriteHdrs = NULL;
        xfree(lpWriteData); lpWriteData  = NULL;
      
        xmemchk();
        shWaveOut = 0;
}


#define WRITE_ERROR_STILL_PLAYING 33

const char *waveOutError(MMRESULT mmr)
{
	switch (mmr){
		CASE_STRING(MMSYSERR_NOERROR);
		CASE_STRING(MMSYSERR_INVALHANDLE);
		CASE_STRING(MMSYSERR_NODRIVER);
		CASE_STRING(MMSYSERR_NOMEM);
		CASE_STRING(WAVERR_UNPREPARED);
		CASE_STRING(WRITE_ERROR_STILL_PLAYING);
	default:
		return "Unknown";
	}
}

WAVEHDR *
w32sdk_audio_write_get_buffer()
{
	int	 i;

	for (i = 0; i < nblks; i++) {
		assert(whWriteHdrs[i].dwFlags & WHDR_PREPARED);
		if (whWriteHdrs[i].dwFlags & WHDR_DONE) {
			whWriteHdrs[i].dwFlags &= WHDR_PREPARED;
			return &whWriteHdrs[i];
		}
	}
	return NULL;
}

int
w32sdk_audio_write(audio_desc_t ad, u_char *buf , int buf_bytes)
{
        WAVEHDR   *whCur;
        MMRESULT   mmr;
        int        done, this_write;
        
        /* THis is slightly ugly because we handle writes of any size, not just */
        /* multiples of blksz. RAT likes to write multiples of the cushion step */
        /* size which is usually 1/2 device blksz.                              */
               
        done = 0;
        while(done < buf_bytes) {
                whCur = w32sdk_audio_write_get_buffer();
		if (whCur == NULL) {
			debug_msg("Write/Right out of buffers ???\n");
			break;
		}
		this_write = min(buf_bytes - done, (int)blksz);
		whCur->dwBufferLength = this_write;
                memcpy(whCur->lpData, 
                        buf + done,
                        this_write);
                done  += this_write;
                mmr    = waveOutWrite(shWaveOut, whCur, sizeof(WAVEHDR));
                if (mmr == WRITE_ERROR_STILL_PLAYING) {
                        debug_msg("Device filled\n");
                        break;
                }
                assert(mmr == MMSYSERR_NOERROR);
        }

        assert(done <= buf_bytes);
       
        return done;
}

/* AUDIO INPUT RELATED FN's *********************************/

static HWAVEIN	shWaveIn;               /* Handle for wave input                                */
static WAVEHDR	*whReadHdrs;            /* Pointer to block of wavehdr's allocated for reading  */
static u_char	*lpReadData;            /* Pointer to raw audio data buffer                     */
static WAVEHDR  *whReadList;            /* List of wave headers that have been read but not     */
                                        /* given to the application.                            */ 
static DWORD     dwBytesUsedAtReadHead; /* Number of bytes that have already been read at head  */
static HANDLE    hAudioReady;           /* Audio Ready Event */

int
w32sdk_audio_is_ready(audio_desc_t ad)
{
        UNUSED(ad);
        return (whReadList != NULL);
}

static void CALLBACK
waveInProc(HWAVEIN hwi,
           UINT    uMsg,
           DWORD   dwInstance,
           DWORD   dwParam1,
           DWORD   dwParam2)
{
        WAVEHDR *whRead, **whInsert;

        switch(uMsg) {
        case WIM_DATA:
                whRead = (WAVEHDR*)dwParam1;       
		/* Insert block at the available list */
                whRead->lpNext   = NULL;  
		whInsert = &whReadList;
                while(*whInsert != NULL) {
                        whInsert = &((*whInsert)->lpNext);
                }
                *whInsert = whRead;
                SetEvent(hAudioReady);
		break;
        default:
                ;  /* nothing to do currently */
        }
        UNUSED(dwInstance);
        UNUSED(dwParam2);
        UNUSED(hwi);
        
        return;
}

static int
w32sdk_audio_open_in(UINT uId, WAVEFORMATEX *pwfx)
{
        MMRESULT mmr;
        int      i;
        
        if (shWaveIn) {
		return (TRUE);
	}
        
        if (lpReadData != NULL) {
		xfree(lpReadData);
	}
        lpReadData = (u_char*)xmalloc(nblks * blksz);
        
        if (whReadHdrs != NULL) {
		xfree(whReadHdrs);
	}
        whReadHdrs = (WAVEHDR*)xmalloc(sizeof(WAVEHDR)*nblks); 
        
        mmr = waveInOpen(&shWaveIn, 
                         uId, 
                         pwfx,
                         (DWORD)waveInProc,
                         0,
                         CALLBACK_FUNCTION);
        
	if (mmr != MMSYSERR_NOERROR) {
                waveInGetErrorText(mmr, errorText, sizeof(errorText));
                debug_msg("waveInOpen: (%d) %s\n", mmr, errorText);
                return (FALSE);
        }

        /* Initialize wave headers */
        for (i = 0; i < nblks; i++) {
                whReadHdrs[i].lpData         = lpReadData + i * blksz;
                whReadHdrs[i].dwBufferLength = blksz;
                whReadHdrs[i].dwFlags        = 0;
                mmr = waveInPrepareHeader(shWaveIn, &whReadHdrs[i], sizeof(WAVEHDR));
                assert(mmr == MMSYSERR_NOERROR);               
                mmr = waveInAddBuffer(shWaveIn, &whReadHdrs[i], sizeof(WAVEHDR));
                assert(mmr == MMSYSERR_NOERROR);
        }

        whReadList           = NULL;
        dwBytesUsedAtReadHead = 0;

        error = waveInStart(shWaveIn);
        if (error) {
                waveInGetErrorText(error, errorText, sizeof(errorText));
                debug_msg("Win32Audio: waveInStart: (%d) %s\n", error, errorText);
                exit(1);
        }
        hAudioReady = CreateEvent(NULL, TRUE, FALSE, "RAT Audio Ready");
        
	return (TRUE);
}

static void
w32sdk_audio_close_in()
{
        int		i;
        
        if (shWaveIn == 0)
                return;
        
        waveInStop(shWaveIn);
        waveInReset(shWaveIn);
        
        for (i = 0; i < nblks; i++) {
                if (whReadHdrs[i].dwFlags & WHDR_PREPARED) {
                        waveInUnprepareHeader(shWaveIn, &whReadHdrs[i], sizeof(WAVEHDR));
                }
        }
        whReadList = NULL;

        waveInClose(shWaveIn);           
	shWaveIn = 0;
        
	xfree(whReadHdrs);               
	whReadHdrs = NULL;
        
	xfree(lpReadData);               
	lpReadData  = NULL;
        
        xmemchk();
}

int
w32sdk_audio_read(audio_desc_t ad, u_char *buf, int buf_bytes)
{
        WAVEHDR *whCur;
	MMRESULT mmr;
        int done = 0, this_read;
        static int added;
        
	/* This is slightly ugle because we want to be able to operate when     */
        /* buf_bytes has any value, not just a multiple of blksz.  In principle */
        /* we do this so the device blksz does not have to match application    */
        /* blksz.  I.e. can reduce process usage by using larger blocks at      */
        /* device whilst the app operates on smaller blocks.                    */

        while(whReadList != NULL && done < buf_bytes) {
		whCur = whReadList;
		this_read = min((int)(whCur->dwBytesRecorded - dwBytesUsedAtReadHead), buf_bytes - done);
                if (buf) {
			memcpy(buf + done, 
			       whCur->lpData + dwBytesUsedAtReadHead,
			       this_read);
		}
                done                  += this_read;
                dwBytesUsedAtReadHead += this_read;
                if (dwBytesUsedAtReadHead == whCur->dwBytesRecorded) {
                        whReadList = whReadList->lpNext;
			/* Finished with the block give it device */
			assert(whCur->dwFlags & WHDR_DONE);
			assert(whCur->dwFlags & ~WHDR_INQUEUE);
                   	whCur->lpNext          = NULL; 
			whCur->dwBytesRecorded = 0; 
			whCur->dwFlags        &= ~WHDR_DONE;
			mmr = waveInAddBuffer(shWaveIn, whCur, sizeof(WAVEHDR)); 
                        assert(mmr == MMSYSERR_NOERROR);
			assert(whCur->dwFlags & WHDR_INQUEUE);
                        dwBytesUsedAtReadHead = 0;
			added++;
                }
		assert((int)dwBytesUsedAtReadHead < blksz);
        }
	
        assert(done <= buf_bytes);
	UNUSED(ad);
        return done;
}

void
w32sdk_audio_drain(audio_desc_t ad)
{
	waveInStop(shWaveIn);
        w32sdk_audio_read(ad, NULL, 10000000);
	waveInStart(shWaveIn);
}

static void dumpReadHdrStats()
{
	WAVEHDR *whp;
	int i, done, inqueue, prepared, ready;
	
	done = inqueue = prepared = 0;
	for(i = 0; i < nblks; i++) {
		if (whReadHdrs[i].dwFlags & WHDR_DONE) {
			done++;
		}
		if (whReadHdrs[i].dwFlags & WHDR_INQUEUE) {
			inqueue++;
		}
		if (whReadHdrs[i].dwFlags & WHDR_PREPARED) {
			prepared++;
		}
	}

	ready = 0;
	whp = whReadList;
	while (whp != NULL) {
		ready++;
		whp = whp->lpNext;
	}
	debug_msg("done %d inqueue %d prepared %d ready %d\n",
		done, inqueue, prepared, ready);
}

void
w32sdk_audio_wait_for(audio_desc_t ad, int delay_ms)
{        
        if (whReadList == NULL) {
                DWORD dwRes;
		dwRes = WaitForSingleObject(hAudioReady, delay_ms);
		switch(dwRes) {
		case WAIT_TIMEOUT:
			debug_msg("No audio (%d ms wait timeout)\n", delay_ms);
			dumpReadHdrStats();
			break;
		case WAIT_FAILED:
			debug_msg("Wait failed (error %u)\n", GetLastError());
			break;
		}
                ResetEvent(hAudioReady);
        }
	waveInStart(shWaveIn);
        UNUSED(ad);
}

static int audio_dev_open = 0;

static int
w32sdk_audio_open_mixer(audio_desc_t ad, audio_format *fmt, audio_format *ofmt)
{
        static int virgin;
        WAVEFORMATEX owfx, wfx;
        UINT uWavIn, uWavOut;

        if (audio_dev_open) {
                debug_msg("Device not closed! Fix immediately");
                w32sdk_audio_close(ad);
        }
        
        assert(audio_format_match(fmt, ofmt));
        if (fmt->encoding != DEV_S16) {
                return FALSE; /* Only support L16 for time being */
        }
        
        if (mixGetInputInfo(ad, &uWavIn, &dwRecLineID) != TRUE) {
                debug_msg("Could not get wave in or mixer destination for mix %u\n", ad);
                return FALSE;
        }

        if (mixGetOutputInfo(ad, &uWavOut, &dwVolLineID) != TRUE) {
                debug_msg("Could not get wave out or mixer destination for mix %u\n", ad);
                return FALSE;
        }
        
        if (mixSetup(ad) == FALSE) {
                return FALSE; /* Could not secure mixer */
        }

        mixSaveControls(ad, &control_list);

        wfx.wFormatTag      = WAVE_FORMAT_PCM;
        wfx.nChannels       = (WORD)fmt->channels;
        wfx.nSamplesPerSec  = fmt->sample_rate;
        wfx.wBitsPerSample  = (WORD)fmt->bits_per_sample;
        smplsz              = wfx.wBitsPerSample / 8;
        wfx.nAvgBytesPerSec = wfx.nChannels * wfx.nSamplesPerSec * smplsz;
        wfx.nBlockAlign     = (WORD)(wfx.nChannels * smplsz);
        wfx.cbSize          = 0;
        
        memcpy(&owfx, &wfx, sizeof(wfx));
        
        /* Use 1 sec device buffer */	
        blksz  = fmt->bytes_per_block;
        nblks  = wfx.nAvgBytesPerSec / blksz;
        
        if (w32sdk_audio_open_in(uWavIn, &wfx) == FALSE){
                debug_msg("Open input failed\n");
                return FALSE;
        }
        
        assert(memcmp(&owfx, &wfx, sizeof(WAVEFORMATEX)) == 0);
        
        if (w32sdk_audio_open_out(uWavOut, &wfx) == FALSE) {
                debug_msg("Open output failed\n");
                w32sdk_audio_close_in();
                return FALSE;
        }

        /* because these get can corrupted... */
        assert(memcmp(&owfx, &wfx, sizeof(WAVEFORMATEX)) == 0);
    
        /* Set process priority as high as we can go without special permissions on */
        /* on NT.  Although this priority may seem anti-social, it's not that bad   */
        /* since we block whilst waiting for audio events.                          */
        SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
        
        /* SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);  */

        if (!have_probed[ad]) {
                have_probed[ad] = w32sdk_probe_formats(ad);
        }
 
        audio_dev_open = TRUE;
        return TRUE;
}

int 
w32sdk_audio_open(audio_desc_t ad, audio_format *ifmt, audio_format *ofmt)
{
        ad = mapAudioDescToMixerID(ad);
        return w32sdk_audio_open_mixer(ad, ifmt, ofmt);
}

static void
w32sdk_audio_close_mixer(audio_desc_t ad)
{
        MMRESULT mmr;

        debug_msg("Closing input device.\n");
        w32sdk_audio_close_in();
        
        debug_msg("Closing output device.\n");
        w32sdk_audio_close_out();
        
        if (input_ports != NULL) {
                xfree(input_ports);
                input_ports = NULL;
        }
        
        if (loop_ports != NULL) {
                xfree(loop_ports);
                loop_ports = NULL;
        }
        
        mixRestoreControls(ad, &control_list);
        mmr = mixerClose(hMixer); hMixer = 0;
        if (mmr != MMSYSERR_NOERROR) {
                debug_msg("mixerClose failed: %s\n", mixGetErrorText(mmr));
        }
        
        audio_dev_open = FALSE;
        UNUSED(ad);
}

void
w32sdk_audio_close(audio_desc_t ad)
{
        w32sdk_audio_close_mixer(ad);
}

int
w32sdk_audio_duplex(audio_desc_t ad)
{
        UNUSED(ad);
        return (TRUE);
}


void
w32sdk_audio_non_block(audio_desc_t ad)
{
        UNUSED(ad);
        debug_msg("Windows audio interface is asynchronous!\n");
}

void
w32sdk_audio_block(audio_desc_t ad)
{
        UNUSED(ad);
        debug_msg("Windows audio interface is asynchronous!\n");
}

void
w32sdk_audio_set_ogain(audio_desc_t ad, int level)
{
        DWORD	vol;
        
        UNUSED(ad);
        
        play_vol = level;
        
        if (shWaveOut == 0)
                return;
        
        vol = rat_to_device(level);
        error = waveOutSetVolume(shWaveOut, vol);
        if (error) {
                waveOutGetErrorText(error, errorText, sizeof(errorText));
                debug_msg("Win32Audio: waveOutSetVolume: %s\n", errorText);
        }
}

int
w32sdk_audio_get_ogain(audio_desc_t ad)
{
        DWORD	vol;
        
        UNUSED(ad);
        
        if (shWaveOut == 0) {
                return play_vol;
	}
        
        error = waveOutGetVolume(shWaveOut, &vol);
        if (error) {
                waveOutGetErrorText(error, errorText, sizeof(errorText));
                debug_msg("Win32Audio: waveOutGetVolume Error: %s\n", errorText);
                return 0;
        } else {
                return (device_to_rat(vol));
        }
}

void
w32sdk_audio_loopback(audio_desc_t ad, int gain)
{
        UNUSED(ad);
        
        nLoopGain = gain;
}

#define WIN32_SPEAKER 0x101010
static audio_port_details_t outports[] = {
        { WIN32_SPEAKER, AUDIO_PORT_SPEAKER}
};
#define NUM_OPORTS (sizeof(outports)/sizeof(outports[0]))

void
w32sdk_audio_oport_set(audio_desc_t ad, audio_port_t port)
{
        UNUSED(ad);
        UNUSED(port);
}

/* Return selected output port */
audio_port_t 
w32sdk_audio_oport_get(audio_desc_t ad)
{
        UNUSED(ad);
        return (WIN32_SPEAKER);
}

int
w32sdk_audio_oport_count(audio_desc_t ad)
{
        UNUSED(ad);
        return (int)NUM_OPORTS;
}

const audio_port_details_t*
w32sdk_audio_oport_details(audio_desc_t ad, int idx)
{
        UNUSED(ad);
        assert(idx >= 0 && idx < NUM_OPORTS);
        return &outports[idx];
}

void 
w32sdk_audio_iport_set(audio_desc_t ad, audio_port_t port)
{
        char portname[MIXER_LONG_NAME_CHARS+1];
        int i, j, gain;
        UNUSED(ad);
        
        for(i = 0; i < n_input_ports; i++) {
                if (input_ports[i].port == port) {
                        /* save gain */
                        gain = mixerGetLineGain((HMIXEROBJ)hMixer, input_ports[iport].port);
                        debug_msg("Gain %d\n", gain);
                        if (mixerGetLineName((HMIXEROBJ)hMixer, input_ports[i].port, portname, MIXER_LONG_NAME_CHARS)) {
                                mixerEnableInputLine((HMIXEROBJ)hMixer, portname);
                        }
                        mixerSetLineGain((HMIXEROBJ)hMixer, input_ports[i].port, gain);
                        
                        /* Do loopback */
                        for(j = 0; j < n_loop_ports && nLoopGain != 0; j++) {
                                if (strcmp(loop_ports[j].name, input_ports[i].name) == 0) {
                                        mixerEnableOutputLine((HMIXEROBJ)hMixer, loop_ports[j].port, 1);
                                        /* mixerSetLineGain((HMIXEROBJ)hMixer, loop_ports[j].port, nLoopGain); */
                                }
                        }
                        iport = i;
                        return;
                }
        }
        debug_msg("Port %d not found\n", port);
}

/* Return selected input port */
audio_port_t
w32sdk_audio_iport_get(audio_desc_t ad)
{
        UNUSED(ad);
        return input_ports[iport].port;
}

int
w32sdk_audio_iport_count(audio_desc_t ad)
{
        UNUSED(ad);
        return n_input_ports;
}

const audio_port_details_t*
w32sdk_audio_iport_details(audio_desc_t ad, int idx)
{
        UNUSED(ad);
        assert(idx >= 0 && idx < n_input_ports);
        return &input_ports[idx];
}

void
w32sdk_audio_set_igain(audio_desc_t ad, int level)
{
        UNUSED(ad);
        assert(iport >= 0 && iport < n_input_ports);
        mixerSetLineGain((HMIXEROBJ)hMixer, input_ports[iport].port, level);
}

int
w32sdk_audio_get_igain(audio_desc_t ad)
{
        UNUSED(ad);
        assert(iport >= 0 && iport < n_input_ports);
        return mixerGetLineGain((HMIXEROBJ)hMixer, input_ports[iport].port);
}

/* Probing support */

static audio_format af_sup[W32SDK_MAX_DEVICES][10];
static int          n_af_sup[W32SDK_MAX_DEVICES];

int
w32sdk_probe_format(int rate, int channels)
{
        WAVEFORMATEX wfx;
        
        wfx.cbSize = 0; /* PCM format */
        wfx.wFormatTag      = WAVE_FORMAT_PCM;
        wfx.wBitsPerSample  = 16; /* 16 bit linear */
        wfx.nChannels       = channels;
        wfx.nSamplesPerSec  = rate;
        wfx.nBlockAlign     = wfx.wBitsPerSample / 8 * wfx.nChannels;
        wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
        
        if (waveInOpen(NULL, (UINT)shWaveIn, &wfx, (UINT)NULL, (UINT)NULL, WAVE_FORMAT_QUERY)) {
                debug_msg("%d %d supported\n", rate, channels);
                return TRUE;
        }
        
        debug_msg("%d %d not supported\n", rate, channels);
        return FALSE;      
}

int 
w32sdk_probe_formats(audio_desc_t ad) 
{
        int rate, channels;

        for (rate = 8000; rate <= 48000; rate+=8000) {
                if (rate == 24000 || rate == 40000) continue;
                for(channels = 1; channels <= 2; channels++) {
                        if (w32sdk_probe_format(rate, channels)) {
                                af_sup[ad][n_af_sup[ad]].sample_rate = rate;
                                af_sup[ad][n_af_sup[ad]].channels    = channels;
                                n_af_sup[ad]++;
                        }
                }
        }
        return (n_af_sup[ad] ? TRUE : FALSE); /* Managed to find at least 1 we support    */
                                              /* We have this test since if we cannot get */
                                              /* device now (because in use elsewhere)    */
                                              /* we will want to test it later            */
}

int
w32sdk_audio_supports(audio_desc_t ad, audio_format *paf)
{
        int i;
        ad = mapAudioDescToMixerID(ad);
        for(i = 0; i < n_af_sup[ad]; i++) {
                if (af_sup[ad][i].sample_rate  == paf->sample_rate &&
                        af_sup[ad][i].channels == paf->channels) {
                        return TRUE;
                }
        }
        return FALSE;
}

static int   nMixersWithFullDuplex = 0;
static UINT *mixerIdMap;

static UINT 
mapAudioDescToMixerID(audio_desc_t ad)
{
        return mixerIdMap[ad];
}

int
w32sdk_audio_init(void)
{
        audio_format af;
        unsigned int i;

        mixerIdMap = (UINT*)xmalloc(sizeof(UINT) * mixerGetNumDevs());

        af.bits_per_sample = 16;
        af.bytes_per_block = 320;
        af.channels        = 1;
        af.encoding        = DEV_S16;
        af.sample_rate     = 8000;
        
        for(i = 0; i < mixerGetNumDevs(); i++) {
                if (w32sdk_audio_open_mixer(i, &af, &af)) {
                        w32sdk_audio_close_mixer(i);
                        mixerIdMap[nMixersWithFullDuplex] = i;
                        nMixersWithFullDuplex++;
                }
        }

        return nMixersWithFullDuplex;
}

int 
w32sdk_audio_free(void)
{
	xfree(mixerIdMap);
	return TRUE;
}

int
w32sdk_get_device_count(void)
{
        /* We are only interested in devices with mixers */
        return (int)nMixersWithFullDuplex;
}

static char tmpname[MAXPNAMELEN];

char *
w32sdk_get_device_name(int idx)
{
        MIXERCAPS mc;
        idx = mapAudioDescToMixerID(idx);
        if ((UINT)idx < mixerGetNumDevs()) {
                mixerGetDevCaps((UINT)idx, &mc, sizeof(mc));
                strncpy(tmpname, mc.szPname, MAXPNAMELEN);
                return tmpname;
        }
        return NULL;
}
#endif /* WIN32 */