File size: 156,082 Bytes
83418c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
/*
 * $Id$
 * pa_win_wmme.c
 * Implementation of PortAudio for Windows MultiMedia Extensions (WMME)
 *
 * PortAudio Portable Real-Time Audio Library
 * Latest Version at: http://www.portaudio.com
 *
 * Authors: Ross Bencina and Phil Burk
 * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * The text above constitutes the entire PortAudio license; however,
 * the PortAudio community also makes the following non-binding requests:
 *
 * Any person wishing to distribute modifications to the Software is
 * requested to send the modifications to the original developer so that
 * they can be incorporated into the canonical version. It is also
 * requested that these non-binding requests be included along with the
 * license above.
 */

/* Modification History:
 PLB = Phil Burk
 JM = Julien Maillard
 RDB = Ross Bencina
 PLB20010402 - sDevicePtrs now allocates based on sizeof(pointer)
 PLB20010413 - check for excessive numbers of channels
 PLB20010422 - apply Mike Berry's changes for CodeWarrior on PC
               including conditional inclusion of memory.h,
               and explicit typecasting on memory allocation
 PLB20010802 - use GlobalAlloc for sDevicesPtr instead of PaHost_AllocFastMemory
 PLB20010816 - pass process instead of thread to SetPriorityClass()
 PLB20010927 - use number of frames instead of real-time for CPULoad calculation.
 JM20020118 - prevent hung thread when buffers underflow.
 PLB20020321 - detect Win XP versus NT, 9x; fix DBUG typo; removed init of CurrentCount
 RDB20020411 - various renaming cleanups, factored streamData alloc and cpu usage init
 RDB20020417 - stopped counting WAVE_MAPPER when there were no real devices
               refactoring, renaming and fixed a few edge case bugs
 RDB20020531 - converted to V19 framework
 ** NOTE  maintenance history is now stored in CVS **
*/

/** @file
    @ingroup hostapi_src

    @brief Win32 host API implementation for the Windows MultiMedia Extensions (WMME) audio API.
*/

/*
    How it works:

    For both callback and blocking read/write streams we open the MME devices
    in CALLBACK_EVENT mode. In this mode, MME signals an Event object whenever
    it has finished with a buffer (either filled it for input, or played it
    for output). Where necessary, we block waiting for Event objects using
    WaitMultipleObjects().

    When implementing a PA callback stream, we set up a high priority thread
    which waits on the MME buffer Events and drains/fills the buffers when
    they are ready.

    When implementing a PA blocking read/write stream, we simply wait on these
    Events (when necessary) inside the ReadStream() and WriteStream() functions.
*/

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <windows.h>
#include <mmsystem.h>
#ifndef UNDER_CE
#include <process.h>
#endif
#include <assert.h>
/* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */
#ifndef __MWERKS__
#include <malloc.h>
#include <memory.h>
#endif /* __MWERKS__ */

#include "portaudio.h"
#include "pa_trace.h"
#include "pa_util.h"
#include "pa_allocation.h"
#include "pa_hostapi.h"
#include "pa_stream.h"
#include "pa_cpuload.h"
#include "pa_process.h"
#include "pa_debugprint.h"

#include "pa_win_wmme.h"
#include "pa_win_waveformat.h"

#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
#include "pa_win_wdmks_utils.h"
#ifndef DRV_QUERYDEVICEINTERFACE
#define DRV_QUERYDEVICEINTERFACE     (DRV_RESERVED + 12)
#endif
#ifndef DRV_QUERYDEVICEINTERFACESIZE
#define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13)
#endif
#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */

/* use CreateThread for CYGWIN, _beginthreadex for all others */
#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
#define CREATE_THREAD (HANDLE)_beginthreadex( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )
#define PA_THREAD_FUNC static unsigned WINAPI
#define PA_THREAD_ID unsigned
#else
#define CREATE_THREAD CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )
#define PA_THREAD_FUNC static DWORD WINAPI
#define PA_THREAD_ID DWORD
#endif
#if (defined(_WIN32_WCE))
#pragma comment(lib, "Coredll.lib")
#elif (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
#pragma comment(lib, "winmm.lib")
#endif

/*
 provided in newer platform sdks
 */
#ifndef DWORD_PTR
    #if defined(_WIN64)
        #define DWORD_PTR unsigned __int64
    #else
        #define DWORD_PTR unsigned long
    #endif
#endif

/************************************************* Constants ********/

#define PA_MME_USE_HIGH_DEFAULT_LATENCY_    (0)  /* For debugging glitches. */

#if PA_MME_USE_HIGH_DEFAULT_LATENCY_
    #define PA_MME_WIN_9X_DEFAULT_LATENCY_                              (0.4)
    #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_                        (4)
    #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_             (4)
    #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_             (4)
    #define PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_     (16)
    #define PA_MME_MAX_HOST_BUFFER_SECS_                                (0.3)       /* Do not exceed unless user buffer exceeds */
    #define PA_MME_MAX_HOST_BUFFER_BYTES_                               (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */
#else
    #define PA_MME_WIN_9X_DEFAULT_LATENCY_                              (0.2)
    #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_                        (2)
    #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_             (3)         /* always use at least 3 input buffers for full duplex */
    #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_             (2)
    #define PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_     (16)
    #define PA_MME_MAX_HOST_BUFFER_SECS_                                (0.1)       /* Do not exceed unless user buffer exceeds */
    #define PA_MME_MAX_HOST_BUFFER_BYTES_                               (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */
#endif

/* Use higher latency for NT because it is even worse at real-time
   operation than Win9x.
*/
#define PA_MME_WIN_NT_DEFAULT_LATENCY_                              (0.4)

/* Default low latency for WDM based systems. This is based on a rough
   survey of workable latency settings using patest_wmme_find_best_latency_params.c.
   See pdf attached to ticket 185 for a graph of the survey results:
   http://www.portaudio.com/trac/ticket/185

   Workable latencies varied between 40ms and ~80ms on different systems (different
   combinations of hardware, 32 and 64 bit, WinXP, Vista and Win7. We didn't
   get enough Vista results to know if Vista has systemically worse latency.
   For now we choose a safe value across all Windows versions here.
*/
#define PA_MME_WIN_WDM_DEFAULT_LATENCY_                             (0.090)


/* When client suggestedLatency could result in many host buffers, we aim to have around 8,
   based off Windows documentation that suggests that the kmixer uses 8 buffers. This choice
   is somewhat arbitrary here, since we haven't observed significant stability degradation
   with using either more, or less buffers.
*/
#define PA_MME_TARGET_HOST_BUFFER_COUNT_    8

#define PA_MME_MIN_TIMEOUT_MSEC_        (1000)

static const char constInputMapperSuffix_[] = " - Input";
static const char constOutputMapperSuffix_[] = " - Output";

/********************************************************************/

/* Copy null-terminated WCHAR string to explicit char string using UTF8 encoding */
static char *CopyWCharStringToUtf8CString(char *destination, size_t destLengthBytes, const WCHAR *source)
{
    /* The cbMultiByte parameter ["destLengthBytes" below] is:
    """
    Size, in bytes, of the buffer indicated by lpMultiByteStr ["destination" below].
    If this parameter is set to 0, the function returns the required buffer
    size for lpMultiByteStr and makes no use of the output parameter itself.
    """
    Source: WideCharToMultiByte at MSDN:
    http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130(v=vs.85).aspx
    */
    int intDestLengthBytes; /* cbMultiByte */
    /* intDestLengthBytes is an int, destLengthBytes is a size_t. Ensure that we don't overflow
    intDestLengthBytes by only using at most INT_MAX bytes of destination buffer.
    */
    if (destLengthBytes < INT_MAX)
    {
#pragma warning (disable : 4267) /* "conversion from 'size_t' to 'int', possible loss of data" */
        intDestLengthBytes = (int)destLengthBytes; /* destLengthBytes is guaranteed < INT_MAX here */
#pragma warning (default : 4267)
    }
    else
    {
        intDestLengthBytes = INT_MAX;
    }

    if (WideCharToMultiByte(CP_UTF8, 0, source, -1, destination, /*cbMultiByte=*/intDestLengthBytes, NULL, NULL) == 0)
        return NULL;
    return destination;
}

/* returns required length (in bytes) of destination buffer when
   converting WCHAR string to UTF8 bytes, not including the terminating null. */
static size_t WCharStringLen(const WCHAR *str)
{
    return WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
}

/********************************************************************/

typedef struct PaWinMmeStream PaWinMmeStream;     /* forward declaration */

/* prototypes for functions declared in this file */

#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */

PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

#ifdef __cplusplus
}
#endif /* __cplusplus */

static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                           PaStream** stream,
                           const PaStreamParameters *inputParameters,
                           const PaStreamParameters *outputParameters,
                           double sampleRate,
                           unsigned long framesPerBuffer,
                           PaStreamFlags streamFlags,
                           PaStreamCallback *streamCallback,
                           void *userData );
static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                                  const PaStreamParameters *inputParameters,
                                  const PaStreamParameters *outputParameters,
                                  double sampleRate );
static PaError CloseStream( PaStream* stream );
static PaError StartStream( PaStream *stream );
static PaError StopStream( PaStream *stream );
static PaError AbortStream( PaStream *stream );
static PaError IsStreamStopped( PaStream *s );
static PaError IsStreamActive( PaStream *stream );
static PaTime GetStreamTime( PaStream *stream );
static double GetStreamCpuLoad( PaStream* stream );
static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
static signed long GetStreamReadAvailable( PaStream* stream );
static signed long GetStreamWriteAvailable( PaStream* stream );


/* macros for setting last host error information */

#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult )                              \
    {                                                                         \
        wchar_t mmeErrorTextWide[ MAXERRORLENGTH ];                           \
        char mmeErrorText[ MAXERRORLENGTH ];                                  \
        waveInGetErrorTextW( mmresult, mmeErrorTextWide, MAXERRORLENGTH );    \
        WideCharToMultiByte( CP_UTF8, 0, mmeErrorTextWide, -1,                \
            mmeErrorText, MAXERRORLENGTH, NULL, NULL );                       \
        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );         \
    }

#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult )                             \
    {                                                                         \
        wchar_t mmeErrorTextWide[ MAXERRORLENGTH ];                           \
        char mmeErrorText[ MAXERRORLENGTH ];                                  \
        waveOutGetErrorTextW( mmresult, mmeErrorTextWide, MAXERRORLENGTH );   \
        WideCharToMultiByte( CP_UTF8, 0, mmeErrorTextWide, -1,                \
            mmeErrorText, MAXERRORLENGTH, NULL, NULL );                       \
        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );         \
    }


static void PaMme_SetLastSystemError( DWORD errorCode )
{
    char *lpMsgBuf;
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        errorCode,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0,
        NULL
    );
    PaUtil_SetLastHostErrorInfo( paMME, errorCode, lpMsgBuf );
    LocalFree( lpMsgBuf );
}

#define PA_MME_SET_LAST_SYSTEM_ERROR( errorCode ) \
    PaMme_SetLastSystemError( errorCode )


/* PaError returning wrappers for some commonly used win32 functions
    note that we allow passing a null ptr to have no effect.
*/

static PaError CreateEventWithPaError( HANDLE *handle,
        LPSECURITY_ATTRIBUTES lpEventAttributes,
        BOOL bManualReset,
        BOOL bInitialState,
        LPCTSTR lpName )
{
    PaError result = paNoError;

    *handle = NULL;

    *handle = CreateEvent( lpEventAttributes, bManualReset, bInitialState, lpName );
    if( *handle == NULL )
    {
        result = paUnanticipatedHostError;
        PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
    }

    return result;
}


static PaError ResetEventWithPaError( HANDLE handle )
{
    PaError result = paNoError;

    if( handle )
    {
        if( ResetEvent( handle ) == 0 )
        {
            result = paUnanticipatedHostError;
            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
        }
    }

    return result;
}


static PaError CloseHandleWithPaError( HANDLE handle )
{
    PaError result = paNoError;

    if( handle )
    {
        if( CloseHandle( handle ) == 0 )
        {
            result = paUnanticipatedHostError;
            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
        }
    }

    return result;
}


/* PaWinMmeHostApiRepresentation - host api datastructure specific to this implementation */

typedef struct
{
    PaUtilHostApiRepresentation inheritedHostApiRep;
    PaUtilStreamInterface callbackStreamInterface;
    PaUtilStreamInterface blockingStreamInterface;

    PaUtilAllocationGroup *allocations;

    int inputDeviceCount, outputDeviceCount;

    /** winMmeDeviceIds is an array of WinMme device ids.
        fields in the range [0, inputDeviceCount) are input device ids,
        and [inputDeviceCount, inputDeviceCount + outputDeviceCount) are output
        device ids.
     */
    UINT *winMmeDeviceIds;
}
PaWinMmeHostApiRepresentation;


typedef struct
{
    PaDeviceInfo inheritedDeviceInfo;
    DWORD dwFormats; /**<< standard formats bitmask from the WAVEINCAPS and WAVEOUTCAPS structures */
    char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
    char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
}
PaWinMmeDeviceInfo;


/*************************************************************************
 * Returns recommended device ID.
 * On the PC, the recommended device can be specified by the user by
 * setting an environment variable. For example, to use device #1.
 *
 *    set PA_RECOMMENDED_OUTPUT_DEVICE=1
 *
 * The user should first determine the available device ID by using
 * the supplied application "pa_devs".
 */
#define PA_ENV_BUF_SIZE_  (32)
#define PA_REC_IN_DEV_ENV_NAME_  ("PA_RECOMMENDED_INPUT_DEVICE")
#define PA_REC_OUT_DEV_ENV_NAME_  ("PA_RECOMMENDED_OUTPUT_DEVICE")
static PaDeviceIndex GetEnvDefaultDeviceID( char *envName )
{
    PaDeviceIndex recommendedIndex = paNoDevice;
    DWORD   hresult;
    char    envbuf[PA_ENV_BUF_SIZE_];

#ifndef WIN32_PLATFORM_PSPC /* no GetEnvironmentVariable on PocketPC */

    /* Let user determine default device by setting environment variable. */
    hresult = GetEnvironmentVariableA( envName, envbuf, PA_ENV_BUF_SIZE_ );
    if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE_) )
    {
        recommendedIndex = atoi( envbuf );
    }
#endif

    return recommendedIndex;
}


static void InitializeDefaultDeviceIdsFromEnv( PaWinMmeHostApiRepresentation *hostApi )
{
    PaDeviceIndex device;

    /* input */
    device = GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME_ );
    if( device != paNoDevice &&
            ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&
            hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxInputChannels > 0 )
    {
        hostApi->inheritedHostApiRep.info.defaultInputDevice = device;
    }

    /* output */
    device = GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME_ );
    if( device != paNoDevice &&
            ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&
            hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxOutputChannels > 0 )
    {
        hostApi->inheritedHostApiRep.info.defaultOutputDevice = device;
    }
}


/** Convert external PA ID to a windows multimedia device ID
*/
static UINT LocalDeviceIndexToWinMmeDeviceId( PaWinMmeHostApiRepresentation *hostApi, PaDeviceIndex device )
{
    assert( device >= 0 && device < hostApi->inputDeviceCount + hostApi->outputDeviceCount );

    return hostApi->winMmeDeviceIds[ device ];
}


static int SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( PaSampleFormat sampleFormat, unsigned long winMmeSpecificFlags )
{
    int waveFormatTag = 0;

    if( winMmeSpecificFlags & paWinMmeWaveFormatDolbyAc3Spdif )
        waveFormatTag = PAWIN_WAVE_FORMAT_DOLBY_AC3_SPDIF;
    else if( winMmeSpecificFlags & paWinMmeWaveFormatWmaSpdif )
        waveFormatTag = PAWIN_WAVE_FORMAT_WMA_SPDIF;
    else
        waveFormatTag = PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat );

    return waveFormatTag;
}


static PaError QueryInputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
{
    MMRESULT mmresult;

    switch( mmresult = waveInOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )
    {
        case MMSYSERR_NOERROR:
            return paNoError;
        case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */
            return paDeviceUnavailable;
        case MMSYSERR_NODRIVER:     /* No device driver is present. */
            return paDeviceUnavailable;
        case MMSYSERR_NOMEM:        /* Unable to allocate or lock memory. */
            return paInsufficientMemory;
        case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */
            return paSampleFormatNotSupported;

        case MMSYSERR_BADDEVICEID:  /* Specified device identifier is out of range. */
            /* falls through */
        default:
            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
            return paUnanticipatedHostError;
    }
}


static PaError QueryOutputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
{
    MMRESULT mmresult;

    switch( mmresult = waveOutOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )
    {
        case MMSYSERR_NOERROR:
            return paNoError;
        case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */
            return paDeviceUnavailable;
        case MMSYSERR_NODRIVER:     /* No device driver is present. */
            return paDeviceUnavailable;
        case MMSYSERR_NOMEM:        /* Unable to allocate or lock memory. */
            return paInsufficientMemory;
        case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */
            return paSampleFormatNotSupported;

        case MMSYSERR_BADDEVICEID:  /* Specified device identifier is out of range. */
            /* falls through */
        default:
            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
            return paUnanticipatedHostError;
    }
}


static PaError QueryFormatSupported( PaDeviceInfo *deviceInfo,
        PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*),
        int winMmeDeviceId, int channels, double sampleRate, unsigned long winMmeSpecificFlags )
{
    PaWinMmeDeviceInfo *winMmeDeviceInfo = (PaWinMmeDeviceInfo*)deviceInfo;
    PaWinWaveFormat waveFormat;
    PaSampleFormat sampleFormat;
    int waveFormatTag;

    /* @todo at the moment we only query with 16 bit sample format and directout speaker config*/

    sampleFormat = paInt16;
    waveFormatTag = SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( sampleFormat, winMmeSpecificFlags );

    if( waveFormatTag == PaWin_SampleFormatToLinearWaveFormatTag( paInt16 ) ){

        /* attempt bypass querying the device for linear formats */

        if( sampleRate == 11025.0
            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1M16))
                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1S16)) ) ){

            return paNoError;
        }

        if( sampleRate == 22050.0
            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2M16))
                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2S16)) ) ){

            return paNoError;
        }

        if( sampleRate == 44100.0
            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4M16))
                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4S16)) ) ){

            return paNoError;
        }
    }


    /* first, attempt to query the device using WAVEFORMATEXTENSIBLE,
       if this fails we fall back to WAVEFORMATEX */

    PaWin_InitializeWaveFormatExtensible( &waveFormat, channels, sampleFormat, waveFormatTag,
            sampleRate, PAWIN_SPEAKER_DIRECTOUT );

    if( waveFormatExQueryFunction( winMmeDeviceId, (WAVEFORMATEX*)&waveFormat ) == paNoError )
        return paNoError;

    PaWin_InitializeWaveFormatEx( &waveFormat, channels, sampleFormat, waveFormatTag, sampleRate );

    return waveFormatExQueryFunction( winMmeDeviceId, (WAVEFORMATEX*)&waveFormat );
}


#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_  (13) /* must match array length below */
static double defaultSampleRateSearchOrder_[] =
    { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,
        16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };

static void DetectDefaultSampleRate( PaWinMmeDeviceInfo *winMmeDeviceInfo, int winMmeDeviceId,
        PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*), int maxChannels )
{
    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
    int i;

    deviceInfo->defaultSampleRate = 0.;

    for( i=0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
    {
        double sampleRate = defaultSampleRateSearchOrder_[ i ];
        PaError paerror = QueryFormatSupported( deviceInfo, waveFormatExQueryFunction, winMmeDeviceId, maxChannels, sampleRate, 0 );
        if( paerror == paNoError )
        {
            deviceInfo->defaultSampleRate = sampleRate;
            break;
        }
    }
}


#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
static int QueryWaveInKSFilterMaxChannels( UINT waveInDeviceId, int *maxChannels )
{
    void *devicePath;
    DWORD devicePathSize;
    int result = 0;

    /* pass UINT ID via punned HWAVEIN, as per DRV_QUERYDEVICEINTERFACESIZE documentation */
    HWAVEIN hDeviceId = (HWAVEIN)((UINT_PTR)waveInDeviceId);

    if( waveInMessage(hDeviceId, DRV_QUERYDEVICEINTERFACESIZE,
            (DWORD_PTR)&devicePathSize, 0 ) != MMSYSERR_NOERROR )
        return 0;

    devicePath = PaUtil_AllocateMemory( devicePathSize );
    if( !devicePath )
        return 0;

    /* apparently DRV_QUERYDEVICEINTERFACE returns a unicode interface path, although this is undocumented */
    if( waveInMessage(hDeviceId, DRV_QUERYDEVICEINTERFACE,
            (DWORD_PTR)devicePath, devicePathSize ) == MMSYSERR_NOERROR )
    {
        int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( devicePath, /* isInput= */ 1  );
        if( count > 0 )
        {
            *maxChannels = count;
            result = 1;
        }
    }

    PaUtil_FreeMemory( devicePath );

    return result;
}
#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */


static PaError InitializeInputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
        PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeInputDeviceId, int *success )
{
    PaError result = paNoError;
    char *deviceName; /* non-const ptr */
    MMRESULT mmresult;
    WAVEINCAPSW wic;
    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
    size_t len;

    *success = 0;

    mmresult = waveInGetDevCapsW( winMmeInputDeviceId, &wic, sizeof( WAVEINCAPSW ) );
    if( mmresult == MMSYSERR_NOMEM )
    {
        result = paInsufficientMemory;
        goto error;
    }
    else if( mmresult != MMSYSERR_NOERROR )
    {
        /* instead of returning paUnanticipatedHostError we return
            paNoError, but leave success set as 0. This allows
            Pa_Initialize to just ignore this device, without failing
            the entire initialisation process.
        */
        return paNoError;
    }

    /* NOTE: the WAVEOUTCAPS.szPname is a null-terminated array of 32 characters,
        so we are limited to displaying only the first 31 characters of the device name. */
    if( winMmeInputDeviceId == WAVE_MAPPER )
    {
        len = WCharStringLen( wic.szPname ) + 1 + sizeof(constInputMapperSuffix_);
        /* Append I/O suffix to WAVE_MAPPER device. */
        deviceName = (char*)PaUtil_GroupAllocateMemory(
                    winMmeHostApi->allocations,
                    (long)len );
        if( !deviceName )
        {
            result = paInsufficientMemory;
            goto error;
        }
        CopyWCharStringToUtf8CString( deviceName, len, wic.szPname );
        strcat( deviceName, constInputMapperSuffix_ );
    }
    else
    {
        len = WCharStringLen( wic.szPname ) + 1;
        deviceName = (char*)PaUtil_GroupAllocateMemory(
                    winMmeHostApi->allocations,
                    (long)len );
        if( !deviceName )
        {
            result = paInsufficientMemory;
            goto error;
        }
        CopyWCharStringToUtf8CString( deviceName, len, wic.szPname  );
    }
    deviceInfo->name = deviceName;

    if( wic.wChannels == 0xFFFF || wic.wChannels < 1 || wic.wChannels > 255 ){
        /* For Windows versions using WDM (possibly Windows 98 ME and later)
         * the kernel mixer sits between the application and the driver. As a result,
         * wave*GetDevCaps often kernel mixer channel counts, which are unlimited.
         * When this happens we assume the device is stereo and set a flag
         * so that other channel counts can be tried with OpenStream -- i.e. when
         * device*ChannelCountIsKnown is false, OpenStream will try whatever
         * channel count you supply.
         * see also InitializeOutputDeviceInfo() below.
     */

        PA_DEBUG(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", wic.wChannels ));
        deviceInfo->maxInputChannels = 2;
        winMmeDeviceInfo->deviceInputChannelCountIsKnown = 0;
    }else{
        deviceInfo->maxInputChannels = wic.wChannels;
        winMmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
    }

#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
    winMmeDeviceInfo->deviceInputChannelCountIsKnown =
            QueryWaveInKSFilterMaxChannels( winMmeInputDeviceId, &deviceInfo->maxInputChannels );
#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */

    winMmeDeviceInfo->dwFormats = wic.dwFormats;

    DetectDefaultSampleRate( winMmeDeviceInfo, winMmeInputDeviceId,
            QueryInputWaveFormatEx, deviceInfo->maxInputChannels );

    *success = 1;

error:
    return result;
}


#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
static int QueryWaveOutKSFilterMaxChannels( UINT waveOutDeviceId, int *maxChannels )
{
    void *devicePath;
    DWORD devicePathSize;
    int result = 0;

    /* pass UINT ID via punned HWAVEOUT, as per DRV_QUERYDEVICEINTERFACESIZE documentation */
    HWAVEOUT hDeviceId = (HWAVEOUT)((UINT_PTR)waveOutDeviceId);

    if( waveOutMessage(hDeviceId, DRV_QUERYDEVICEINTERFACESIZE,
            (DWORD_PTR)&devicePathSize, 0 ) != MMSYSERR_NOERROR )
        return 0;

    devicePath = PaUtil_AllocateMemory( devicePathSize );
    if( !devicePath )
        return 0;

    /* apparently DRV_QUERYDEVICEINTERFACE returns a unicode interface path, although this is undocumented */
    if( waveOutMessage(hDeviceId, DRV_QUERYDEVICEINTERFACE,
            (DWORD_PTR)devicePath, devicePathSize ) == MMSYSERR_NOERROR )
    {
        int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( devicePath, /* isInput= */ 0  );
        if( count > 0 )
        {
            *maxChannels = count;
            result = 1;
        }
    }

    PaUtil_FreeMemory( devicePath );

    return result;
}
#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */


static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
        PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeOutputDeviceId, int *success )
{
    PaError result = paNoError;
    char *deviceName; /* non-const ptr */
    MMRESULT mmresult;
    WAVEOUTCAPSW woc;
    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
    size_t len;
#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
    int wdmksDeviceOutputChannelCountIsKnown;
#endif

    *success = 0;

    mmresult = waveOutGetDevCapsW( winMmeOutputDeviceId, &woc, sizeof( WAVEOUTCAPSW ) );
    if( mmresult == MMSYSERR_NOMEM )
    {
        result = paInsufficientMemory;
        goto error;
    }
    else if( mmresult != MMSYSERR_NOERROR )
    {
        /* instead of returning paUnanticipatedHostError we return
            paNoError, but leave success set as 0. This allows
            Pa_Initialize to just ignore this device, without failing
            the entire initialisation process.
        */
        return paNoError;
    }

    /* NOTE: the WAVEOUTCAPS.szPname is a null-terminated array of 32 characters,
        so we are limited to displaying only the first 31 characters of the device name. */
    if( winMmeOutputDeviceId == WAVE_MAPPER )
    {
        /* Append I/O suffix to WAVE_MAPPER device. */
        len = WCharStringLen( woc.szPname ) + 1 + sizeof(constOutputMapperSuffix_);
        deviceName = (char*)PaUtil_GroupAllocateMemory(
                    winMmeHostApi->allocations,
                    (long)len );
        if( !deviceName )
        {
            result = paInsufficientMemory;
            goto error;
        }
        CopyWCharStringToUtf8CString( deviceName, len, woc.szPname );
        strcat( deviceName, constOutputMapperSuffix_ );
    }
    else
    {
        len = WCharStringLen( woc.szPname ) + 1;
        deviceName = (char*)PaUtil_GroupAllocateMemory(
                    winMmeHostApi->allocations,
                    (long)len );
        if( !deviceName )
        {
            result = paInsufficientMemory;
            goto error;
        }
        CopyWCharStringToUtf8CString( deviceName, len, woc.szPname );
    }
    deviceInfo->name = deviceName;

    if( woc.wChannels == 0xFFFF || woc.wChannels < 1 || woc.wChannels > 255 ){
        /* For Windows versions using WDM (possibly Windows 98 ME and later)
         * the kernel mixer sits between the application and the driver. As a result,
         * wave*GetDevCaps often kernel mixer channel counts, which are unlimited.
         * When this happens we assume the device is stereo and set a flag
         * so that other channel counts can be tried with OpenStream -- i.e. when
         * device*ChannelCountIsKnown is false, OpenStream will try whatever
         * channel count you supply.
         * see also InitializeInputDeviceInfo() above.
         */

        PA_DEBUG(("Pa_GetDeviceInfo: Num output channels reported as %d! Changed to 2.\n", woc.wChannels ));
        deviceInfo->maxOutputChannels = 2;
        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 0;
    }else{
        deviceInfo->maxOutputChannels = woc.wChannels;
        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
    }

#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
    wdmksDeviceOutputChannelCountIsKnown = QueryWaveOutKSFilterMaxChannels(
            winMmeOutputDeviceId, &deviceInfo->maxOutputChannels );
    if( wdmksDeviceOutputChannelCountIsKnown && !winMmeDeviceInfo->deviceOutputChannelCountIsKnown )
        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */

    winMmeDeviceInfo->dwFormats = woc.dwFormats;

    DetectDefaultSampleRate( winMmeDeviceInfo, winMmeOutputDeviceId,
            QueryOutputWaveFormatEx, deviceInfo->maxOutputChannels );

    *success = 1;

error:
    return result;
}


static void GetDefaultLatencies( PaTime *defaultLowLatency, PaTime *defaultHighLatency )
{
/*
NOTE: GetVersionEx() is deprecated as of Windows 8.1 and can not be used to reliably detect
versions of Windows higher than Windows 8 (due to manifest requirements for reporting higher versions).
Microsoft recommends switching to VerifyVersionInfo (available on Win 2k and later), however GetVersionEx
is faster, for now we just disable the deprecation warning.
See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
See: http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
*/
#pragma warning (disable : 4996) /* use of GetVersionEx */

    OSVERSIONINFO osvi;
    osvi.dwOSVersionInfoSize = sizeof( osvi );
    GetVersionEx( &osvi );

    /* Check for NT */
    if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )
    {
        *defaultLowLatency = PA_MME_WIN_NT_DEFAULT_LATENCY_;
    }
    else if(osvi.dwMajorVersion >= 5)
    {
        *defaultLowLatency = PA_MME_WIN_WDM_DEFAULT_LATENCY_;
    }
    else
    {
        *defaultLowLatency = PA_MME_WIN_9X_DEFAULT_LATENCY_;
    }

    *defaultHighLatency = *defaultLowLatency * 2;

#pragma warning (default : 4996)
}


PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
{
    PaError result = paNoError;
    int i;
    PaWinMmeHostApiRepresentation *winMmeHostApi;
    int inputDeviceCount, outputDeviceCount, maximumPossibleDeviceCount;
    PaWinMmeDeviceInfo *deviceInfoArray;
    int deviceInfoInitializationSucceeded;
    PaTime defaultLowLatency, defaultHighLatency;
    DWORD waveInPreferredDevice, waveOutPreferredDevice;
    DWORD preferredDeviceStatusFlags;

    winMmeHostApi = (PaWinMmeHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinMmeHostApiRepresentation) );
    if( !winMmeHostApi )
    {
        result = paInsufficientMemory;
        goto error;
    }

    winMmeHostApi->allocations = PaUtil_CreateAllocationGroup();
    if( !winMmeHostApi->allocations )
    {
        result = paInsufficientMemory;
        goto error;
    }

    *hostApi = &winMmeHostApi->inheritedHostApiRep;
    (*hostApi)->info.structVersion = 1;
    (*hostApi)->info.type = paMME;
    (*hostApi)->info.name = "MME";


    /* initialise device counts and default devices under the assumption that
        there are no devices. These values are incremented below if and when
        devices are successfully initialized.
    */
    (*hostApi)->info.deviceCount = 0;
    (*hostApi)->info.defaultInputDevice = paNoDevice;
    (*hostApi)->info.defaultOutputDevice = paNoDevice;
    winMmeHostApi->inputDeviceCount = 0;
    winMmeHostApi->outputDeviceCount = 0;

#if !defined(DRVM_MAPPER_PREFERRED_GET)
/* DRVM_MAPPER_PREFERRED_GET is defined in mmddk.h but we avoid a dependency on the DDK by defining it here */
#define DRVM_MAPPER_PREFERRED_GET    (0x2000+21)
#endif

    /* the following calls assume that if wave*Message fails the preferred device parameter won't be modified */
    preferredDeviceStatusFlags = 0;
    waveInPreferredDevice = -1;
    waveInMessage( (HWAVEIN)((UINT_PTR)WAVE_MAPPER), DRVM_MAPPER_PREFERRED_GET, (DWORD_PTR)&waveInPreferredDevice, (DWORD_PTR)&preferredDeviceStatusFlags );

    preferredDeviceStatusFlags = 0;
    waveOutPreferredDevice = -1;
    waveOutMessage( (HWAVEOUT)((UINT_PTR)WAVE_MAPPER), DRVM_MAPPER_PREFERRED_GET, (DWORD_PTR)&waveOutPreferredDevice, (DWORD_PTR)&preferredDeviceStatusFlags );

    maximumPossibleDeviceCount = 0;

    inputDeviceCount = waveInGetNumDevs();
    if( inputDeviceCount > 0 )
        maximumPossibleDeviceCount += inputDeviceCount + 1;     /* assume there is a WAVE_MAPPER */

    outputDeviceCount = waveOutGetNumDevs();
    if( outputDeviceCount > 0 )
        maximumPossibleDeviceCount += outputDeviceCount + 1;    /* assume there is a WAVE_MAPPER */


    if( maximumPossibleDeviceCount > 0 ){

        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
                winMmeHostApi->allocations, sizeof(PaDeviceInfo*) * maximumPossibleDeviceCount );
        if( !(*hostApi)->deviceInfos )
        {
            result = paInsufficientMemory;
            goto error;
        }

        /* allocate all device info structs in a contiguous block */
        deviceInfoArray = (PaWinMmeDeviceInfo*)PaUtil_GroupAllocateMemory(
                winMmeHostApi->allocations, sizeof(PaWinMmeDeviceInfo) * maximumPossibleDeviceCount );
        if( !deviceInfoArray )
        {
            result = paInsufficientMemory;
            goto error;
        }

        winMmeHostApi->winMmeDeviceIds = (UINT*)PaUtil_GroupAllocateMemory(
                winMmeHostApi->allocations, sizeof(int) * maximumPossibleDeviceCount );
        if( !winMmeHostApi->winMmeDeviceIds )
        {
            result = paInsufficientMemory;
            goto error;
        }

        GetDefaultLatencies( &defaultLowLatency, &defaultHighLatency );

        if( inputDeviceCount > 0 ){
            /* -1 is the WAVE_MAPPER */
            for( i = -1; i < inputDeviceCount; ++i ){
                UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);
                PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
                PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;
                deviceInfo->structVersion = 2;
                deviceInfo->hostApi = hostApiIndex;

                deviceInfo->maxInputChannels = 0;
                wmmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
                deviceInfo->maxOutputChannels = 0;
                wmmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;

                deviceInfo->defaultLowInputLatency = defaultLowLatency;
                deviceInfo->defaultLowOutputLatency = defaultLowLatency;
                deviceInfo->defaultHighInputLatency = defaultHighLatency;
                deviceInfo->defaultHighOutputLatency = defaultHighLatency;

                result = InitializeInputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,
                        winMmeDeviceId, &deviceInfoInitializationSucceeded );
                if( result != paNoError )
                    goto error;

                if( deviceInfoInitializationSucceeded ){
                    if( (*hostApi)->info.defaultInputDevice == paNoDevice ){
                        /* if there is currently no default device, use the first one available */
                        (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;

                    }else if( winMmeDeviceId == waveInPreferredDevice ){
                        /* set the default device to the system preferred device */
                        (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
                    }

                    winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
                    (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;

                    winMmeHostApi->inputDeviceCount++;
                    (*hostApi)->info.deviceCount++;
                }
            }
        }

        if( outputDeviceCount > 0 ){
            /* -1 is the WAVE_MAPPER */
            for( i = -1; i < outputDeviceCount; ++i ){
                UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);
                PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
                PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;
                deviceInfo->structVersion = 2;
                deviceInfo->hostApi = hostApiIndex;

                deviceInfo->maxInputChannels = 0;
                wmmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
                deviceInfo->maxOutputChannels = 0;
                wmmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;

                deviceInfo->defaultLowInputLatency = defaultLowLatency;
                deviceInfo->defaultLowOutputLatency = defaultLowLatency;
                deviceInfo->defaultHighInputLatency = defaultHighLatency;
                deviceInfo->defaultHighOutputLatency = defaultHighLatency;

                result = InitializeOutputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,
                        winMmeDeviceId, &deviceInfoInitializationSucceeded );
                if( result != paNoError )
                    goto error;

                if( deviceInfoInitializationSucceeded ){
                    if( (*hostApi)->info.defaultOutputDevice == paNoDevice ){
                        /* if there is currently no default device, use the first one available */
                        (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;

                    }else if( winMmeDeviceId == waveOutPreferredDevice ){
                        /* set the default device to the system preferred device */
                        (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
                    }

                    winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
                    (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;

                    winMmeHostApi->outputDeviceCount++;
                    (*hostApi)->info.deviceCount++;
                }
            }
        }
    }

    InitializeDefaultDeviceIdsFromEnv( winMmeHostApi );

    (*hostApi)->Terminate = Terminate;
    (*hostApi)->OpenStream = OpenStream;
    (*hostApi)->IsFormatSupported = IsFormatSupported;

    PaUtil_InitializeStreamInterface( &winMmeHostApi->callbackStreamInterface, CloseStream, StartStream,
                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
                                      GetStreamTime, GetStreamCpuLoad,
                                      PaUtil_DummyRead, PaUtil_DummyWrite,
                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );

    PaUtil_InitializeStreamInterface( &winMmeHostApi->blockingStreamInterface, CloseStream, StartStream,
                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );

    return result;

error:
    if( winMmeHostApi )
    {
        if( winMmeHostApi->allocations )
        {
            PaUtil_FreeAllAllocations( winMmeHostApi->allocations );
            PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );
        }

        PaUtil_FreeMemory( winMmeHostApi );
    }

    return result;
}


static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
{
    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;

    if( winMmeHostApi->allocations )
    {
        PaUtil_FreeAllAllocations( winMmeHostApi->allocations );
        PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );
    }

    PaUtil_FreeMemory( winMmeHostApi );
}


static PaError IsInputChannelCountSupported( PaWinMmeDeviceInfo* deviceInfo, int channelCount )
{
    PaError result = paNoError;

    if( channelCount > 0
            && deviceInfo->deviceInputChannelCountIsKnown
            && channelCount > deviceInfo->inheritedDeviceInfo.maxInputChannels ){

        result = paInvalidChannelCount;
    }

    return result;
}

static PaError IsOutputChannelCountSupported( PaWinMmeDeviceInfo* deviceInfo, int channelCount )
{
    PaError result = paNoError;

    if( channelCount > 0
            && deviceInfo->deviceOutputChannelCountIsKnown
            && channelCount > deviceInfo->inheritedDeviceInfo.maxOutputChannels ){

        result = paInvalidChannelCount;
    }

    return result;
}

static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                                  const PaStreamParameters *inputParameters,
                                  const PaStreamParameters *outputParameters,
                                  double sampleRate )
{
    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
    int inputChannelCount, outputChannelCount;
    int inputMultipleDeviceChannelCount, outputMultipleDeviceChannelCount;
    PaSampleFormat inputSampleFormat, outputSampleFormat;
    PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
    UINT winMmeInputDeviceId, winMmeOutputDeviceId;
    unsigned int i;
    PaError paerror;

    /* The calls to QueryFormatSupported below are intended to detect invalid
        sample rates. If we assume that the channel count and format are OK,
        then the only thing that could fail is the sample rate. This isn't
        strictly true, but I can't think of a better way to test that the
        sample rate is valid.
    */

    if( inputParameters )
    {
        inputChannelCount = inputParameters->channelCount;
        inputSampleFormat = inputParameters->sampleFormat;
        inputStreamInfo = inputParameters->hostApiSpecificStreamInfo;

        /* all standard sample formats are supported by the buffer adapter,
             this implementation doesn't support any custom sample formats */
        if( inputSampleFormat & paCustomFormat )
            return paSampleFormatNotSupported;

        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification
                && inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )
        {
            inputMultipleDeviceChannelCount = 0;
            for( i=0; i< inputStreamInfo->deviceCount; ++i )
            {
                inputMultipleDeviceChannelCount += inputStreamInfo->devices[i].channelCount;

                inputDeviceInfo = hostApi->deviceInfos[ inputStreamInfo->devices[i].device ];

                /* check that input device can support inputChannelCount */
                if( inputStreamInfo->devices[i].channelCount < 1 )
                    return paInvalidChannelCount;

                paerror = IsInputChannelCountSupported( (PaWinMmeDeviceInfo*)inputDeviceInfo,
                        inputStreamInfo->devices[i].channelCount );
                if( paerror != paNoError )
                    return paerror;

                /* test for valid sample rate, see comment above */
                winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputStreamInfo->devices[i].device );
                paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx,
                        winMmeInputDeviceId, inputStreamInfo->devices[i].channelCount, sampleRate,
                        ((inputStreamInfo) ? inputStreamInfo->flags : 0) );
                if( paerror != paNoError )
                    return paInvalidSampleRate;
            }

            if( inputMultipleDeviceChannelCount != inputChannelCount )
                return paIncompatibleHostApiSpecificStreamInfo;
        }
        else
        {
            if( inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )
                return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the input device */

            inputDeviceInfo = hostApi->deviceInfos[ inputParameters->device ];

            /* check that input device can support inputChannelCount */
            paerror = IsInputChannelCountSupported( (PaWinMmeDeviceInfo*)inputDeviceInfo, inputChannelCount );
            if( paerror != paNoError )
                return paerror;

            /* test for valid sample rate, see comment above */
            winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputParameters->device );
            paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx,
                    winMmeInputDeviceId, inputChannelCount, sampleRate,
                    ((inputStreamInfo) ? inputStreamInfo->flags : 0) );
            if( paerror != paNoError )
                return paInvalidSampleRate;
        }
    }

    if( outputParameters )
    {
        outputChannelCount = outputParameters->channelCount;
        outputSampleFormat = outputParameters->sampleFormat;
        outputStreamInfo = outputParameters->hostApiSpecificStreamInfo;

        /* all standard sample formats are supported by the buffer adapter,
            this implementation doesn't support any custom sample formats */
        if( outputSampleFormat & paCustomFormat )
            return paSampleFormatNotSupported;

        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification
                && outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )
        {
            outputMultipleDeviceChannelCount = 0;
            for( i=0; i< outputStreamInfo->deviceCount; ++i )
            {
                outputMultipleDeviceChannelCount += outputStreamInfo->devices[i].channelCount;

                outputDeviceInfo = hostApi->deviceInfos[ outputStreamInfo->devices[i].device ];

                /* check that output device can support outputChannelCount */
                if( outputStreamInfo->devices[i].channelCount < 1 )
                    return paInvalidChannelCount;

                paerror = IsOutputChannelCountSupported( (PaWinMmeDeviceInfo*)outputDeviceInfo,
                        outputStreamInfo->devices[i].channelCount );
                if( paerror != paNoError )
                    return paerror;

                /* test for valid sample rate, see comment above */
                winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputStreamInfo->devices[i].device );
                paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx,
                        winMmeOutputDeviceId, outputStreamInfo->devices[i].channelCount, sampleRate,
                        ((outputStreamInfo) ? outputStreamInfo->flags : 0) );
                if( paerror != paNoError )
                    return paInvalidSampleRate;
            }

            if( outputMultipleDeviceChannelCount != outputChannelCount )
                return paIncompatibleHostApiSpecificStreamInfo;
        }
        else
        {
            if( outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )
                return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the output device */

            outputDeviceInfo = hostApi->deviceInfos[ outputParameters->device ];

            /* check that output device can support outputChannelCount */
            paerror = IsOutputChannelCountSupported( (PaWinMmeDeviceInfo*)outputDeviceInfo, outputChannelCount );
            if( paerror != paNoError )
                return paerror;

            /* test for valid sample rate, see comment above */
            winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputParameters->device );
            paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx,
                    winMmeOutputDeviceId, outputChannelCount, sampleRate,
                    ((outputStreamInfo) ? outputStreamInfo->flags : 0) );
            if( paerror != paNoError )
                return paInvalidSampleRate;
        }
    }

    /*
        - if a full duplex stream is requested, check that the combination
            of input and output parameters is supported

        - check that the device supports sampleRate

        for mme all we can do is test that the input and output devices
        support the requested sample rate and number of channels. we
        cannot test for full duplex compatibility.
    */

    return paFormatIsSupported;
}


static unsigned long ComputeHostBufferCountForFixedBufferSizeFrames(
        unsigned long suggestedLatencyFrames,
        unsigned long hostBufferSizeFrames,
        unsigned long minimumBufferCount )
{
    /* Calculate the number of buffers of length hostFramesPerBuffer
       that fit in suggestedLatencyFrames, rounding up to the next integer.

       The value (hostBufferSizeFrames - 1) below is to ensure the buffer count is rounded up.
    */
    unsigned long resultBufferCount = ((suggestedLatencyFrames + (hostBufferSizeFrames - 1)) / hostBufferSizeFrames);

    /* We always need one extra buffer for processing while the rest are queued/playing.
       i.e. latency is framesPerBuffer * (bufferCount - 1)
    */
    resultBufferCount += 1;

    if( resultBufferCount < minimumBufferCount ) /* clamp to minimum buffer count */
        resultBufferCount = minimumBufferCount;

    return resultBufferCount;
}


static unsigned long ComputeHostBufferSizeGivenHardUpperLimit(
        unsigned long userFramesPerBuffer,
        unsigned long absoluteMaximumBufferSizeFrames )
{
    static unsigned long primes_[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23,
            29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 0 }; /* zero terminated */

    unsigned long result = userFramesPerBuffer;
    int i;

    assert( absoluteMaximumBufferSizeFrames > 67 ); /* assume maximum is large and we're only factoring by small primes */

    /* search for the largest integer factor of userFramesPerBuffer less
       than or equal to absoluteMaximumBufferSizeFrames */

    /* repeatedly divide by smallest prime factors until a buffer size
       smaller than absoluteMaximumBufferSizeFrames is found */
    while( result > absoluteMaximumBufferSizeFrames ){

        /* search for the smallest prime factor of result */
        for( i=0; primes_[i] != 0; ++i )
        {
            unsigned long p = primes_[i];
            unsigned long divided = result / p;
            if( divided*p == result )
            {
                result = divided;
                break; /* continue with outer while loop */
            }
        }
        if( primes_[i] == 0 )
        { /* loop failed to find a prime factor, return an approximate result */
            unsigned long d = (userFramesPerBuffer + (absoluteMaximumBufferSizeFrames-1))
                    / absoluteMaximumBufferSizeFrames;
            return userFramesPerBuffer / d;
        }
    }

    return result;
}


static PaError SelectHostBufferSizeFramesAndHostBufferCount(
        unsigned long suggestedLatencyFrames,
        unsigned long userFramesPerBuffer,
        unsigned long minimumBufferCount,
        unsigned long preferredMaximumBufferSizeFrames, /* try not to exceed this. for example, don't exceed when coalescing buffers */
        unsigned long absoluteMaximumBufferSizeFrames,  /* never exceed this, a hard limit */
        unsigned long *hostBufferSizeFrames,
        unsigned long *hostBufferCount )
{
    unsigned long effectiveUserFramesPerBuffer;
    unsigned long numberOfUserBuffersPerHostBuffer;


    if( userFramesPerBuffer == paFramesPerBufferUnspecified ){

        effectiveUserFramesPerBuffer = PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_;

    }else{

        if( userFramesPerBuffer > absoluteMaximumBufferSizeFrames ){

            /* user has requested a user buffer that's larger than absoluteMaximumBufferSizeFrames.
               try to choose a buffer size that is equal or smaller than absoluteMaximumBufferSizeFrames
               but is also an integer factor of userFramesPerBuffer, so as to distribute computation evenly.
               the buffer processor will handle the block adaption between host and user buffer sizes.
               see http://www.portaudio.com/trac/ticket/189 for discussion.
            */

            effectiveUserFramesPerBuffer = ComputeHostBufferSizeGivenHardUpperLimit( userFramesPerBuffer, absoluteMaximumBufferSizeFrames );
            assert( effectiveUserFramesPerBuffer <= absoluteMaximumBufferSizeFrames );

            /* try to ensure that duration of host buffering is at least as
                large as duration of user buffer. */
            if( suggestedLatencyFrames < userFramesPerBuffer )
                suggestedLatencyFrames = userFramesPerBuffer;

        }else{

            effectiveUserFramesPerBuffer = userFramesPerBuffer;
        }
    }

    /* compute a host buffer count based on suggestedLatencyFrames and our granularity */

    *hostBufferSizeFrames = effectiveUserFramesPerBuffer;

    *hostBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
            suggestedLatencyFrames, *hostBufferSizeFrames, minimumBufferCount );

    if( *hostBufferSizeFrames >= userFramesPerBuffer )
    {
        /*
            If there are too many host buffers we would like to coalesce
            them by packing an integer number of user buffers into each host buffer.
            We try to coalesce such that hostBufferCount will lie between
            PA_MME_TARGET_HOST_BUFFER_COUNT_ and (PA_MME_TARGET_HOST_BUFFER_COUNT_*2)-1.
            We limit coalescing to avoid exceeding either absoluteMaximumBufferSizeFrames and
            preferredMaximumBufferSizeFrames.

            First, compute a coalescing factor: the number of user buffers per host buffer.
            The goal is to achieve PA_MME_TARGET_HOST_BUFFER_COUNT_ total buffer count.
            Since our latency is computed based on (*hostBufferCount - 1) we compute a
            coalescing factor based on (*hostBufferCount - 1) and (PA_MME_TARGET_HOST_BUFFER_COUNT_-1).

            The + (PA_MME_TARGET_HOST_BUFFER_COUNT_-2) term below is intended to round up.
        */
        numberOfUserBuffersPerHostBuffer = ((*hostBufferCount - 1) + (PA_MME_TARGET_HOST_BUFFER_COUNT_-2)) / (PA_MME_TARGET_HOST_BUFFER_COUNT_ - 1);

        if( numberOfUserBuffersPerHostBuffer > 1 )
        {
            unsigned long maxCoalescedBufferSizeFrames = (absoluteMaximumBufferSizeFrames < preferredMaximumBufferSizeFrames) /* minimum of our limits */
                            ? absoluteMaximumBufferSizeFrames
                            : preferredMaximumBufferSizeFrames;

            unsigned long maxUserBuffersPerHostBuffer = maxCoalescedBufferSizeFrames / effectiveUserFramesPerBuffer; /* don't coalesce more than this */

            if( numberOfUserBuffersPerHostBuffer > maxUserBuffersPerHostBuffer )
                numberOfUserBuffersPerHostBuffer = maxUserBuffersPerHostBuffer;

            *hostBufferSizeFrames = effectiveUserFramesPerBuffer * numberOfUserBuffersPerHostBuffer;

            /* recompute hostBufferCount to approximate suggestedLatencyFrames now that hostBufferSizeFrames is larger */
            *hostBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
                    suggestedLatencyFrames, *hostBufferSizeFrames, minimumBufferCount );
        }
    }

    return paNoError;
}


static PaError CalculateMaxHostSampleFrameSizeBytes(
        int channelCount,
        PaSampleFormat hostSampleFormat,
        const PaWinMmeStreamInfo *streamInfo,
        int *hostSampleFrameSizeBytes )
{
    unsigned int i;
    /* PA WMME streams may aggregate multiple WMME devices. When the stream addresses
       more than one device in a single direction, maxDeviceChannelCount is the maximum
       number of channels used by a single device.
    */
    int maxDeviceChannelCount = channelCount;
    int hostSampleSizeBytes = Pa_GetSampleSize( hostSampleFormat );
    if( hostSampleSizeBytes < 0 )
    {
        return hostSampleSizeBytes; /* the value of hostSampleSize here is an error code, not a sample size */
    }

    if( streamInfo && ( streamInfo->flags & paWinMmeUseMultipleDevices ) )
    {
        maxDeviceChannelCount = streamInfo->devices[0].channelCount;
        for( i=1; i< streamInfo->deviceCount; ++i )
        {
            if( streamInfo->devices[i].channelCount > maxDeviceChannelCount )
                maxDeviceChannelCount = streamInfo->devices[i].channelCount;
        }
    }

    *hostSampleFrameSizeBytes = hostSampleSizeBytes * maxDeviceChannelCount;

    return paNoError;
}


/* CalculateBufferSettings() fills the framesPerHostInputBuffer, hostInputBufferCount,
   framesPerHostOutputBuffer and hostOutputBufferCount parameters based on the values
   of the other parameters.
*/

static PaError CalculateBufferSettings(
        unsigned long *hostFramesPerInputBuffer, unsigned long *hostInputBufferCount,
        unsigned long *hostFramesPerOutputBuffer, unsigned long *hostOutputBufferCount,
        int inputChannelCount, PaSampleFormat hostInputSampleFormat,
        PaTime suggestedInputLatency, const PaWinMmeStreamInfo *inputStreamInfo,
        int outputChannelCount, PaSampleFormat hostOutputSampleFormat,
        PaTime suggestedOutputLatency, const PaWinMmeStreamInfo *outputStreamInfo,
        double sampleRate, unsigned long userFramesPerBuffer )
{
    PaError result = paNoError;

    if( inputChannelCount > 0 ) /* stream has input */
    {
        int hostInputFrameSizeBytes;
        result = CalculateMaxHostSampleFrameSizeBytes(
                inputChannelCount, hostInputSampleFormat, inputStreamInfo, &hostInputFrameSizeBytes );
        if( result != paNoError )
            goto error;

        if( inputStreamInfo
                && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
        {
            /* input - using low level latency parameters if provided */

            if( inputStreamInfo->bufferCount <= 0
                    || inputStreamInfo->framesPerBuffer <= 0 )
            {
                result = paIncompatibleHostApiSpecificStreamInfo;
                goto error;
            }

            *hostFramesPerInputBuffer = inputStreamInfo->framesPerBuffer;
            *hostInputBufferCount = inputStreamInfo->bufferCount;
        }
        else
        {
            /* input - not using low level latency parameters, so compute
               hostFramesPerInputBuffer and hostInputBufferCount
               based on userFramesPerBuffer and suggestedInputLatency. */

            unsigned long minimumBufferCount = (outputChannelCount > 0)
                    ? PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_
                    : PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_;

            result = SelectHostBufferSizeFramesAndHostBufferCount(
                    (unsigned long)(suggestedInputLatency * sampleRate), /* (truncate) */
                    userFramesPerBuffer,
                    minimumBufferCount,
                    (unsigned long)(PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate), /* in frames. preferred maximum */
                    (PA_MME_MAX_HOST_BUFFER_BYTES_ / hostInputFrameSizeBytes),  /* in frames. a hard limit. note truncation due to
                                                                                division is intentional here to limit max bytes */
                    hostFramesPerInputBuffer,
                    hostInputBufferCount );
            if( result != paNoError )
                goto error;
        }
    }
    else
    {
        *hostFramesPerInputBuffer = 0;
        *hostInputBufferCount = 0;
    }

    if( outputChannelCount > 0 ) /* stream has output */
    {
        if( outputStreamInfo
                && ( outputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
        {
            /* output - using low level latency parameters */

            if( outputStreamInfo->bufferCount <= 0
                    || outputStreamInfo->framesPerBuffer <= 0 )
            {
                result = paIncompatibleHostApiSpecificStreamInfo;
                goto error;
            }

            *hostFramesPerOutputBuffer = outputStreamInfo->framesPerBuffer;
            *hostOutputBufferCount = outputStreamInfo->bufferCount;

            if( inputChannelCount > 0 ) /* full duplex */
            {
                /* harmonize hostFramesPerInputBuffer and hostFramesPerOutputBuffer */

                if( *hostFramesPerInputBuffer != *hostFramesPerOutputBuffer )
                {
                    if( inputStreamInfo
                            && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
                    {
                        /* a custom StreamInfo was used for specifying both input
                            and output buffer sizes. We require that the larger buffer size
                            must be a multiple of the smaller buffer size */

                        if( *hostFramesPerInputBuffer < *hostFramesPerOutputBuffer )
                        {
                            if( *hostFramesPerOutputBuffer % *hostFramesPerInputBuffer != 0 )
                            {
                                result = paIncompatibleHostApiSpecificStreamInfo;
                                goto error;
                            }
                        }
                        else
                        {
                            assert( *hostFramesPerInputBuffer > *hostFramesPerOutputBuffer );
                            if( *hostFramesPerInputBuffer % *hostFramesPerOutputBuffer != 0 )
                            {
                                result = paIncompatibleHostApiSpecificStreamInfo;
                                goto error;
                            }
                        }
                    }
                    else
                    {
                        /* a custom StreamInfo was not used for specifying the input buffer size,
                            so use the output buffer size, and approximately the suggested input latency. */

                        *hostFramesPerInputBuffer = *hostFramesPerOutputBuffer;

                        *hostInputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
                                (unsigned long)(suggestedInputLatency * sampleRate),
                                *hostFramesPerInputBuffer,
                                PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ );
                    }
                }
            }
        }
        else
        {
            /* output - no low level latency parameters, so compute hostFramesPerOutputBuffer and hostOutputBufferCount
                based on userFramesPerBuffer and suggestedOutputLatency. */

            int hostOutputFrameSizeBytes;
            result = CalculateMaxHostSampleFrameSizeBytes(
                    outputChannelCount, hostOutputSampleFormat, outputStreamInfo, &hostOutputFrameSizeBytes );
            if( result != paNoError )
                goto error;

            /* compute the output buffer size and count */

            result = SelectHostBufferSizeFramesAndHostBufferCount(
                    (unsigned long)(suggestedOutputLatency * sampleRate), /* (truncate) */
                    userFramesPerBuffer,
                    PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_,
                    (unsigned long)(PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate), /* in frames. preferred maximum */
                    (PA_MME_MAX_HOST_BUFFER_BYTES_ / hostOutputFrameSizeBytes), /* in frames. a hard limit. note truncation due to
                                                                                 division is intentional here to limit max bytes */
                    hostFramesPerOutputBuffer,
                    hostOutputBufferCount );
            if( result != paNoError )
                goto error;

            if( inputChannelCount > 0 ) /* full duplex */
            {
                /* harmonize hostFramesPerInputBuffer and hostFramesPerOutputBuffer */

                /* ensure that both input and output buffer sizes are the same.
                    if they don't match at this stage, choose the smallest one
                    and use that for input and output and recompute the corresponding
                    buffer count accordingly.
                */

                if( *hostFramesPerOutputBuffer != *hostFramesPerInputBuffer )
                {
                    if( hostFramesPerInputBuffer < hostFramesPerOutputBuffer )
                    {
                        *hostFramesPerOutputBuffer = *hostFramesPerInputBuffer;

                        *hostOutputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
                                (unsigned long)(suggestedOutputLatency * sampleRate),
                                *hostOutputBufferCount,
                                PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ );
                    }
                    else
                    {
                        *hostFramesPerInputBuffer = *hostFramesPerOutputBuffer;

                        *hostInputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
                                (unsigned long)(suggestedInputLatency * sampleRate),
                                *hostFramesPerInputBuffer,
                                PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ );
                    }
                }
            }
        }
    }
    else
    {
        *hostFramesPerOutputBuffer = 0;
        *hostOutputBufferCount = 0;
    }

error:
    return result;
}


typedef struct
{
    HANDLE bufferEvent;
    void *waveHandles;
    unsigned int deviceCount;
    /* unsigned int channelCount; */
    WAVEHDR **waveHeaders;                  /* waveHeaders[device][buffer] */
    unsigned int bufferCount;
    unsigned int currentBufferIndex;
    unsigned int framesPerBuffer;
    unsigned int framesUsedInCurrentBuffer;
}PaWinMmeSingleDirectionHandlesAndBuffers;

/* prototypes for functions operating on PaWinMmeSingleDirectionHandlesAndBuffers */

static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers );
static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
        PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
        unsigned long winMmeSpecificFlags,
        unsigned long bytesPerHostSample,
        double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
        unsigned int deviceCount, PaWinWaveFormatChannelMask channelMask, int isInput );
static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError );
static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
        unsigned long hostBufferCount,
        PaSampleFormat hostSampleFormat,
        unsigned long framesPerHostBuffer,
        PaWinMmeDeviceAndChannelCount *devices,
        int isInput );
static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput );


static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
{
    handlesAndBuffers->bufferEvent = 0;
    handlesAndBuffers->waveHandles = 0;
    handlesAndBuffers->deviceCount = 0;
    handlesAndBuffers->waveHeaders = 0;
    handlesAndBuffers->bufferCount = 0;
}

static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
        PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
        unsigned long winMmeSpecificFlags,
        unsigned long bytesPerHostSample,
        double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
        unsigned int deviceCount, PaWinWaveFormatChannelMask channelMask, int isInput )
{
    PaError result;
    MMRESULT mmresult;
    signed int i, j;
    PaSampleFormat sampleFormat;
    int waveFormatTag;

    /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
        has already been called to zero some fields */

    result = CreateEventWithPaError( &handlesAndBuffers->bufferEvent, NULL, FALSE, FALSE, NULL );
    if( result != paNoError ) goto error;

    if( isInput )
        handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEIN) * deviceCount );
    else
        handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEOUT) * deviceCount );
    if( !handlesAndBuffers->waveHandles )
    {
        result = paInsufficientMemory;
        goto error;
    }

    handlesAndBuffers->deviceCount = deviceCount;

    for( i = 0; i < (signed int)deviceCount; ++i )
    {
        if( isInput )
            ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] = 0;
        else
            ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] = 0;
    }

    /* @todo at the moment we only use 16 bit sample format */
    sampleFormat = paInt16;
    waveFormatTag = SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( sampleFormat, winMmeSpecificFlags );

    for( i = 0; i < (signed int)deviceCount; ++i )
    {
        PaWinWaveFormat waveFormat;
        UINT winMmeDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, devices[i].device );

        /* @todo: consider providing a flag or #define to not try waveformat extensible
           this could just initialize j to 1 the first time round. */

        for( j = 0; j < 2; ++j )
        {
            switch(j){
                case 0:
                    /* first, attempt to open the device using WAVEFORMATEXTENSIBLE,
                        if this fails we fall back to WAVEFORMATEX */

                    PaWin_InitializeWaveFormatExtensible( &waveFormat, devices[i].channelCount,
                            sampleFormat, waveFormatTag, sampleRate, channelMask );
                    break;

                case 1:
                    /* retry with WAVEFORMATEX */

                    PaWin_InitializeWaveFormatEx( &waveFormat, devices[i].channelCount,
                            sampleFormat, waveFormatTag, sampleRate );
                    break;
            }

            /* REVIEW: consider not firing an event for input when a full duplex
                stream is being used. this would probably depend on the
                neverDropInput flag. */

            if( isInput )
            {
                mmresult = waveInOpen( &((HWAVEIN*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId,
                                    (WAVEFORMATEX*)&waveFormat,
                               (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
            }
            else
            {
                mmresult = waveOutOpen( &((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId,
                                    (WAVEFORMATEX*)&waveFormat,
                                (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
            }

            if( mmresult == MMSYSERR_NOERROR )
            {
                break; /* success */
            }
            else if( j == 0 )
            {
                continue; /* try again with WAVEFORMATEX */
            }
            else
            {
                switch( mmresult )
                {
                    case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */
                        result = paDeviceUnavailable;
                        break;
                    case MMSYSERR_NODRIVER:     /* No device driver is present. */
                        result = paDeviceUnavailable;
                        break;
                    case MMSYSERR_NOMEM:        /* Unable to allocate or lock memory. */
                        result = paInsufficientMemory;
                        break;

                    case MMSYSERR_BADDEVICEID:  /* Specified device identifier is out of range. */
                        /* falls through */

                    case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */
                                                    /* This can also occur if we try to open the device with an unsupported
                                                     * number of channels. This is attempted when device*ChannelCountIsKnown is
                                                     * set to 0.
                                                     */
                        /* falls through */
                    default:
                        result = paUnanticipatedHostError;
                        if( isInput )
                        {
                            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
                        }
                        else
                        {
                            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
                        }
                }
                goto error;
            }
        }
    }

    return result;

error:
    TerminateWaveHandles( handlesAndBuffers, isInput, 1 /* currentlyProcessingAnError */ );

    return result;
}


static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError )
{
    PaError result = paNoError;
    MMRESULT mmresult;
    signed int i;

    if( handlesAndBuffers->waveHandles )
    {
        for( i = handlesAndBuffers->deviceCount-1; i >= 0; --i )
        {
            if( isInput )
            {
                if( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] )
                    mmresult = waveInClose( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] );
                else
                    mmresult = MMSYSERR_NOERROR;
            }
            else
            {
                if( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] )
                    mmresult = waveOutClose( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] );
                else
                    mmresult = MMSYSERR_NOERROR;
            }

            if( mmresult != MMSYSERR_NOERROR &&
                !currentlyProcessingAnError ) /* don't update the error state if we're already processing an error */
            {
                result = paUnanticipatedHostError;
                if( isInput )
                {
                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
                }
                else
                {
                    PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
                }
                /* note that we don't break here, we try to continue closing devices */
            }
        }

        PaUtil_FreeMemory( handlesAndBuffers->waveHandles );
        handlesAndBuffers->waveHandles = 0;
    }

    if( handlesAndBuffers->bufferEvent )
    {
        result = CloseHandleWithPaError( handlesAndBuffers->bufferEvent );
        handlesAndBuffers->bufferEvent = 0;
    }

    return result;
}


static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
        unsigned long hostBufferCount,
        PaSampleFormat hostSampleFormat,
        unsigned long framesPerHostBuffer,
        PaWinMmeDeviceAndChannelCount *devices,
        int isInput )
{
    PaError result = paNoError;
    MMRESULT mmresult;
    WAVEHDR *deviceWaveHeaders;
    signed int i, j;

    /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
        has already been called to zero some fields */


    /* allocate an array of pointers to arrays of wave headers, one array of
        wave headers per device */
    handlesAndBuffers->waveHeaders = (WAVEHDR**)PaUtil_AllocateMemory( sizeof(WAVEHDR*) * handlesAndBuffers->deviceCount );
    if( !handlesAndBuffers->waveHeaders )
    {
        result = paInsufficientMemory;
        goto error;
    }

    for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )
        handlesAndBuffers->waveHeaders[i] = 0;

    handlesAndBuffers->bufferCount = hostBufferCount;

    for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )
    {
        int bufferBytes = Pa_GetSampleSize( hostSampleFormat ) *
                framesPerHostBuffer * devices[i].channelCount;
        if( bufferBytes < 0 )
        {
            result = paInternalError;
            goto error;
        }

        /* Allocate an array of wave headers for device i */
        deviceWaveHeaders = (WAVEHDR *) PaUtil_AllocateMemory( sizeof(WAVEHDR)*hostBufferCount );
        if( !deviceWaveHeaders )
        {
            result = paInsufficientMemory;
            goto error;
        }

        for( j=0; j < (signed int)hostBufferCount; ++j )
            deviceWaveHeaders[j].lpData = 0;

        handlesAndBuffers->waveHeaders[i] = deviceWaveHeaders;

        /* Allocate a buffer for each wave header */
        for( j=0; j < (signed int)hostBufferCount; ++j )
        {
            deviceWaveHeaders[j].lpData = (char *)PaUtil_AllocateMemory( bufferBytes );
            if( !deviceWaveHeaders[j].lpData )
            {
                result = paInsufficientMemory;
                goto error;
            }
            deviceWaveHeaders[j].dwBufferLength = bufferBytes;
            deviceWaveHeaders[j].dwUser = 0xFFFFFFFF; /* indicates that *PrepareHeader() has not yet been called, for error clean up code */

            if( isInput )
            {
                mmresult = waveInPrepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
                if( mmresult != MMSYSERR_NOERROR )
                {
                    result = paUnanticipatedHostError;
                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
                    goto error;
                }
            }
            else /* output */
            {
                mmresult = waveOutPrepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
                if( mmresult != MMSYSERR_NOERROR )
                {
                    result = paUnanticipatedHostError;
                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
                    goto error;
                }
            }
            deviceWaveHeaders[j].dwUser = devices[i].channelCount;
        }
    }

    return result;

error:
    TerminateWaveHeaders( handlesAndBuffers, isInput );

    return result;
}


static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput )
{
    signed int i, j;
    WAVEHDR *deviceWaveHeaders;

    if( handlesAndBuffers->waveHeaders )
    {
        for( i = handlesAndBuffers->deviceCount-1; i >= 0 ; --i )
        {
            deviceWaveHeaders = handlesAndBuffers->waveHeaders[i];  /* wave headers for device i */
            if( deviceWaveHeaders )
            {
                for( j = handlesAndBuffers->bufferCount-1; j >= 0; --j )
                {
                    if( deviceWaveHeaders[j].lpData )
                    {
                        if( deviceWaveHeaders[j].dwUser != 0xFFFFFFFF )
                        {
                            if( isInput )
                                waveInUnprepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
                            else
                                waveOutUnprepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
                        }

                        PaUtil_FreeMemory( deviceWaveHeaders[j].lpData );
                    }
                }

                PaUtil_FreeMemory( deviceWaveHeaders );
            }
        }

        PaUtil_FreeMemory( handlesAndBuffers->waveHeaders );
        handlesAndBuffers->waveHeaders = 0;
    }
}



/* PaWinMmeStream - a stream data structure specifically for this implementation */
/* note that struct PaWinMmeStream is typedeffed to PaWinMmeStream above. */
struct PaWinMmeStream
{
    PaUtilStreamRepresentation streamRepresentation;
    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
    PaUtilBufferProcessor bufferProcessor;

    int primeStreamUsingCallback;

    PaWinMmeSingleDirectionHandlesAndBuffers input;
    PaWinMmeSingleDirectionHandlesAndBuffers output;

    /* Processing thread management -------------- */
    HANDLE abortEvent;
    HANDLE processingThread;
    PA_THREAD_ID processingThreadId;

    char throttleProcessingThreadOnOverload;    /* 0 -> don't throttle, non-0 -> throttle */
    int processingThreadPriority;
    int highThreadPriority;
    int throttledThreadPriority;
    unsigned long throttledSleepMsecs;

    int isStopped;
    volatile int isActive;
    volatile int stopProcessing;    /* stop thread once existing buffers have been returned */
    volatile int abortProcessing;   /* stop thread immediately */

    DWORD allBuffersDurationMs;     /* used to calculate timeouts */
};

/* updates deviceCount if PaWinMmeUseMultipleDevices is used */

static PaError ValidateWinMmeSpecificStreamInfo(
        const PaStreamParameters *streamParameters,
        const PaWinMmeStreamInfo *streamInfo,
        unsigned long *winMmeSpecificFlags,
        char *throttleProcessingThreadOnOverload,
        unsigned long *deviceCount )
{
    if( streamInfo )
    {
        if( streamInfo->size != sizeof( PaWinMmeStreamInfo )
                || streamInfo->version != 1 )
        {
            return paIncompatibleHostApiSpecificStreamInfo;
        }

        *winMmeSpecificFlags = streamInfo->flags;

        if( streamInfo->flags & paWinMmeDontThrottleOverloadedProcessingThread )
            *throttleProcessingThreadOnOverload = 0;

        if( streamInfo->flags & paWinMmeUseMultipleDevices )
        {
            if( streamParameters->device != paUseHostApiSpecificDeviceSpecification )
                return paInvalidDevice;

            *deviceCount = streamInfo->deviceCount;
        }
    }

    return paNoError;
}

static PaError RetrieveDevicesFromStreamParameters(
        struct PaUtilHostApiRepresentation *hostApi,
        const PaStreamParameters *streamParameters,
        const PaWinMmeStreamInfo *streamInfo,
        PaWinMmeDeviceAndChannelCount *devices,
        unsigned long deviceCount )
{
    PaError result = paNoError;
    unsigned int i;
    int totalChannelCount;
    PaDeviceIndex hostApiDevice;

    if( streamInfo && streamInfo->flags & paWinMmeUseMultipleDevices )
    {
        totalChannelCount = 0;
        for( i=0; i < deviceCount; ++i )
        {
            /* validate that the device number is within range */
            result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice,
                            streamInfo->devices[i].device, hostApi );
            if( result != paNoError )
                return result;

            devices[i].device = hostApiDevice;
            devices[i].channelCount = streamInfo->devices[i].channelCount;

            totalChannelCount += devices[i].channelCount;
        }

        if( totalChannelCount != streamParameters->channelCount )
        {
            /* channelCount must match total channels specified by multiple devices */
            return paInvalidChannelCount; /* REVIEW use of this error code */
        }
    }
    else
    {
        devices[0].device = streamParameters->device;
        devices[0].channelCount = streamParameters->channelCount;
    }

    return result;
}

static PaError ValidateInputChannelCounts(
        struct PaUtilHostApiRepresentation *hostApi,
        PaWinMmeDeviceAndChannelCount *devices,
        unsigned long deviceCount )
{
    unsigned int i;
    PaWinMmeDeviceInfo *inputDeviceInfo;
    PaError paerror;

    for( i=0; i < deviceCount; ++i )
    {
        if( devices[i].channelCount < 1 )
            return paInvalidChannelCount;

        inputDeviceInfo =
                (PaWinMmeDeviceInfo*)hostApi->deviceInfos[ devices[i].device ];

        paerror = IsInputChannelCountSupported( inputDeviceInfo, devices[i].channelCount );
        if( paerror != paNoError )
            return paerror;
    }

    return paNoError;
}

static PaError ValidateOutputChannelCounts(
        struct PaUtilHostApiRepresentation *hostApi,
        PaWinMmeDeviceAndChannelCount *devices,
        unsigned long deviceCount )
{
    unsigned int i;
    PaWinMmeDeviceInfo *outputDeviceInfo;
    PaError paerror;

    for( i=0; i < deviceCount; ++i )
    {
        if( devices[i].channelCount < 1 )
            return paInvalidChannelCount;

        outputDeviceInfo =
                (PaWinMmeDeviceInfo*)hostApi->deviceInfos[ devices[i].device ];

        paerror = IsOutputChannelCountSupported( outputDeviceInfo, devices[i].channelCount );
        if( paerror != paNoError )
            return paerror;
    }

    return paNoError;
}


/* the following macros are intended to improve the readability of the following code */
#define PA_IS_INPUT_STREAM_( stream ) ( stream ->input.waveHandles )
#define PA_IS_OUTPUT_STREAM_( stream ) ( stream ->output.waveHandles )
#define PA_IS_FULL_DUPLEX_STREAM_( stream ) ( stream ->input.waveHandles && stream ->output.waveHandles )
#define PA_IS_HALF_DUPLEX_STREAM_( stream ) ( !(stream ->input.waveHandles && stream ->output.waveHandles) )

static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                           PaStream** s,
                           const PaStreamParameters *inputParameters,
                           const PaStreamParameters *outputParameters,
                           double sampleRate,
                           unsigned long framesPerBuffer,
                           PaStreamFlags streamFlags,
                           PaStreamCallback *streamCallback,
                           void *userData )
{
    PaError result;
    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
    PaWinMmeStream *stream = 0;
    int bufferProcessorIsInitialized = 0;
    int streamRepresentationIsInitialized = 0;
    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
    int inputChannelCount, outputChannelCount;
    PaSampleFormat inputSampleFormat, outputSampleFormat;
    double suggestedInputLatency, suggestedOutputLatency;
    PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
    PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask;
    unsigned long framesPerHostInputBuffer;
    unsigned long hostInputBufferCount;
    unsigned long framesPerHostOutputBuffer;
    unsigned long hostOutputBufferCount;
    unsigned long framesPerBufferProcessorCall;
    PaWinMmeDeviceAndChannelCount *inputDevices = 0;    /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
    unsigned long winMmeSpecificInputFlags = 0;
    unsigned long inputDeviceCount = 0;
    PaWinMmeDeviceAndChannelCount *outputDevices = 0;
    unsigned long winMmeSpecificOutputFlags = 0;
    unsigned long outputDeviceCount = 0;                /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
    char throttleProcessingThreadOnOverload = 1;


    if( inputParameters )
    {
        inputChannelCount = inputParameters->channelCount;
        inputSampleFormat = inputParameters->sampleFormat;
        suggestedInputLatency = inputParameters->suggestedLatency;

        inputDeviceCount = 1;

        /* validate input hostApiSpecificStreamInfo */
        inputStreamInfo = (PaWinMmeStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
        result = ValidateWinMmeSpecificStreamInfo( inputParameters, inputStreamInfo,
                &winMmeSpecificInputFlags,
                &throttleProcessingThreadOnOverload,
                &inputDeviceCount );
        if( result != paNoError ) return result;

        inputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * inputDeviceCount );
        if( !inputDevices ) return paInsufficientMemory;

        result = RetrieveDevicesFromStreamParameters( hostApi, inputParameters, inputStreamInfo, inputDevices, inputDeviceCount );
        if( result != paNoError ) return result;

        result = ValidateInputChannelCounts( hostApi, inputDevices, inputDeviceCount );
        if( result != paNoError ) return result;

        hostInputSampleFormat =
            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat );

        if( inputDeviceCount != 1 ){
            /* always use direct speakers when using multi-device multichannel mode */
            inputChannelMask = PAWIN_SPEAKER_DIRECTOUT;
        }
        else
        {
            if( inputStreamInfo && inputStreamInfo->flags & paWinMmeUseChannelMask )
                inputChannelMask = inputStreamInfo->channelMask;
            else
                inputChannelMask = PaWin_DefaultChannelMask( inputDevices[0].channelCount );
        }
    }
    else
    {
        inputChannelCount = 0;
        inputSampleFormat = 0;
        suggestedInputLatency = 0.;
        inputStreamInfo = 0;
        hostInputSampleFormat = 0;
    }


    if( outputParameters )
    {
        outputChannelCount = outputParameters->channelCount;
        outputSampleFormat = outputParameters->sampleFormat;
        suggestedOutputLatency = outputParameters->suggestedLatency;

        outputDeviceCount = 1;

        /* validate output hostApiSpecificStreamInfo */
        outputStreamInfo = (PaWinMmeStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
        result = ValidateWinMmeSpecificStreamInfo( outputParameters, outputStreamInfo,
                &winMmeSpecificOutputFlags,
                &throttleProcessingThreadOnOverload,
                &outputDeviceCount );
        if( result != paNoError ) return result;

        outputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * outputDeviceCount );
        if( !outputDevices ) return paInsufficientMemory;

        result = RetrieveDevicesFromStreamParameters( hostApi, outputParameters, outputStreamInfo, outputDevices, outputDeviceCount );
        if( result != paNoError ) return result;

        result = ValidateOutputChannelCounts( hostApi, outputDevices, outputDeviceCount );
        if( result != paNoError ) return result;

        hostOutputSampleFormat =
            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat );

        if( outputDeviceCount != 1 ){
            /* always use direct speakers when using multi-device multichannel mode */
            outputChannelMask = PAWIN_SPEAKER_DIRECTOUT;
        }
        else
        {
            if( outputStreamInfo && outputStreamInfo->flags & paWinMmeUseChannelMask )
                outputChannelMask = outputStreamInfo->channelMask;
            else
                outputChannelMask = PaWin_DefaultChannelMask( outputDevices[0].channelCount );
        }
    }
    else
    {
        outputChannelCount = 0;
        outputSampleFormat = 0;
        outputStreamInfo = 0;
        hostOutputSampleFormat = 0;
        suggestedOutputLatency = 0.;
    }


    /*
        IMPLEMENT ME:
            - alter sampleRate to a close allowable rate if possible / necessary
    */


    /* validate platform specific flags */
    if( (streamFlags & paPlatformSpecificFlags) != 0 )
        return paInvalidFlag; /* unexpected platform specific flag */


    /* always disable clipping and dithering if we are outputting a raw spdif stream */
    if( (winMmeSpecificOutputFlags & paWinMmeWaveFormatDolbyAc3Spdif)
            || (winMmeSpecificOutputFlags & paWinMmeWaveFormatWmaSpdif) ){

        streamFlags = streamFlags | paClipOff | paDitherOff;
    }


    result = CalculateBufferSettings( &framesPerHostInputBuffer, &hostInputBufferCount,
                &framesPerHostOutputBuffer, &hostOutputBufferCount,
                inputChannelCount, hostInputSampleFormat, suggestedInputLatency, inputStreamInfo,
                outputChannelCount, hostOutputSampleFormat, suggestedOutputLatency, outputStreamInfo,
                sampleRate, framesPerBuffer );
    if( result != paNoError ) goto error;


    stream = (PaWinMmeStream*)PaUtil_AllocateMemory( sizeof(PaWinMmeStream) );
    if( !stream )
    {
        result = paInsufficientMemory;
        goto error;
    }

    InitializeSingleDirectionHandlesAndBuffers( &stream->input );
    InitializeSingleDirectionHandlesAndBuffers( &stream->output );

    stream->abortEvent = 0;
    stream->processingThread = 0;

    stream->throttleProcessingThreadOnOverload = throttleProcessingThreadOnOverload;

    PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
                                           ( (streamCallback)
                                            ? &winMmeHostApi->callbackStreamInterface
                                            : &winMmeHostApi->blockingStreamInterface ),
                                           streamCallback, userData );
    streamRepresentationIsInitialized = 1;

    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );


    if( inputParameters && outputParameters ) /* full duplex */
    {
        if( framesPerHostInputBuffer < framesPerHostOutputBuffer )
        {
            assert( (framesPerHostOutputBuffer % framesPerHostInputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */

            framesPerBufferProcessorCall = framesPerHostInputBuffer;
        }
        else
        {
            assert( (framesPerHostInputBuffer % framesPerHostOutputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */

            framesPerBufferProcessorCall = framesPerHostOutputBuffer;
        }
    }
    else if( inputParameters )
    {
        framesPerBufferProcessorCall = framesPerHostInputBuffer;
    }
    else if( outputParameters )
    {
        framesPerBufferProcessorCall = framesPerHostOutputBuffer;
    }

    stream->input.framesPerBuffer = framesPerHostInputBuffer;
    stream->output.framesPerBuffer = framesPerHostOutputBuffer;

    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
                    inputChannelCount, inputSampleFormat, hostInputSampleFormat,
                    outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
                    sampleRate, streamFlags, framesPerBuffer,
                    framesPerBufferProcessorCall, paUtilFixedHostBufferSize,
                    streamCallback, userData );
    if( result != paNoError ) goto error;

    bufferProcessorIsInitialized = 1;

    /* stream info input latency is the minimum buffering latency (unlike suggested and default which are *maximums*) */
    stream->streamRepresentation.streamInfo.inputLatency =
            (double)(PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)
                + framesPerHostInputBuffer) / sampleRate;
    stream->streamRepresentation.streamInfo.outputLatency =
            (double)(PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)
                + (framesPerHostOutputBuffer * (hostOutputBufferCount-1))) / sampleRate;
    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;

    stream->primeStreamUsingCallback = ( (streamFlags&paPrimeOutputBuffersUsingStreamCallback) && streamCallback ) ? 1 : 0;

    /* time to sleep when throttling due to >100% cpu usage.
        -a quarter of a buffer's duration */
    stream->throttledSleepMsecs =
            (unsigned long)(stream->bufferProcessor.framesPerHostBuffer *
             stream->bufferProcessor.samplePeriod * .25 * 1000);

    stream->isStopped = 1;
    stream->isActive = 0;


    /* for maximum compatibility with multi-device multichannel drivers,
        we first open all devices, then we prepare all buffers, finally
        we start all devices ( in StartStream() ). teardown in reverse order.
    */

    if( inputParameters )
    {
        result = InitializeWaveHandles( winMmeHostApi, &stream->input,
                winMmeSpecificInputFlags,
                stream->bufferProcessor.bytesPerHostInputSample, sampleRate,
                inputDevices, inputDeviceCount, inputChannelMask, 1 /* isInput */ );
        if( result != paNoError ) goto error;
    }

    if( outputParameters )
    {
        result = InitializeWaveHandles( winMmeHostApi, &stream->output,
                winMmeSpecificOutputFlags,
                stream->bufferProcessor.bytesPerHostOutputSample, sampleRate,
                outputDevices, outputDeviceCount, outputChannelMask, 0 /* isInput */ );
        if( result != paNoError ) goto error;
    }

    if( inputParameters )
    {
        result = InitializeWaveHeaders( &stream->input, hostInputBufferCount,
                hostInputSampleFormat, framesPerHostInputBuffer, inputDevices, 1 /* isInput */ );
        if( result != paNoError ) goto error;
    }

    if( outputParameters )
    {
        result = InitializeWaveHeaders( &stream->output, hostOutputBufferCount,
                hostOutputSampleFormat, framesPerHostOutputBuffer, outputDevices, 0 /* not isInput */ );
        if( result != paNoError ) goto error;

        stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostOutputBuffer * stream->output.bufferCount) / sampleRate);
    }
    else
    {
        stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostInputBuffer * stream->input.bufferCount) / sampleRate);
    }


    if( streamCallback )
    {
        /* abort event is only needed for callback streams */
        result = CreateEventWithPaError( &stream->abortEvent, NULL, TRUE, FALSE, NULL );
        if( result != paNoError ) goto error;
    }

    *s = (PaStream*)stream;

    return result;

error:

    if( stream )
    {
        if( stream->abortEvent )
            CloseHandle( stream->abortEvent );

        TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );
        TerminateWaveHeaders( &stream->input, 1 /* isInput */ );

        TerminateWaveHandles( &stream->output, 0 /* not isInput */, 1 /* currentlyProcessingAnError */ );
        TerminateWaveHandles( &stream->input, 1 /* isInput */, 1 /* currentlyProcessingAnError */ );

        if( bufferProcessorIsInitialized )
            PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );

        if( streamRepresentationIsInitialized )
            PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );

        PaUtil_FreeMemory( stream );
    }

    return result;
}


/* return non-zero if all current buffers are done */
static int BuffersAreDone( WAVEHDR **waveHeaders, unsigned int deviceCount, int bufferIndex )
{
    unsigned int i;

    for( i=0; i < deviceCount; ++i )
    {
        if( !(waveHeaders[i][ bufferIndex ].dwFlags & WHDR_DONE) )
        {
            return 0;
        }
    }

    return 1;
}

static int CurrentInputBuffersAreDone( PaWinMmeStream *stream )
{
    return BuffersAreDone( stream->input.waveHeaders, stream->input.deviceCount, stream->input.currentBufferIndex );
}

static int CurrentOutputBuffersAreDone( PaWinMmeStream *stream )
{
    return BuffersAreDone( stream->output.waveHeaders, stream->output.deviceCount, stream->output.currentBufferIndex );
}


/* return non-zero if any buffers are queued */
static int NoBuffersAreQueued( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
{
    unsigned int i, j;

    if( handlesAndBuffers->waveHandles )
    {
        for( i=0; i < handlesAndBuffers->bufferCount; ++i )
        {
            for( j=0; j < handlesAndBuffers->deviceCount; ++j )
            {
                if( !( handlesAndBuffers->waveHeaders[ j ][ i ].dwFlags & WHDR_DONE) )
                {
                    return 0;
                }
            }
        }
    }

    return 1;
}


#define PA_CIRCULAR_INCREMENT_( current, max )\
    ( (((current) + 1) >= (max)) ? (0) : (current+1) )

#define PA_CIRCULAR_DECREMENT_( current, max )\
    ( ((current) == 0) ? ((max)-1) : (current-1) )


static signed long GetAvailableFrames( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
{
    signed long result = 0;
    unsigned int i;

    if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, handlesAndBuffers->currentBufferIndex ) )
    {
        /* we could calculate the following in O(1) if we kept track of the
            last done buffer */
        result = handlesAndBuffers->framesPerBuffer - handlesAndBuffers->framesUsedInCurrentBuffer;

        i = PA_CIRCULAR_INCREMENT_( handlesAndBuffers->currentBufferIndex, handlesAndBuffers->bufferCount );
        while( i != handlesAndBuffers->currentBufferIndex )
        {
            if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, i ) )
            {
                result += handlesAndBuffers->framesPerBuffer;
                i = PA_CIRCULAR_INCREMENT_( i, handlesAndBuffers->bufferCount );
            }
            else
                break;
        }
    }

    return result;
}


static PaError AdvanceToNextInputBuffer( PaWinMmeStream *stream )
{
    PaError result = paNoError;
    MMRESULT mmresult;
    unsigned int i;

    for( i=0; i < stream->input.deviceCount; ++i )
    {
        stream->input.waveHeaders[i][ stream->input.currentBufferIndex ].dwFlags &= ~WHDR_DONE;
        mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[i],
                                    &stream->input.waveHeaders[i][ stream->input.currentBufferIndex ],
                                    sizeof(WAVEHDR) );
        if( mmresult != MMSYSERR_NOERROR )
        {
            result = paUnanticipatedHostError;
            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
        }
    }

    stream->input.currentBufferIndex =
            PA_CIRCULAR_INCREMENT_( stream->input.currentBufferIndex, stream->input.bufferCount );

    stream->input.framesUsedInCurrentBuffer = 0;

    return result;
}


static PaError AdvanceToNextOutputBuffer( PaWinMmeStream *stream )
{
    PaError result = paNoError;
    MMRESULT mmresult;
    unsigned int i;

    for( i=0; i < stream->output.deviceCount; ++i )
    {
        mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[i],
                                 &stream->output.waveHeaders[i][ stream->output.currentBufferIndex ],
                                 sizeof(WAVEHDR) );
        if( mmresult != MMSYSERR_NOERROR )
        {
            result = paUnanticipatedHostError;
            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
        }
    }

    stream->output.currentBufferIndex =
            PA_CIRCULAR_INCREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );

    stream->output.framesUsedInCurrentBuffer = 0;

    return result;
}


/* requeue all but the most recent input with the driver. Used for catching
    up after a total input buffer underrun */
static PaError CatchUpInputBuffers( PaWinMmeStream *stream )
{
    PaError result = paNoError;
    unsigned int i;

    for( i=0; i < stream->input.bufferCount - 1; ++i )
    {
        result = AdvanceToNextInputBuffer( stream );
        if( result != paNoError )
            break;
    }

    return result;
}


/* take the most recent output and duplicate it to all other output buffers
    and requeue them. Used for catching up after a total output buffer underrun.
*/
static PaError CatchUpOutputBuffers( PaWinMmeStream *stream )
{
    PaError result = paNoError;
    unsigned int i, j;
    unsigned int previousBufferIndex =
            PA_CIRCULAR_DECREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );

    for( i=0; i < stream->output.bufferCount - 1; ++i )
    {
        for( j=0; j < stream->output.deviceCount; ++j )
        {
            if( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData
                    != stream->output.waveHeaders[j][ previousBufferIndex ].lpData )
            {
                CopyMemory( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData,
                            stream->output.waveHeaders[j][ previousBufferIndex ].lpData,
                            stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].dwBufferLength );
            }
        }

        result = AdvanceToNextOutputBuffer( stream );
        if( result != paNoError )
            break;
    }

    return result;
}


PA_THREAD_FUNC ProcessingThreadProc( void *pArg )
{
    PaWinMmeStream *stream = (PaWinMmeStream *)pArg;
    HANDLE events[3];
    int eventCount = 0;
    DWORD result = paNoError;
    DWORD waitResult;
    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
    int hostBuffersAvailable;
    signed int hostInputBufferIndex, hostOutputBufferIndex;
    PaStreamCallbackFlags statusFlags;
    int callbackResult;
    int done = 0;
    unsigned int channel, i;
    unsigned long framesProcessed;

    /* prepare event array for call to WaitForMultipleObjects() */
    if( stream->input.bufferEvent )
        events[eventCount++] = stream->input.bufferEvent;
    if( stream->output.bufferEvent )
        events[eventCount++] = stream->output.bufferEvent;
    events[eventCount++] = stream->abortEvent;

    statusFlags = 0; /** @todo support paInputUnderflow, paOutputOverflow and paNeverDropInput */

    /* loop until something causes us to stop */
    do{
        /* wait for MME to signal that a buffer is available, or for
            the PA abort event to be signaled.

          When this indicates that one or more buffers are available
          NoBuffersAreQueued() and Current*BuffersAreDone are used below to
          poll for additional done buffers. NoBuffersAreQueued() will fail
          to identify an underrun/overflow if the driver doesn't mark all done
          buffers prior to signalling the event. Some drivers do this
          (eg RME Digi96, and others don't eg VIA PC 97 input). This isn't a
          huge problem, it just means that we won't always be able to detect
          underflow/overflow.
        */
        waitResult = WaitForMultipleObjects( eventCount, events, FALSE /* wait all = FALSE */, timeout );
        if( waitResult == WAIT_FAILED )
        {
            result = paUnanticipatedHostError;
            /** @todo FIXME/REVIEW: can't return host error info from an asynchronous thread. see http://www.portaudio.com/trac/ticket/143 */
            done = 1;
        }
        else if( waitResult == WAIT_TIMEOUT )
        {
            /* if a timeout is encountered, continue */
        }

        if( stream->abortProcessing )
        {
            /* Pa_AbortStream() has been called, stop processing immediately */
            done = 1;
        }
        else if( stream->stopProcessing )
        {
            /* Pa_StopStream() has been called or the user callback returned
                non-zero, processing will continue until all output buffers
                are marked as done. The stream will stop immediately if it
                is input-only.
            */

            if( PA_IS_OUTPUT_STREAM_(stream) )
            {
                if( NoBuffersAreQueued( &stream->output ) )
                    done = 1; /* Will cause thread to return. */
            }
            else
            {
                /* input only stream */
                done = 1; /* Will cause thread to return. */
            }
        }
        else
        {
            hostBuffersAvailable = 1;

            /* process all available host buffers */
            do
            {
                hostInputBufferIndex = -1;
                hostOutputBufferIndex = -1;

                if( PA_IS_INPUT_STREAM_(stream) )
                {
                    if( CurrentInputBuffersAreDone( stream ) )
                    {
                        if( NoBuffersAreQueued( &stream->input ) )
                        {
                            /** @todo
                               if all of the other buffers are also ready then
                               we discard all but the most recent. This is an
                               input buffer overflow. FIXME: these buffers should
                               be passed to the callback in a paNeverDropInput
                               stream. http://www.portaudio.com/trac/ticket/142

                               note that it is also possible for an input overflow
                               to happen while the callback is processing a buffer.
                               that is handled further down.
                            */
                            result = CatchUpInputBuffers( stream );
                            if( result != paNoError )
                                done = 1;

                            statusFlags |= paInputOverflow;
                        }

                        hostInputBufferIndex = stream->input.currentBufferIndex;
                    }
                }

                if( PA_IS_OUTPUT_STREAM_(stream) )
                {
                    if( CurrentOutputBuffersAreDone( stream ) )
                    {
                        /* ok, we have an output buffer */

                        if( NoBuffersAreQueued( &stream->output ) )
                        {
                            /*
                            if all of the other buffers are also ready, catch up by copying
                            the most recently generated buffer into all but one of the output
                            buffers.

                            note that this catch up code only handles the case where all
                            buffers have been played out due to this thread not having
                            woken up at all. a more common case occurs when this thread
                            is woken up, processes one buffer, but takes too long, and as
                            a result all the other buffers have become un-queued. that
                            case is handled further down.
                            */

                            result = CatchUpOutputBuffers( stream );
                            if( result != paNoError )
                                done = 1;

                            statusFlags |= paOutputUnderflow;
                        }

                        hostOutputBufferIndex = stream->output.currentBufferIndex;
                    }
                }


                if( (PA_IS_FULL_DUPLEX_STREAM_(stream) && hostInputBufferIndex != -1 && hostOutputBufferIndex != -1) ||
                        (PA_IS_HALF_DUPLEX_STREAM_(stream) && ( hostInputBufferIndex != -1 || hostOutputBufferIndex != -1 ) ) )
                {
                    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */


                    if( PA_IS_OUTPUT_STREAM_(stream) )
                    {
                        /* set timeInfo.currentTime and calculate timeInfo.outputBufferDacTime
                            from the current wave out position */
                        MMTIME mmtime;
                        double timeBeforeGetPosition, timeAfterGetPosition;
                        double time;
                        long framesInBufferRing;
                        long writePosition;
                        long playbackPosition;
                        HWAVEOUT firstWaveOutDevice = ((HWAVEOUT*)stream->output.waveHandles)[0];

                        mmtime.wType = TIME_SAMPLES;
                        timeBeforeGetPosition = PaUtil_GetTime();
                        waveOutGetPosition( firstWaveOutDevice, &mmtime, sizeof(MMTIME) );
                        timeAfterGetPosition = PaUtil_GetTime();

                        timeInfo.currentTime = timeAfterGetPosition;

                        /* approximate time at which wave out position was measured
                            as half way between timeBeforeGetPosition and timeAfterGetPosition */
                        time = timeBeforeGetPosition + (timeAfterGetPosition - timeBeforeGetPosition) * .5;

                        framesInBufferRing = stream->output.bufferCount * stream->bufferProcessor.framesPerHostBuffer;
                        playbackPosition = mmtime.u.sample % framesInBufferRing;

                        writePosition = stream->output.currentBufferIndex * stream->bufferProcessor.framesPerHostBuffer
                                + stream->output.framesUsedInCurrentBuffer;

                        if( playbackPosition >= writePosition ){
                            timeInfo.outputBufferDacTime =
                                    time + ((double)( writePosition + (framesInBufferRing - playbackPosition) ) * stream->bufferProcessor.samplePeriod );
                        }else{
                            timeInfo.outputBufferDacTime =
                                    time + ((double)( writePosition - playbackPosition ) * stream->bufferProcessor.samplePeriod );
                        }
                    }


                    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );

                    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, statusFlags  );

                    /* reset status flags once they have been passed to the buffer processor */
                    statusFlags = 0;

                    if( PA_IS_INPUT_STREAM_(stream) )
                    {
                        PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );

                        channel = 0;
                        for( i=0; i<stream->input.deviceCount; ++i )
                        {
                             /* we have stored the number of channels in the buffer in dwUser */
                            int channelCount = (int)stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;

                            PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
                                    stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
                                        stream->input.framesUsedInCurrentBuffer * channelCount *
                                        stream->bufferProcessor.bytesPerHostInputSample,
                                    channelCount );


                            channel += channelCount;
                        }
                    }

                    if( PA_IS_OUTPUT_STREAM_(stream) )
                    {
                        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );

                        channel = 0;
                        for( i=0; i<stream->output.deviceCount; ++i )
                        {
                            /* we have stored the number of channels in the buffer in dwUser */
                            int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;

                            PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
                                    stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
                                        stream->output.framesUsedInCurrentBuffer * channelCount *
                                        stream->bufferProcessor.bytesPerHostOutputSample,
                                    channelCount );

                            channel += channelCount;
                        }
                    }

                    callbackResult = paContinue;
                    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );

                    stream->input.framesUsedInCurrentBuffer += framesProcessed;
                    stream->output.framesUsedInCurrentBuffer += framesProcessed;

                    PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );

                    if( callbackResult == paContinue )
                    {
                        /* nothing special to do */
                    }
                    else if( callbackResult == paAbort )
                    {
                        stream->abortProcessing = 1;
                        done = 1;
                        /** @todo FIXME: should probably reset the output device immediately once the callback returns paAbort
                            see: http://www.portaudio.com/trac/ticket/141
                        */
                        result = paNoError;
                    }
                    else
                    {
                        /* User callback has asked us to stop with paComplete or other non-zero value */
                        stream->stopProcessing = 1; /* stop once currently queued audio has finished */
                        result = paNoError;
                    }


                    if( PA_IS_INPUT_STREAM_(stream)
                            && stream->stopProcessing == 0 && stream->abortProcessing == 0
                            && stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )
                    {
                        if( NoBuffersAreQueued( &stream->input ) )
                        {
                            /** @todo need to handle PaNeverDropInput here where necessary */
                            result = CatchUpInputBuffers( stream );
                            if( result != paNoError )
                                done = 1;

                            statusFlags |= paInputOverflow;
                        }

                        result = AdvanceToNextInputBuffer( stream );
                        if( result != paNoError )
                            done = 1;
                    }


                    if( PA_IS_OUTPUT_STREAM_(stream) && !stream->abortProcessing )
                    {
                        if( stream->stopProcessing &&
                                stream->output.framesUsedInCurrentBuffer < stream->output.framesPerBuffer )
                        {
                            /* zero remaining samples in output output buffer and flush */

                            stream->output.framesUsedInCurrentBuffer += PaUtil_ZeroOutput( &stream->bufferProcessor,
                                    stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );

                            /* we send the entire buffer to the output devices, but we could
                                just send a partial buffer, rather than zeroing the unused
                                samples.
                            */
                        }

                        if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )
                        {
                            /* check for underflow before enquing the just-generated buffer,
                                but recover from underflow after enquing it. This ensures
                                that the most recent audio segment is repeated */
                            int outputUnderflow = NoBuffersAreQueued( &stream->output );

                            result = AdvanceToNextOutputBuffer( stream );
                            if( result != paNoError )
                                done = 1;

                            if( outputUnderflow && !done && !stream->stopProcessing )
                            {
                                /* Recover from underflow in the case where the
                                    underflow occurred while processing the buffer
                                    we just finished */

                                result = CatchUpOutputBuffers( stream );
                                if( result != paNoError )
                                    done = 1;

                                statusFlags |= paOutputUnderflow;
                            }
                        }
                    }

                    if( stream->throttleProcessingThreadOnOverload != 0 )
                    {
                        if( stream->stopProcessing || stream->abortProcessing )
                        {
                            if( stream->processingThreadPriority != stream->highThreadPriority )
                            {
                                SetThreadPriority( stream->processingThread, stream->highThreadPriority );
                                stream->processingThreadPriority = stream->highThreadPriority;
                            }
                        }
                        else if( PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ) > 1. )
                        {
                            if( stream->processingThreadPriority != stream->throttledThreadPriority )
                            {
                                SetThreadPriority( stream->processingThread, stream->throttledThreadPriority );
                                stream->processingThreadPriority = stream->throttledThreadPriority;
                            }

                            /* sleep to give other processes a go */
                            Sleep( stream->throttledSleepMsecs );
                        }
                        else
                        {
                            if( stream->processingThreadPriority != stream->highThreadPriority )
                            {
                                SetThreadPriority( stream->processingThread, stream->highThreadPriority );
                                stream->processingThreadPriority = stream->highThreadPriority;
                            }
                        }
                    }
                }
                else
                {
                    hostBuffersAvailable = 0;
                }
            }
            while( hostBuffersAvailable &&
                    stream->stopProcessing == 0 &&
                    stream->abortProcessing == 0 &&
                    !done );
        }
    }
    while( !done );

    stream->isActive = 0;

    if( stream->streamRepresentation.streamFinishedCallback != 0 )
        stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );

    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );

    return result;
}


/*
    When CloseStream() is called, the multi-api layer ensures that
    the stream has already been stopped or aborted.
*/
static PaError CloseStream( PaStream* s )
{
    PaError result;
    PaWinMmeStream *stream = (PaWinMmeStream*)s;

    result = CloseHandleWithPaError( stream->abortEvent );
    if( result != paNoError ) goto error;

    TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );
    TerminateWaveHeaders( &stream->input, 1 /* isInput */ );

    TerminateWaveHandles( &stream->output, 0 /* not isInput */, 0 /* not currentlyProcessingAnError */ );
    TerminateWaveHandles( &stream->input, 1 /* isInput */, 0 /* not currentlyProcessingAnError */ );

    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
    PaUtil_FreeMemory( stream );

error:
    /** @todo REVIEW: what is the best way to clean up a stream if an error is detected? */
    return result;
}


static PaError StartStream( PaStream *s )
{
    PaError result;
    PaWinMmeStream *stream = (PaWinMmeStream*)s;
    MMRESULT mmresult;
    unsigned int i, j;
    int callbackResult;
    unsigned int channel;
    unsigned long framesProcessed;
    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement this for stream priming */

    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );

    if( PA_IS_INPUT_STREAM_(stream) )
    {
        for( i=0; i<stream->input.bufferCount; ++i )
        {
            for( j=0; j<stream->input.deviceCount; ++j )
            {
                stream->input.waveHeaders[j][i].dwFlags &= ~WHDR_DONE;
                mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[j], &stream->input.waveHeaders[j][i], sizeof(WAVEHDR) );
                if( mmresult != MMSYSERR_NOERROR )
                {
                    result = paUnanticipatedHostError;
                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
                    goto error;
                }
            }
        }
        stream->input.currentBufferIndex = 0;
        stream->input.framesUsedInCurrentBuffer = 0;
    }

    if( PA_IS_OUTPUT_STREAM_(stream) )
    {
        for( i=0; i<stream->output.deviceCount; ++i )
        {
            if( (mmresult = waveOutPause( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )
            {
                result = paUnanticipatedHostError;
                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
                goto error;
            }
        }

        for( i=0; i<stream->output.bufferCount; ++i )
        {
            if( stream->primeStreamUsingCallback )
            {

                stream->output.framesUsedInCurrentBuffer = 0;
                do{

                    PaUtil_BeginBufferProcessing( &stream->bufferProcessor,
                            &timeInfo,
                            paPrimingOutput | ((stream->input.bufferCount > 0 ) ? paInputUnderflow : 0));

                    if( stream->input.bufferCount > 0 )
                        PaUtil_SetNoInput( &stream->bufferProcessor );

                    PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );

                    channel = 0;
                    for( j=0; j<stream->output.deviceCount; ++j )
                    {
                        /* we have stored the number of channels in the buffer in dwUser */
                        int channelCount = (int)stream->output.waveHeaders[j][i].dwUser;

                        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
                                stream->output.waveHeaders[j][i].lpData +
                                stream->output.framesUsedInCurrentBuffer * channelCount *
                                stream->bufferProcessor.bytesPerHostOutputSample,
                                channelCount );

                        /* we have stored the number of channels in the buffer in dwUser */
                        channel += channelCount;
                    }

                    callbackResult = paContinue;
                    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
                    stream->output.framesUsedInCurrentBuffer += framesProcessed;

                    if( callbackResult != paContinue )
                    {
                        /** @todo fix this, what do we do if callback result is non-zero during stream
                            priming?

                            for complete: play out primed waveHeaders as usual
                            for abort: clean up immediately.
                       */
                    }

                }while( stream->output.framesUsedInCurrentBuffer != stream->output.framesPerBuffer );

            }
            else
            {
                for( j=0; j<stream->output.deviceCount; ++j )
                {
                    ZeroMemory( stream->output.waveHeaders[j][i].lpData, stream->output.waveHeaders[j][i].dwBufferLength );
                }
            }

            /* we queue all channels of a single buffer frame (across all
                devices, because some multidevice multichannel drivers work
                better this way */
            for( j=0; j<stream->output.deviceCount; ++j )
            {
                mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[j], &stream->output.waveHeaders[j][i], sizeof(WAVEHDR) );
                if( mmresult != MMSYSERR_NOERROR )
                {
                    result = paUnanticipatedHostError;
                    PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
                    goto error;
                }
            }
        }
        stream->output.currentBufferIndex = 0;
        stream->output.framesUsedInCurrentBuffer = 0;
    }


    stream->isStopped = 0;
    stream->isActive = 1;
    stream->stopProcessing = 0;
    stream->abortProcessing = 0;

    result = ResetEventWithPaError( stream->input.bufferEvent );
    if( result != paNoError ) goto error;

    result = ResetEventWithPaError( stream->output.bufferEvent );
    if( result != paNoError ) goto error;


    if( stream->streamRepresentation.streamCallback )
    {
        /* callback stream */

        result = ResetEventWithPaError( stream->abortEvent );
        if( result != paNoError ) goto error;

        /* Create thread that waits for audio buffers to be ready for processing. */
        stream->processingThread = CREATE_THREAD;
        if( !stream->processingThread )
        {
            result = paUnanticipatedHostError;
            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
            goto error;
        }

        /** @todo could have mme specific stream parameters to allow the user
            to set the callback thread priorities */
        stream->highThreadPriority = THREAD_PRIORITY_TIME_CRITICAL;
        stream->throttledThreadPriority = THREAD_PRIORITY_NORMAL;

        if( !SetThreadPriority( stream->processingThread, stream->highThreadPriority ) )
        {
            result = paUnanticipatedHostError;
            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
            goto error;
        }
        stream->processingThreadPriority = stream->highThreadPriority;
    }
    else
    {
        /* blocking read/write stream */

    }

    if( PA_IS_INPUT_STREAM_(stream) )
    {
        for( i=0; i < stream->input.deviceCount; ++i )
        {
            mmresult = waveInStart( ((HWAVEIN*)stream->input.waveHandles)[i] );
            PA_DEBUG(("Pa_StartStream: waveInStart returned = 0x%X.\n", mmresult));
            if( mmresult != MMSYSERR_NOERROR )
            {
                result = paUnanticipatedHostError;
                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
                goto error;
            }
        }
    }

    if( PA_IS_OUTPUT_STREAM_(stream) )
    {
        for( i=0; i < stream->output.deviceCount; ++i )
        {
            if( (mmresult = waveOutRestart( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )
            {
                result = paUnanticipatedHostError;
                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
                goto error;
            }
        }
    }

    return result;

error:
    /** @todo FIXME: implement recovery as best we can
    This should involve rolling back to a state as-if this function had never been called
    */
    return result;
}


static PaError StopStream( PaStream *s )
{
    PaError result = paNoError;
    PaWinMmeStream *stream = (PaWinMmeStream*)s;
    int timeout;
    DWORD waitResult;
    MMRESULT mmresult;
    signed int hostOutputBufferIndex;
    unsigned int channel, waitCount, i;

    /** @todo
        REVIEW: the error checking in this function needs review. the basic
        idea is to return from this function in a known state - for example
        there is no point avoiding calling waveInReset just because
        the thread times out.
    */

    if( stream->processingThread )
    {
        /* callback stream */

        /* Tell processing thread to stop generating more data and to let current data play out. */
        stream->stopProcessing = 1;

        /* Calculate timeOut longer than longest time it could take to return all buffers. */
        timeout = (int)(stream->allBuffersDurationMs * 1.5);
        if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
            timeout = PA_MME_MIN_TIMEOUT_MSEC_;

        PA_DEBUG(("WinMME StopStream: waiting for background thread.\n"));

        waitResult = WaitForSingleObject( stream->processingThread, timeout );
        if( waitResult == WAIT_TIMEOUT )
        {
            /* try to abort */
            stream->abortProcessing = 1;
            SetEvent( stream->abortEvent );
            waitResult = WaitForSingleObject( stream->processingThread, timeout );
            if( waitResult == WAIT_TIMEOUT )
            {
                PA_DEBUG(("WinMME StopStream: timed out while waiting for background thread to finish.\n"));
                result = paTimedOut;
            }
        }

        CloseHandle( stream->processingThread );
        stream->processingThread = NULL;
    }
    else
    {
        /* blocking read / write stream */

        if( PA_IS_OUTPUT_STREAM_(stream) )
        {
            if( stream->output.framesUsedInCurrentBuffer > 0 )
            {
                /* there are still unqueued frames in the current buffer, so flush them */

                hostOutputBufferIndex = stream->output.currentBufferIndex;

                PaUtil_SetOutputFrameCount( &stream->bufferProcessor,
                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );

                channel = 0;
                for( i=0; i<stream->output.deviceCount; ++i )
                {
                    /* we have stored the number of channels in the buffer in dwUser */
                    int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;

                    PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
                            stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
                                stream->output.framesUsedInCurrentBuffer * channelCount *
                                stream->bufferProcessor.bytesPerHostOutputSample,
                            channelCount );

                    channel += channelCount;
                }

                PaUtil_ZeroOutput( &stream->bufferProcessor,
                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );

                /* we send the entire buffer to the output devices, but we could
                    just send a partial buffer, rather than zeroing the unused
                    samples.
                */
                AdvanceToNextOutputBuffer( stream );
            }


            timeout = (stream->allBuffersDurationMs / stream->output.bufferCount) + 1;
            if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
                timeout = PA_MME_MIN_TIMEOUT_MSEC_;

            waitCount = 0;
            while( !NoBuffersAreQueued( &stream->output ) && waitCount <= stream->output.bufferCount )
            {
                /* wait for MME to signal that a buffer is available */
                waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );
                if( waitResult == WAIT_FAILED )
                {
                    break;
                }
                else if( waitResult == WAIT_TIMEOUT )
                {
                    /* keep waiting */
                }

                ++waitCount;
            }
        }
    }

    if( PA_IS_OUTPUT_STREAM_(stream) )
    {
        for( i =0; i < stream->output.deviceCount; ++i )
        {
            mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );
            if( mmresult != MMSYSERR_NOERROR )
            {
                result = paUnanticipatedHostError;
                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
            }
        }
    }

    if( PA_IS_INPUT_STREAM_(stream) )
    {
        for( i=0; i < stream->input.deviceCount; ++i )
        {
            mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );
            if( mmresult != MMSYSERR_NOERROR )
            {
                result = paUnanticipatedHostError;
                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
            }
        }
    }

    stream->isStopped = 1;
    stream->isActive = 0;

    return result;
}


static PaError AbortStream( PaStream *s )
{
    PaError result = paNoError;
    PaWinMmeStream *stream = (PaWinMmeStream*)s;
    int timeout;
    DWORD waitResult;
    MMRESULT mmresult;
    unsigned int i;

    /** @todo
        REVIEW: the error checking in this function needs review. the basic
        idea is to return from this function in a known state - for example
        there is no point avoiding calling waveInReset just because
        the thread times out.
    */

    if( stream->processingThread )
    {
        /* callback stream */

        /* Tell processing thread to abort immediately */
        stream->abortProcessing = 1;
        SetEvent( stream->abortEvent );
    }


    if( PA_IS_OUTPUT_STREAM_(stream) )
    {
        for( i =0; i < stream->output.deviceCount; ++i )
        {
            mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );
            if( mmresult != MMSYSERR_NOERROR )
            {
                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
                return paUnanticipatedHostError;
            }
        }
    }

    if( PA_IS_INPUT_STREAM_(stream) )
    {
        for( i=0; i < stream->input.deviceCount; ++i )
        {
            mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );
            if( mmresult != MMSYSERR_NOERROR )
            {
                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
                return paUnanticipatedHostError;
            }
        }
    }


    if( stream->processingThread )
    {
        /* callback stream */

        PA_DEBUG(("WinMME AbortStream: waiting for background thread.\n"));

        /* Calculate timeOut longer than longest time it could take to return all buffers. */
        timeout = (int)(stream->allBuffersDurationMs * 1.5);
        if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
            timeout = PA_MME_MIN_TIMEOUT_MSEC_;

        waitResult = WaitForSingleObject( stream->processingThread, timeout );
        if( waitResult == WAIT_TIMEOUT )
        {
            PA_DEBUG(("WinMME AbortStream: timed out while waiting for background thread to finish.\n"));
            return paTimedOut;
        }

        CloseHandle( stream->processingThread );
        stream->processingThread = NULL;
    }

    stream->isStopped = 1;
    stream->isActive = 0;

    return result;
}


static PaError IsStreamStopped( PaStream *s )
{
    PaWinMmeStream *stream = (PaWinMmeStream*)s;

    return stream->isStopped;
}


static PaError IsStreamActive( PaStream *s )
{
    PaWinMmeStream *stream = (PaWinMmeStream*)s;

    return stream->isActive;
}


static PaTime GetStreamTime( PaStream *s )
{
    (void) s; /* unused parameter */

    return PaUtil_GetTime();
}


static double GetStreamCpuLoad( PaStream* s )
{
    PaWinMmeStream *stream = (PaWinMmeStream*)s;

    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
}


/*
    As separate stream interfaces are used for blocking and callback
    streams, the following functions can be guaranteed to only be called
    for blocking streams.
*/

static PaError ReadStream( PaStream* s,
                           void *buffer,
                           unsigned long frames )
{
    PaError result = paNoError;
    PaWinMmeStream *stream = (PaWinMmeStream*)s;
    void *userBuffer;
    unsigned long framesRead = 0;
    unsigned long framesProcessed;
    signed int hostInputBufferIndex;
    DWORD waitResult;
    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
    unsigned int channel, i;

    if( PA_IS_INPUT_STREAM_(stream) )
    {
        /* make a local copy of the user buffer pointer(s). this is necessary
            because PaUtil_CopyInput() advances these pointers every time
            it is called.
        */
        if( stream->bufferProcessor.userInputIsInterleaved )
        {
            userBuffer = buffer;
        }
        else
        {
            userBuffer = (void*)alloca( sizeof(void*) * stream->bufferProcessor.inputChannelCount );
            if( !userBuffer )
                return paInsufficientMemory;
            for( i = 0; i<stream->bufferProcessor.inputChannelCount; ++i )
                ((void**)userBuffer)[i] = ((void**)buffer)[i];
        }

        do{
            if( CurrentInputBuffersAreDone( stream ) )
            {
                if( NoBuffersAreQueued( &stream->input ) )
                {
                    /** @todo REVIEW: consider what to do if the input overflows.
                        do we requeue all of the buffers? should we be running
                        a thread to make sure they are always queued?
                        see: http://www.portaudio.com/trac/ticket/117
                        */

                    result = paInputOverflowed;
                }

                hostInputBufferIndex = stream->input.currentBufferIndex;

                PaUtil_SetInputFrameCount( &stream->bufferProcessor,
                        stream->input.framesPerBuffer - stream->input.framesUsedInCurrentBuffer );

                channel = 0;
                for( i=0; i<stream->input.deviceCount; ++i )
                {
                    /* we have stored the number of channels in the buffer in dwUser */
                    int channelCount = (int)stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;

                    PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
                            stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
                                stream->input.framesUsedInCurrentBuffer * channelCount *
                                stream->bufferProcessor.bytesPerHostInputSample,
                            channelCount );

                    channel += channelCount;
                }

                framesProcessed = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, frames - framesRead );

                stream->input.framesUsedInCurrentBuffer += framesProcessed;
                if( stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )
                {
                    result = AdvanceToNextInputBuffer( stream );
                    if( result != paNoError )
                        break;
                }

                framesRead += framesProcessed;

            }else{
                /* wait for MME to signal that a buffer is available */
                waitResult = WaitForSingleObject( stream->input.bufferEvent, timeout );
                if( waitResult == WAIT_FAILED )
                {
                    result = paUnanticipatedHostError;
                    break;
                }
                else if( waitResult == WAIT_TIMEOUT )
                {
                    /* if a timeout is encountered, continue,
                        perhaps we should give up eventually
                    */
                }
            }
        }while( framesRead < frames );
    }
    else
    {
        result = paCanNotReadFromAnOutputOnlyStream;
    }

    return result;
}


static PaError WriteStream( PaStream* s,
                            const void *buffer,
                            unsigned long frames )
{
    PaError result = paNoError;
    PaWinMmeStream *stream = (PaWinMmeStream*)s;
    const void *userBuffer;
    unsigned long framesWritten = 0;
    unsigned long framesProcessed;
    signed int hostOutputBufferIndex;
    DWORD waitResult;
    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
    unsigned int channel, i;


    if( PA_IS_OUTPUT_STREAM_(stream) )
    {
        /* make a local copy of the user buffer pointer(s). this is necessary
            because PaUtil_CopyOutput() advances these pointers every time
            it is called.
        */
        if( stream->bufferProcessor.userOutputIsInterleaved )
        {
            userBuffer = buffer;
        }
        else
        {
            userBuffer = (const void*)alloca( sizeof(void*) * stream->bufferProcessor.outputChannelCount );
            if( !userBuffer )
                return paInsufficientMemory;
            for( i = 0; i<stream->bufferProcessor.outputChannelCount; ++i )
                ((const void**)userBuffer)[i] = ((const void**)buffer)[i];
        }

        do{
            if( CurrentOutputBuffersAreDone( stream ) )
            {
                if( NoBuffersAreQueued( &stream->output ) )
                {
                    /** @todo REVIEW: consider what to do if the output
                    underflows. do we requeue all the existing buffers with
                    zeros? should we run a separate thread to keep the buffers
                    enqueued at all times?
                    see: http://www.portaudio.com/trac/ticket/117
                    */

                    result = paOutputUnderflowed;
                }

                hostOutputBufferIndex = stream->output.currentBufferIndex;

                PaUtil_SetOutputFrameCount( &stream->bufferProcessor,
                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );

                channel = 0;
                for( i=0; i<stream->output.deviceCount; ++i )
                {
                    /* we have stored the number of channels in the buffer in dwUser */
                    int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;

                    PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
                            stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
                                stream->output.framesUsedInCurrentBuffer * channelCount *
                                stream->bufferProcessor.bytesPerHostOutputSample,
                            channelCount );

                    channel += channelCount;
                }

                framesProcessed = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames - framesWritten );

                stream->output.framesUsedInCurrentBuffer += framesProcessed;
                if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )
                {
                    result = AdvanceToNextOutputBuffer( stream );
                    if( result != paNoError )
                        break;
                }

                framesWritten += framesProcessed;
            }
            else
            {
                /* wait for MME to signal that a buffer is available */
                waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );
                if( waitResult == WAIT_FAILED )
                {
                    result = paUnanticipatedHostError;
                    break;
                }
                else if( waitResult == WAIT_TIMEOUT )
                {
                    /* if a timeout is encountered, continue,
                        perhaps we should give up eventually
                    */
                }
            }
        }while( framesWritten < frames );
    }
    else
    {
        result = paCanNotWriteToAnInputOnlyStream;
    }

    return result;
}


static signed long GetStreamReadAvailable( PaStream* s )
{
    PaWinMmeStream *stream = (PaWinMmeStream*)s;

    if( PA_IS_INPUT_STREAM_(stream) )
        return GetAvailableFrames( &stream->input );
    else
        return paCanNotReadFromAnOutputOnlyStream;
}


static signed long GetStreamWriteAvailable( PaStream* s )
{
    PaWinMmeStream *stream = (PaWinMmeStream*)s;

    if( PA_IS_OUTPUT_STREAM_(stream) )
        return GetAvailableFrames( &stream->output );
    else
        return paCanNotWriteToAnInputOnlyStream;
}


/* NOTE: the following functions are MME-stream specific, and are called directly
    by client code. We need to check for many more error conditions here because
    we don't have the benefit of pa_front.c's parameter checking.
*/

static PaError GetWinMMEStreamPointer( PaWinMmeStream **stream, PaStream *s )
{
    PaError result;
    PaUtilHostApiRepresentation *hostApi;
    PaWinMmeHostApiRepresentation *winMmeHostApi;

    result = PaUtil_ValidateStreamPointer( s );
    if( result != paNoError )
        return result;

    result = PaUtil_GetHostApiRepresentation( &hostApi, paMME );
    if( result != paNoError )
        return result;

    winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;

    /* note, the following would be easier if there was a generic way of testing
        that a stream belongs to a specific host API */

    if( PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->callbackStreamInterface
            || PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->blockingStreamInterface )
    {
        /* s is a WinMME stream */
        *stream = (PaWinMmeStream *)s;
        return paNoError;
    }
    else
    {
        return paIncompatibleStreamHostApi;
    }
}


int PaWinMME_GetStreamInputHandleCount( PaStream* s )
{
    PaWinMmeStream *stream;
    PaError result = GetWinMMEStreamPointer( &stream, s );

    if( result == paNoError )
        return (PA_IS_INPUT_STREAM_(stream)) ? stream->input.deviceCount : 0;
    else
        return result;
}


HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* s, int handleIndex )
{
    PaWinMmeStream *stream;
    PaError result = GetWinMMEStreamPointer( &stream, s );

    if( result == paNoError
            && PA_IS_INPUT_STREAM_(stream)
            && handleIndex >= 0
            && (unsigned int)handleIndex < stream->input.deviceCount )
        return ((HWAVEIN*)stream->input.waveHandles)[handleIndex];
    else
        return 0;
}


int PaWinMME_GetStreamOutputHandleCount( PaStream* s)
{
    PaWinMmeStream *stream;
    PaError result = GetWinMMEStreamPointer( &stream, s );

    if( result == paNoError )
        return (PA_IS_OUTPUT_STREAM_(stream)) ? stream->output.deviceCount : 0;
    else
        return result;
}


HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* s, int handleIndex )
{
    PaWinMmeStream *stream;
    PaError result = GetWinMMEStreamPointer( &stream, s );

    if( result == paNoError
            && PA_IS_OUTPUT_STREAM_(stream)
            && handleIndex >= 0
            && (unsigned int)handleIndex < stream->output.deviceCount )
        return ((HWAVEOUT*)stream->output.waveHandles)[handleIndex];
    else
        return 0;
}