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

#include "imagefilter.h"
#include "wiaitem.h"
#include "gphelper.h"

using namespace Gdiplus;

/*****************************************************************************
 *
 *  @func STDMETHODIMP | DoFiltering | Reads unfiltered data from input stream, cuts, deskews, rotates and filters the image data
 *                                     and then writes fitlered data to output stream.
 *
 *  @parm   LONG | lBrightness |
 *          The brightness set into the region we are filtering. Should be between -1000 and 1000
 *
 *  @parm   LONG | lContrast |
 *          The contrast set into the region we are filtering. Should be between -1000 and 1000
 *
 *  @parm   LONG | regionRotate |
 *          How much we should rotate the reion (note rotate happens after deskew!)
 *
 *  @parm   LONG | regionDeskewX |
 *          WIA_IPS_DESKEW_X for region to deskew (note 0 means no deskew)
 *
 *  @parm   LONG | regionDeskewY |
 *          WIA_IPS_DESKEW_Y for region to deskew (note 0 means no deskew)
 *
 *  @parm   IStream* | pInputStream |
 *          Unfiltered image data, either directly from driver of from WIA Preview Component
 *
 *
 *  @parm   IStream* | pOutputStream |
 *          Application stream where we write image data
 *
 *  @parm   LONG | inputXPOS |
 *          X-position of upper left corner of region to "cut-out" from image in pInputStream.
 *          Note that this parameter is relative to image in pInputStream which is not necessarily
 *          its X-position on the flatbed.
 *
 *  @parm   LONG | inputYPOS |
 *          Y-position of upper left corner of region to "cut-out" from image in pInputStream.
 *          Note that this parameter is relative to image in pInputStream which is not necessarily
 *          its Y-position on the flatbed.
 *
 *  @parm   LONG | boundingRegionWidth |
 *          Width of bounding area to "cut-out" from pInputStream. A value of 0 means that we should not perform
 *          any cutting, but instead filter the whole image.
 *          boundingRegionWidth will be set to 0 when we receive the image data from the driver since the driver
 *          will only send us the bounding rectangle of the selected region and not the entire flatbed.
 *          Note: if there is not deskewing being performed this is the "actual" width of the region.
 *
 *  @parm   LONG | boundingRegionHeight |
 *          Height of bounding area to "cut-out" from pInputStream. A value of 0 means that we should not perform
 *          any cutting, but instead filter the whole image.
 *          boundingRegionHeight will be set to 0 when we receive the image data from the driver since the driver
 *          will only send us the bounding rectangle of the selected region and not the entire flatbed.
 *          Note: if there is not deskewing being performed this is the "actual" height of the region.
 *
 *  @comm
 *  Note, our simple implementation of DoFiltering always write all the data
 *  in one chunk to the application. An actual image processing filter should
 *  be able to work on bands of data in the case where there is no rotation
 *  or deskewing being performed.
 *  This implementation also does not send callbacks (TransferCallback) messages
 *  to the application indicating progress. A "real" implementation should do that!
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXX   |
 *              The function failed
 *
 *****************************************************************************/

static HRESULT DoFiltering(
            LONG        lBrightness,
            LONG        lContrast,
            LONG        regionRotate,
            LONG        regionDeskewX,
            LONG        regionDeskewY,
    _In_    IStream     *pInputStream,
    _In_    IStream     *pOutputStream,
    _Inout_ ULONG64     *pulBytesWrittenToOutputStream,
            LONG        inputXPOS = 0,
            LONG        inputYPOS = 0,
            LONG        boundingRegionWidth = 0,
            LONG        boundingRegionHeight = 0
    )
{
    HRESULT                 hr                  = S_OK;

    Bitmap                  *pOriginalBitmap    = NULL;
    Bitmap                  *pTargetBitmap      = NULL;
    CLSID                   formatEncoder       = {0};
    GdiplusStartupInput     gdiplusStartupInput;
    ULONG_PTR               ulImageLibraryToken = 0;

    if (SUCCEEDED(hr))
    {
        hr = GDISTATUS_TO_HRESULT(GdiplusStartup(&ulImageLibraryToken, &gdiplusStartupInput, NULL));
    }

    //
    // Create a Bitmap object on the unfiltered input stream
    //
    if (SUCCEEDED(hr))
    {
#pragma prefast(suppress:__WARNING_ALIASED_MEMORY_LEAK_EXCEPTION, "Sample code only. Production code should handle exceptions.")
        pOriginalBitmap = new Bitmap(pInputStream, TRUE);

        if (pOriginalBitmap)
        {
            hr = GDISTATUS_TO_HRESULT(pOriginalBitmap->GetLastStatus());
        }
        else
        {
            hr = E_OUTOFMEMORY;
        }

        if (SUCCEEDED(hr))
        {
            hr = GDISTATUS_TO_HRESULT(GetEncoderGUIDFromImage(pOriginalBitmap, &formatEncoder));
        }
    }

    //
    // If boundingRegionWidth or boundingRegionHeight is 0, this means that we should not perform any
    // "cutting" but instead just filter the whole input image.
    //
    if (SUCCEEDED(hr))
    {
        if ((0 == boundingRegionWidth) || (0 == boundingRegionHeight))
        {
            inputXPOS = 0;
            inputYPOS = 0;
            boundingRegionWidth  = pOriginalBitmap->GetWidth();
            boundingRegionHeight = pOriginalBitmap->GetHeight();
        }
    }

    //
    // Perform filtering. This is done in 3 steps:
    // 1. Create a new bitmap with the dimensions of the final, filtered image.
    // 2. "Cut-out" and deskew final image from full image. This is done by a translate
    //    followed by a rotate transformtation.
    // 3. Apply color matrix to to perform brightness and contrast modifications.
    //
    if (SUCCEEDED(hr))
    {
        PixelFormat     originalPixelFormat = pOriginalBitmap->GetPixelFormat();

        double dblDeskewAngle        = 0.0;
        LONG   lXdelta               = 0;
        LONG   lYdelta               = 0;
        LONG   lActualRegionWidth    = 0;
        LONG   lActualRegionHeight   = 0;

        //
        // No deskew, just cut out a rectangular area!
        //
        if ((regionDeskewX) == 0 || (regionDeskewY == 0))
        {
            lActualRegionWidth  = boundingRegionWidth;
            lActualRegionHeight = boundingRegionHeight;
            dblDeskewAngle = 0.0;
        }
        else
        {
            if (regionDeskewX > regionDeskewY)
            {
                lYdelta = regionDeskewY;

                dblDeskewAngle = atan2((double)regionDeskewY, (double)regionDeskewX);

                lActualRegionWidth  = (LONG) sqrt((double) (regionDeskewX * regionDeskewX + regionDeskewY * regionDeskewY));
                lActualRegionHeight = (LONG) (((double) (boundingRegionHeight - regionDeskewY)) / cos(dblDeskewAngle));
            }
            else
            {
                lXdelta = regionDeskewX;

                dblDeskewAngle = atan2((double)regionDeskewX, (double)regionDeskewY);

                lActualRegionWidth  = (LONG) (((double) (boundingRegionWidth - regionDeskewX)) / cos(dblDeskewAngle));
                lActualRegionHeight = (LONG) sqrt((double) (regionDeskewX * regionDeskewX + regionDeskewY * regionDeskewY));

                dblDeskewAngle = -dblDeskewAngle;
            }
        }

        pTargetBitmap = new Bitmap(lActualRegionWidth, lActualRegionHeight, originalPixelFormat);

        if (pTargetBitmap)
        {
            hr = GDISTATUS_TO_HRESULT(pTargetBitmap->GetLastStatus());
        }
        else
        {
            hr = E_OUTOFMEMORY;
        }



        if (SUCCEEDED(hr))
        {
            Graphics        graphics(pTargetBitmap);
            ImageAttributes imageAttributes;

            hr = GDISTATUS_TO_HRESULT(graphics.GetLastStatus());

            if (SUCCEEDED(hr))
            {
                graphics.TranslateTransform((REAL)-(inputXPOS + lXdelta), (REAL)-(inputYPOS + lYdelta));
                hr = GDISTATUS_TO_HRESULT(graphics.GetLastStatus());
            }


            if (dblDeskewAngle != 0.0)
            {
                if (SUCCEEDED(hr))
                {
                    graphics.RotateTransform((REAL)(dblDeskewAngle * 180.0 / PI), MatrixOrderAppend);
                    hr = GDISTATUS_TO_HRESULT(graphics.GetLastStatus());
                }
            }

            if (SUCCEEDED(hr))
            {
                //
                // Calculate the values needed for the matrix
                //
                REAL scale = 0.0;
                REAL trans = 0.0;

                //
                // Normalize brightness and contrast to 0 to 1000.
                // This assumes valid settings are - 1000 to 1000.
                //
                CalculateBrightnessAndContrastParams( (lBrightness + 1000) /2, (lContrast + 1000) / 2, &scale, &trans );

                //
                // Prepare the matrix for brightness and contrast transforms
                //
                ColorMatrix brightnessAndContrast = {scale, 0,     0,     0,     0,
                                                     0,     scale, 0,     0,     0,
                                                     0,     0,     scale, 0,     0,
                                                     0,     0,     0,     1,     0,
                                                     trans, trans, trans, 0,     1};

                hr = imageAttributes.SetColorMatrix(&brightnessAndContrast);
            }

            if (SUCCEEDED(hr))
            {
                UINT    uWidth  = pOriginalBitmap->GetWidth();
                UINT    uHeight = pOriginalBitmap->GetHeight();

                Rect rect( 0, 0, uWidth, uHeight );

                hr = GDISTATUS_TO_HRESULT(graphics.DrawImage(pOriginalBitmap,rect,0,0,uWidth, uHeight,UnitPixel,&imageAttributes));
            }
        }


    }

    //
    // The last step for us to perform is rotating the region
    //
    if (SUCCEEDED(hr) && (regionRotate != PORTRAIT))
    {
        RotateFlipType  rotateFlipType;

        switch (regionRotate)
        {
            case LANSCAPE:
                rotateFlipType = Rotate270FlipNone;
                break;
            case ROT180:
                rotateFlipType = Rotate180FlipNone;
                break;
            case ROT270:
                rotateFlipType = Rotate90FlipNone;
                break;
            default:
                //
                // We should never get here!
                //
                rotateFlipType = RotateNoneFlipNone;
        }

        hr = GDISTATUS_TO_HRESULT(pTargetBitmap->RotateFlip(rotateFlipType));
    }

    //
    // The GDI+ Bitmap::Save method does not work very well for images that
    // an application displays band by band since it results in a large number
    // of small Write calls. Instead we do a LockBits to read the bits from
    // the bitmap and then write them to the application's stream.
    //
    if (SUCCEEDED(hr))
    {
        hr = WriteBitmapToStream(pTargetBitmap, pOutputStream, pulBytesWrittenToOutputStream);
    }

    if (pOriginalBitmap)
    {
        delete pOriginalBitmap;
    }

    if (pTargetBitmap)
    {
        delete pTargetBitmap;
    }

    if(ulImageLibraryToken)
    {
        GdiplusShutdown(ulImageLibraryToken);
        ulImageLibraryToken = 0;
    }

    return hr;
}


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

Routine Name:         ConvertBMPImageToRaw

Routine Description: Converts an uncompressed 24-bpp RGB BMP image Stream to a RAW Stream

Arguments:              input Stream

Return Value:           Output Stream if conversion successful
                               HRESULT (S_OK in case the operation succeeds)

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

HRESULT ConvertBMPImageToRaw(IStream * pStreamIn, IStream *pStreamOut, ULONG64 * pcbWritten = NULL)
{
    HRESULT hr = S_OK;
    ULONG ulRead = 0, ulWrite = 0;

    WIA_RAW_HEADER RawHeader = {0};

    BITMAPFILEHEADER bmfh = {0};
    BITMAPINFOHEADER bmih = {0};

    if (!pStreamIn || !pStreamOut)
    {
        hr = E_POINTER;
    }

    //
    // Seek to the beginning of Input Stream
    //
    if (SUCCEEDED(hr))
    {
        if (pcbWritten)
        {
            *pcbWritten = (ULONG64)0;
        }

        LARGE_INTEGER li = {0};
        hr = pStreamIn->Seek(li, STREAM_SEEK_SET, NULL);
    }

    //
    // Attempt to read the Bitmap File Header
    //
    if (SUCCEEDED(hr))
    {
        hr = pStreamIn->Read(&bmfh, sizeof(bmfh), &ulRead);

        if (SUCCEEDED(hr))
        {
            if (ulRead != sizeof(bmfh))
            {
                hr = E_FAIL;
            }
        }
    }

    //
    // Attempt to read the Bitmap File Header
    //
    if (SUCCEEDED(hr))
    {
        hr = pStreamIn->Read(&bmih, sizeof(bmih), &ulRead);

        if (SUCCEEDED(hr))
        {
            if (ulRead != sizeof(bmih))
            {
                hr = E_FAIL;
            }
        }
    }

    //
    // todo: check the bitmap info header and bitmap file header for validity
    //
    if (SUCCEEDED(hr))
    {
        //
        // The 'WRAW' 4 ASCII character signature is required at the begining of all WIA Raw transfers:
        //
        const char szSignature[] = "WRAW";
        memcpy(&RawHeader.Tag, szSignature, sizeof(DWORD));

        //
        // Fill in the fields describing version identity for this header:
        //
        RawHeader.Version = 0x00010000;
        RawHeader.HeaderSize = sizeof(WIA_RAW_HEADER);

        //
        // Fill in all the fields that we can retrieve directly from the current MINIDRV_TRANSFER_CONTEXT:
        //

        //
        // Resolution values must be converted to DPI (pixels per inch) from pixels per meter:
        //
        // (1" = 25.4 mm, 1 m ~ 39.37")
        //
        RawHeader.XRes = (LONG)((float)bmih.biXPelsPerMeter / 39.37f);
        RawHeader.YRes = (LONG)((float)bmih.biYPelsPerMeter / 39.37f);

        RawHeader.XExtent = bmih.biWidth;
        RawHeader.YExtent = bmih.biHeight;

        RawHeader.BytesPerLine = bmih.biWidth * 3;

        RawHeader.BitsPerPixel = bmih.biBitCount;
        RawHeader.ChannelsPerPixel = 3;
        RawHeader.DataType = WIA_DATA_RAW_RGB;

        ZeroMemory(RawHeader.BitsPerChannel, sizeof(RawHeader.BitsPerChannel));
        RawHeader.BitsPerChannel[0] = 8;
        RawHeader.BitsPerChannel[1] = 8;
        RawHeader.BitsPerChannel[2] = 8;

        RawHeader.Compression = WIA_COMPRESSION_NONE;

        RawHeader.PhotometricInterp = bmih.biSizeImage;

        RawHeader.LineOrder = WIA_LINE_ORDER_BOTTOM_TO_TOP;

        //
        // Raw data: the offset is the size of the header (we don't have a color palette in this case):
        //
        RawHeader.RawDataOffset = RawHeader.HeaderSize;
        RawHeader.RawDataSize = bmih.biSizeImage;

        RawHeader.PaletteSize = 0;
        RawHeader.PaletteOffset = 0;
    }

    //
    // Save the RawHeader: Dont Seek
    //
    if (SUCCEEDED(hr))
    {
        hr = pStreamOut->Write(&RawHeader, sizeof(RawHeader), &ulWrite);

        if (SUCCEEDED(hr))
        {
            if (pcbWritten)
            {
                (*pcbWritten)+= (ULONG64)ulWrite;
            }

            if (ulWrite != sizeof(RawHeader))
            {
                hr = E_FAIL;
            }
        }
    }

    //
    // Save the DIB data: Read from in stream and write to out stream
    //
    ULONG ulBufferSize = 100000; // approx 100 KB
    BYTE *pbImageData = NULL;
    if (SUCCEEDED(hr))
    {
        pbImageData = (BYTE *)malloc(ulBufferSize);
        if (!pbImageData)
        {
            hr = E_OUTOFMEMORY;
        }

        //
        // memory allocated. now copy
        //
        while(S_OK == hr)
        {
            hr = pStreamIn->Read(pbImageData, ulBufferSize, &ulRead);
            if (SUCCEEDED(hr))
            {
                hr = pStreamOut->Write(pbImageData, ulRead, &ulWrite);
                if (SUCCEEDED(hr))
                {
                    if (pcbWritten)
                    {
                        (*pcbWritten)+= (ULONG64)ulWrite;
                    }

                    if (ulRead != ulWrite)
                    {
                        hr = E_FAIL;
                    }
                }
            }
            if (ulRead != ulBufferSize)
            {
                break;
            }
        }
    }

    //
    // Clean-up:
    //
    if (pbImageData)
    {
        free(pbImageData);
        pbImageData = NULL;
    }

    return hr;
}


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

Routine Name:         ConvertRawImageToBMP

Routine Description: Converts an uncompressed 24-bpp RGB raw image Stream to a DIB Stream

Arguments:              input Stream

Return Value:           Output Stream if conversion successful
                               HRESULT (S_OK in case the operation succeeds)

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

HRESULT ConvertRawImageToBMP(IStream * pStreamIn, IStream **ppStreamOut, ULONG64 * pcbWritten = NULL)
{
    HRESULT hr = S_OK;
    ULONG ulRead = 0, ulWrite = 0;
    IStream *pStreamOut = NULL;

    WIA_RAW_HEADER RawHeader = {0};

    BITMAPFILEHEADER bmfh = {0};
    BITMAPINFOHEADER bmih = {0};

    if (!pStreamIn || !ppStreamOut)
    {
        hr = E_POINTER;
    }

    if (SUCCEEDED(hr))
    {
        if(pcbWritten)
        {
            *pcbWritten = (ULONG64)0;
        }

        (*ppStreamOut) = NULL;

        //
        // Seek to the beginning of Input Stream
        //
        LARGE_INTEGER li = {0};
        hr = pStreamIn->Seek(li, STREAM_SEEK_SET, NULL);
    }

    //
    // Attempt to read the WIA_RAW_HEADER:
    //
    if (SUCCEEDED(hr))
    {
        hr = pStreamIn->Read(&RawHeader, sizeof(WIA_RAW_HEADER), &ulRead);

        if (SUCCEEDED(hr))
        {
            if (ulRead != sizeof(WIA_RAW_HEADER))
            {
                hr = E_FAIL;
            }
        }
    }

    //
    // Verify the WIA raw header signature:
    //
    if (SUCCEEDED(hr))
    {
        const char szSignature[] = "WRAW";
        if (memcmp(&RawHeader.Tag, szSignature, sizeof(DWORD)))
        {
            hr = E_FAIL;
        }
    }

    //
    // Verify the WIA raw header reported size and version number:
    //
    if (SUCCEEDED(hr))
    {
        if ((0x00010000 != RawHeader.Version) || (sizeof(WIA_RAW_HEADER) != RawHeader.HeaderSize))
        {
            hr = E_FAIL;
        }
    }

    //
    // Verify if the raw image format - this sample supports only uncompressed 24-bpp RGB data:
    //
    if (SUCCEEDED(hr))
    {
        if ((WIA_COMPRESSION_NONE != RawHeader.Compression) || (24 != RawHeader.BitsPerPixel) ||
           (3 != RawHeader.ChannelsPerPixel) || (RawHeader.PaletteSize) ||
           (8 != RawHeader.BitsPerChannel[0]) || (8 != RawHeader.BitsPerChannel[1]) ||
           (8 != RawHeader.BitsPerChannel[2]))
        {
            hr = E_FAIL;
        }
    }

    //
    // Build the BITMAPFILEHEADER and the BITMAPINFOHEADER structures needed
    // to convert the raw uncompressed 24-bpp RGB image to a DIB:
    //
    if (SUCCEEDED(hr))
    {
        //
        // BITMAPFILEHEADER:
        //
        const char szBM[] = "BM";
        memcpy(&bmfh.bfType, szBM, sizeof(WORD));
        bmfh.bfSize = sizeof(BITMAPFILEHEADER);
        bmfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

        //
        // BITMAPINFOHEADER:
        //
        bmih.biSize = sizeof(BITMAPINFOHEADER);
        bmih.biWidth = RawHeader.XExtent;
        bmih.biHeight = (WIA_LINE_ORDER_BOTTOM_TO_TOP == RawHeader.LineOrder) ? ((LONG)RawHeader.YExtent) : (-(LONG)RawHeader.YExtent);
        bmih.biPlanes = 1;
        bmih.biBitCount = (WORD)RawHeader.BitsPerPixel;
        bmih.biCompression = BI_RGB;
        bmih.biSizeImage = RawHeader.RawDataSize;
        bmih.biClrUsed = 0;
        bmih.biClrImportant = 0;

        //
        // Resolution values must be converted from DPI (pixels per inch) to pixels per meter:
        //
        // (1" = 25.4 mm, 1 m ~ 39.37")
        //
        bmih.biXPelsPerMeter = (LONG)((float)RawHeader.XRes * 39.37f);
        bmih.biYPelsPerMeter = (LONG)((float)RawHeader.YRes * 39.37f);
    }

    if (SUCCEEDED(hr))
    {
        hr = CreateStreamOnHGlobal(0, TRUE, &pStreamOut);
    }

    //
    // Save the BITMAPFILEHEADER:
    //
    if (SUCCEEDED(hr))
    {
        hr = pStreamOut->Write(&bmfh, bmfh.bfSize, &ulWrite);

        if (SUCCEEDED(hr))
        {
            if (pcbWritten)
            {
                (*pcbWritten)+= (ULONG64)ulWrite;
            }
            if (ulWrite != bmfh.bfSize)
            {
                hr = E_FAIL;
            }
        }
    }

    //
    // Save the BITMAPINFOHEADER:
    //
   if (SUCCEEDED(hr))
    {
        hr = pStreamOut->Write(&bmih, bmih.biSize, &ulWrite);

        if (SUCCEEDED(hr))
        {
            if (pcbWritten)
            {
                (*pcbWritten)+= (ULONG64)ulWrite;
            }
            if (ulWrite != bmih.biSize)
            {
                hr = E_FAIL;
            }
        }
    }

    //
    // Save the DIB data: Read from in stream and write to out stream
    //
    ULONG ulBufferSize = 100000; // approx 100 KB
    BYTE *pbImageData = NULL;
    if (SUCCEEDED(hr))
    {

        pbImageData = (BYTE *)malloc(ulBufferSize);
        if (!pbImageData)
        {
            hr = E_OUTOFMEMORY;
        }

        //
        // memory allocated. now copy
        //
        while(S_OK == hr)
        {
            hr = pStreamIn->Read(pbImageData, ulBufferSize, &ulRead);
            if (SUCCEEDED(hr))
            {
                hr = pStreamOut->Write(pbImageData, ulRead, &ulWrite);
                if (SUCCEEDED(hr))
                {
                    if (pcbWritten)
                    {
                        (*pcbWritten)+= (ULONG64)ulWrite;
                    }
                    if (ulRead != ulWrite)
                    {
                        hr = E_FAIL;
                    }
                }
            }
            if (ulRead != ulBufferSize)
            {
                break;
            }
        }
    }

    //
    // Clean-up:
    //
    if (pbImageData)
    {
        free(pbImageData);
        pbImageData = NULL;
    }

    if (SUCCEEDED(hr))
    {
        //
        // Seek to the beginning of Output Stream (We can do this since we created the stream)
        //
        LARGE_INTEGER li = {0};
        hr = pStreamOut->Seek(li, STREAM_SEEK_SET, NULL);
    }

    if (pStreamOut)
    {
        if (SUCCEEDED(hr))
        {
            *ppStreamOut = pStreamOut;
        }
        else
        {
            pStreamOut->Release();
        }
    }

    return hr;
}


/*****************************************************************************
 *
 * CMyFilterStream is our implemetation of the filtering stream.
 * The only IStream method that it implements is Write().
 *
 * The stream keeps a reference to the applications stream into which it writes
 * the filtered data (the header is not modified however).
 *
 *******************************************************************************/

///
///  Constructor - note sets reference count to 1
///
CMyFilterStream::CMyFilterStream(
    VOID) : m_pAppStream(NULL) , m_pCachingStream(NULL), m_nRefCount(0), m_cBytesWritten(0),
            m_lBrightness(0), m_lContrast(0), m_lRotation(0), m_lDeskewX(0), m_lDeskewY(0)
{
    //
    // Note: Do not initialize refcount to 1 as it will break module locking, instead call AddRef()
    //
    AddRef();
}

///
///  Destructor:
///
CMyFilterStream::~CMyFilterStream(
    VOID)
{
    if (m_pAppStream)
    {
        m_pAppStream->Release();
        m_pAppStream = NULL;
    }

    if (m_pCachingStream)
    {
        m_pCachingStream->Release();
        m_pCachingStream = NULL;
    }
}

///
/// Initilize stores a reference to the application's stream. It also creates
/// its own stream with CreateStreamOnHGlobal into which it stores all the
/// unfiltered image data before it performs its filtering (in Flush).
///
HRESULT
CMyFilterStream::Initialize(
    _In_    IStream      *pAppStream,
            LONG         lBrightness,
            LONG         lContrast,
            LONG         lRotation,
            LONG         lDeskewX,
            LONG         lDeskewY,
            LONG         lXExtent,
            LONG         lYExtent,
            LONG         lBitDepth,
            GUID         guidFormat)
{
    UNREFERENCED_PARAMETER(lXExtent);
    UNREFERENCED_PARAMETER(lYExtent);
    UNREFERENCED_PARAMETER(lBitDepth);

    HRESULT     hr = S_OK;

    hr = pAppStream ? S_OK : E_INVALIDARG;

    if (SUCCEEDED(hr))
    {
        m_pAppStream = pAppStream;
        m_pAppStream->AddRef();
    }

    if (SUCCEEDED(hr))
    {
        hr = CreateStreamOnHGlobal(0, TRUE, &m_pCachingStream);
    }

    if (SUCCEEDED(hr))
    {
        m_lBrightness = lBrightness;
        m_lContrast   = lContrast;
        m_lRotation   = lRotation;
        m_lDeskewX    = lDeskewX;
        m_lDeskewY    = lDeskewY;
        m_guidFormat = guidFormat;
    }

    return hr;
}

/*****************************************************************************
 *
 *  @func STDMETHODIMP | CMyFilterStream::Flush | Reads unfiltered data, performs filtering and writes
 *                                                data to application stream
 *
 *  @comm
 *
 * Flush is called when the image processing filter receives a WIA_TRANSFER_MSG_END_OF_STREAM message.
 * Flush calls DoFiltering where the actual filtering is done.
 *
 * Note that this simple implementation performs all its filtering only after it has received all
 * unfiltered image data and stored it in m_pCachingStream. A "real" implementation should be able
 * to work on bands of data (at least if no deskew and rotation has to be performed).
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXX   |
 *              The function failed
 *
 *****************************************************************************/
HRESULT
CMyFilterStream::Flush(
    VOID)
{
    HRESULT hr = S_OK;
    IStream * tempStream = NULL;
    IStream * tempOutStream = NULL;

    if(IsEqualGUID(m_guidFormat, WiaImgFmt_RAW))
    {
        if (SUCCEEDED(hr))
        {
            hr = ConvertRawImageToBMP(m_pCachingStream, &tempStream);

            if (SUCCEEDED(hr) && tempStream)
            {
                hr = CreateStreamOnHGlobal(0, TRUE, &tempOutStream);

                if (SUCCEEDED(hr) && tempOutStream)
                {
                    ULONG64 ulDummy = 0;
                    hr = DoFiltering(m_lBrightness,
                                     m_lContrast,
                                     m_lRotation,
                                     m_lDeskewX,
                                     m_lDeskewY,
                                     tempStream,
                                     tempOutStream,
                                     &ulDummy);

                    if (SUCCEEDED(hr))
                    {
                        hr = ConvertBMPImageToRaw(tempOutStream, m_pAppStream, &m_cBytesWritten);
                    }

                    tempOutStream->Release();
                }
                tempStream->Release();
            }
        }
    }
    else
    {
        hr = DoFiltering(
            m_lBrightness,
            m_lContrast,
            m_lRotation,
            m_lDeskewX,
            m_lDeskewY,
            m_pCachingStream,
            m_pAppStream,
            &m_cBytesWritten);
    }

    //
    // Note: m_pAppStream and m_pCachingStream are released by ReleaseStreams which must be always called after Flush
    //

    return hr;
}

///
///  Query Interface
///
STDMETHODIMP
CMyFilterStream::QueryInterface(_In_ const IID& iid_requested, _Out_ void** ppInterfaceOut)
{
    HRESULT hr = S_OK;

    hr = ppInterfaceOut ? S_OK : E_POINTER;

    if (SUCCEEDED(hr))
    {
        *ppInterfaceOut = NULL;
    }

    //
    //  We support IID_IUnknown and IID_IStream
    //
    if (SUCCEEDED(hr))
    {
        if (IID_IUnknown == iid_requested)
        {
            *ppInterfaceOut = static_cast<IUnknown*>(this);
        }
        else if (IID_IStream == iid_requested)
        {
            *ppInterfaceOut = static_cast<IStream*>(this);
        }
        else
        {
            hr = E_NOINTERFACE;
        }
    }

    if (SUCCEEDED(hr))
    {
        reinterpret_cast<IUnknown*>(*ppInterfaceOut)->AddRef();
    }

    return hr;
}

///
///  AddRef
///
STDMETHODIMP_(ULONG)
CMyFilterStream::AddRef(void)
{
    if (m_nRefCount == 0)
    {
        LockModule();
    }

    return InterlockedIncrement(&m_nRefCount);
}

///
///  Release
///
STDMETHODIMP_(ULONG)
CMyFilterStream::Release(void)
{
    ULONG nRetval = InterlockedDecrement(&m_nRefCount);

    if (0 == nRetval)
    {
        delete this;
        UnlockModule();
    }

    return nRetval;
}

STDMETHODIMP
CMyFilterStream::Seek(LARGE_INTEGER dlibMove, DWORD dwOrigin, _Out_ ULARGE_INTEGER *plibNewPosition)
{
    return m_pCachingStream->Seek(dlibMove,dwOrigin,plibNewPosition);
}

STDMETHODIMP
CMyFilterStream::SetSize(ULARGE_INTEGER libNewSize)
{
    return m_pCachingStream->SetSize(libNewSize);
}

STDMETHODIMP
CMyFilterStream::LockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
{
    return m_pCachingStream->LockRegion(libOffset,cb,dwLockType);
}

STDMETHODIMP
CMyFilterStream::CopyTo(_In_ IStream *pstm, ULARGE_INTEGER cb, _Out_ ULARGE_INTEGER *pcbRead, _Out_ ULARGE_INTEGER *pcbWritten)
{
    return m_pCachingStream->CopyTo(pstm,cb,pcbRead,pcbWritten);
}

STDMETHODIMP
CMyFilterStream::Commit(DWORD grfCommitFlags)
{
    return m_pCachingStream->Commit(grfCommitFlags);
}

STDMETHODIMP
CMyFilterStream::Revert(void)
{
    return m_pCachingStream->Revert();
}

STDMETHODIMP
CMyFilterStream::UnlockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
{
    return m_pCachingStream->UnlockRegion(libOffset,cb,dwLockType);
}

STDMETHODIMP
CMyFilterStream::Stat(_Out_ STATSTG *pstatstg, DWORD grfStatFlag)
{
    return m_pCachingStream->Stat(pstatstg, grfStatFlag);
}

STDMETHODIMP
CMyFilterStream::Clone(_Out_ IStream **ppstm)
{
    return m_pCachingStream->Clone(ppstm);
}

STDMETHODIMP
CMyFilterStream::Read(_Out_ void *pv, ULONG cb, _Out_ ULONG *pcbRead)
{
    return m_pCachingStream->Read(pv,cb,pcbRead);
}

STDMETHODIMP
CMyFilterStream::ReleaseStreams()
{
    if (m_pAppStream)
    {
        m_pAppStream->Release();
        m_pAppStream = NULL;
    }

    if (m_pCachingStream)
    {
        m_pCachingStream->Release();
        m_pCachingStream = NULL;
    }

    return S_OK;
}

/*****************************************************************************
 *
 *  @func STDMETHODIMP | CMyFilterStream::Write | Filtering streams implementation of Write
 *
 *  @parm   const void * | pv |
 *          Pointer to the memory buffer.
 *
 *  @parm   ULONG | cb |
 *          Specifies the number of bytes of data to write from the stream object.
 *
 *  @parm   ULONG | pcbWritten |
 *          Pointer to a ULONG variable that receives the actual number of bytes written from the stream object.
 *
 *  @comm
 *  Write simply writes unfiltered data from the driver into its internal caching stream.
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXX   |
 *              The function failed
 *
 *****************************************************************************/
STDMETHODIMP
CMyFilterStream::Write(_In_ const void *pv, ULONG cb, _Out_ ULONG *pcbWritten)
{
    return m_pCachingStream->Write(pv, cb, pcbWritten);
}

///
///  Constructor
///
CImageFilter::CImageFilter(
    VOID) : m_pWiaItem(NULL), m_pAppWiaTransferCallback(NULL), m_nRefCount(0), m_pCurrentStream(NULL)
{
    //
    // Nothing
    //
}

///
///  Destructor
///
CImageFilter::~CImageFilter(
    VOID)
{
    if (m_pWiaItem)
    {
        m_pWiaItem->Release();
        m_pWiaItem = NULL;
    }

    if (m_pAppWiaTransferCallback)
    {
        m_pAppWiaTransferCallback->Release();
        m_pAppWiaTransferCallback = NULL;
    }
}

///
///  QueryInterface
///
STDMETHODIMP
CImageFilter::QueryInterface(_In_ const IID& iid_requested, _Out_ void** ppInterfaceOut)
{
    HRESULT hr = S_OK;

    hr = ppInterfaceOut ? S_OK : E_POINTER;

    if (SUCCEEDED(hr))
    {
        *ppInterfaceOut = NULL;
    }

    //
    //  We support IID_IUnknown, IID_IWiaImageFilter and IID_IWiaTransferCallback
    //
    if (SUCCEEDED(hr))
    {
        if (IID_IUnknown == iid_requested)
        {
            *ppInterfaceOut = static_cast<IWiaImageFilter*>(this);
        }
        else if (IID_IWiaImageFilter == iid_requested)
        {
            *ppInterfaceOut = static_cast<IWiaImageFilter*>(this);
        }
        else if (IID_IWiaTransferCallback == iid_requested)
        {
            *ppInterfaceOut = static_cast<IWiaTransferCallback*>(this);
        }
        else
        {
            hr = E_NOINTERFACE;
        }
    }

    if (SUCCEEDED(hr))
    {
        reinterpret_cast<IUnknown*>(*ppInterfaceOut)->AddRef();
    }

    return hr;
}

///
///  AddRef
///
STDMETHODIMP_(ULONG)
CImageFilter::AddRef(void)
{
    if (m_nRefCount == 0)
    {
        LockModule();
    }

    return InterlockedIncrement(&m_nRefCount);
}

///
///  Release
///
STDMETHODIMP_(ULONG)
CImageFilter::Release(void)
{
    ULONG nRetval = InterlockedDecrement(&m_nRefCount);

    if (0 == nRetval)
    {
        delete this;
        UnlockModule();
    }

    return nRetval;
}

/*****************************************************************************
 *
 *  @func STDMETHODIMP | CImageFilter::InitializeFilter | Initializes image processing filter
 *
 *  @parm   IWiaItem2 | pWiaItem |
 *          The WIA item we are doing the download for. This will actually be the parent item
 *          for some of the item we acquire the image for. See implementation of GetNextStream
 *          for more details.
 *
 *  @parm   IWiaTransferCallback | pWiaTransferCallback |
 *          Application's callback function
 *
 *  @comm
 *  Initializes image processing filter. Stores references to applications callback interface
 *  and IWiaItem2
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXX   |
 *              The function failed
 *
 *****************************************************************************/
STDMETHODIMP
CImageFilter::InitializeFilter(
        _In_            IN  IWiaItem2               *pWiaItem,
        __callback      IN  IWiaTransferCallback    *pWiaTransferCallback)
{
    HRESULT     hr = S_OK;

    m_bTransferCancelled = FALSE;

    hr = (pWiaItem && pWiaTransferCallback) ? S_OK : E_INVALIDARG;

    //
    // Image processing filters supplied with WIA drivers do not
    // support storage items.
    //

    if (SUCCEEDED(hr))
    {
        GUID guidItemCategory = {0};
        hr = pWiaItem->GetItemCategory(&guidItemCategory);
        if (SUCCEEDED(hr))
        {
            if ((WIA_CATEGORY_FINISHED_FILE == guidItemCategory) ||
                (WIA_CATEGORY_FOLDER == guidItemCategory) ||
                (WIA_CATEGORY_ROOT == guidItemCategory))
            {
                hr = E_NOTIMPL;
            }
        }
    }

    //
    // InitializeFilter should only be called once ... but we still Release
    // any resources we might reference
    //
    if (SUCCEEDED(hr))
    {
        if (m_pWiaItem)
        {
            m_pWiaItem->Release();
            m_pWiaItem = NULL;
        }

        if (m_pAppWiaTransferCallback)
        {
            m_pAppWiaTransferCallback->Release();
            m_pAppWiaTransferCallback = NULL;
        }
    }

    if (SUCCEEDED(hr))
    {
        m_pWiaItem = pWiaItem;
        m_pWiaItem->AddRef();

        m_pAppWiaTransferCallback = pWiaTransferCallback;
        m_pAppWiaTransferCallback->AddRef();
    }

    return hr;
}

/*****************************************************************************
 *
 *  @func STDMETHODIMP | CImageFilter::SetNewCallback | Sets new callback for image processing filter to use
 *
 *  @parm   IWiaTransferCallback | pWiaTransferCallback |
 *          The new application callback which the filter should use.
 *
 *  @comm
 *  Since an application can change the callback to use in the IWiaPreview::UpdatePreview call the image
 *  processing filter must "get notified" of this.
 *  Note, the image processing filter is always required to release its current callback even if it is
 *  passed NULL for the callback.
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXX   |
 *              The function failed
 *
 *****************************************************************************/
STDMETHODIMP
CImageFilter::SetNewCallback(
   _In_opt_ __callback  IN   IWiaTransferCallback    *pWiaTransferCallback)
{
    if (m_pAppWiaTransferCallback)
    {
        m_pAppWiaTransferCallback->Release();
        m_pAppWiaTransferCallback = NULL;
    }

    if (pWiaTransferCallback)
    {
        m_pAppWiaTransferCallback = pWiaTransferCallback;
        m_pAppWiaTransferCallback->AddRef();
    }

    return S_OK;
}



/*****************************************************************************
 *
 *  @func STDMETHODIMP | CImageFilter::FilterPreviewImage | FilterPreviewImage implementation
 *

 *  @parm   IWiaItem2 | pWiaChildItem |
 *          pWiaChildItem2 is the item which the image process is to process.
 *          This item must be a child item of the item, m_pWiaItem, that was passed into InitializeFilter.
 *
 *  @parm   RECT | InputImageExtents |
 *          The coordinates (on the flatbed scanner) of the image that the preview component caches internally,
 *          which is also the image that is passed into the pInputStream parameter.
 *          We need this parameter since it is possible that the cached image (pInputStream) was not captured
 *          with XPOS=YPOS=0.
 *
 *  @parm   IStream | pInputStream |
 *          Unfiltered image that is stored by WIA Preview Component.
 *
 *  @comm
 *  FilterPreviewImage is called by the preview component, when an application calls UpdatePreview.
 *  We simply read all the properties from pWiaChildItem that are required for us to do the filtering
 *  and then retrieve the application stream. The actual filtering is then performed in DoFiltering.
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXX   |
 *              The function failed
 *
 *****************************************************************************/
STDMETHODIMP
CImageFilter::FilterPreviewImage(
            IN     LONG                    lFlags,
    _In_    IN     IWiaItem2               *pWiaChildItem,
            IN     RECT                    InputImageExtents,
    _In_    IN     IStream                 *pInputStream)
{
    UNREFERENCED_PARAMETER(lFlags);

    IStream     *pAppStream = NULL;

    BSTR        bstrItemName        = NULL;
    BSTR        bstrFullItemName    = NULL;
    GUID        guidItemCategory    = {0};
    LONG        xpos = 0, ypos = 0, width = 0, height = 0;
    LONG        lBrightness = 0;
    LONG        lContrast = 0;
    LONG        lDeskewX = 0;
    LONG        lDeskewY = 0;
    LONG        lRotation = PORTRAIT;

    HRESULT     hr = S_OK;

    IStream * tempStream = NULL;
    IStream * tempOutStream = NULL;
    BOOL bConvertedRawImage = FALSE;

    ULONG64 ulBytesWrittenToOutputStream = 0;

    //
    // Parameter validation
    //

    hr = (pWiaChildItem && pInputStream) ? S_OK : E_INVALIDARG;

    if (SUCCEEDED(hr))
    {
        //
        // Check whether the image extents are correct.
        // Error if the right or bottom coordinate is zero.
        // Or Left >= Right or Top >= Bottom.
        //

        if ((0 == InputImageExtents.right) ||
            (0 == InputImageExtents.bottom) ||
            (InputImageExtents.left >= InputImageExtents.right) ||
            (InputImageExtents.top >= InputImageExtents.bottom))
        {
            hr = E_INVALIDARG;
        }
    }

    if (SUCCEEDED(hr))
    {
        hr = m_pAppWiaTransferCallback ? S_OK : E_UNEXPECTED;
    }

    //
    // Read all properties we need
    //
    if (SUCCEEDED(hr))
    {
        CWiaItem    *pWiaItemWrapper = new CWiaItem();

        hr = pWiaItemWrapper ? S_OK : E_OUTOFMEMORY;

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->SetIWiaItem(pWiaChildItem);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyGUID(WIA_IPA_ITEM_CATEGORY, &guidItemCategory);

            if (SUCCEEDED(hr) && ((guidItemCategory == WIA_CATEGORY_ROOT) || (guidItemCategory == WIA_CATEGORY_FINISHED_FILE) || (WIA_CATEGORY_FOLDER == guidItemCategory)))
            {
                //
                // We should never get here for storage items!
                //
                hr = E_INVALIDARG;
            }
        }

        //
        // Error if the following is not satisfied:
        //     WIA_IPS_MIN_HORIZONTAL_SIZE <= right - left <= WIA_IPS_MAX_HORIZONTAL_SIZE
        //     WIA_IPS_MIN_VERTICAL_SIZE   <= bottom - top <= WIA_IPS_MAX_VERTICAL_SIZE
        //

        if (SUCCEEDED(hr))
        {
            LONG lHorMin = 0, lHorMax = 0, lHorExtent = InputImageExtents.right - InputImageExtents.left;
            LONG lVerMin = 0, lVerMax = 0, lVerExtent = InputImageExtents.bottom - InputImageExtents.top;

            if (SUCCEEDED(hr))
            {
                hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_MIN_HORIZONTAL_SIZE, &lHorMin);
            }
            if (SUCCEEDED(hr))
            {
                hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_MAX_HORIZONTAL_SIZE, &lHorMax);
            }
            if (SUCCEEDED(hr))
            {
                hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_MIN_VERTICAL_SIZE, &lVerMin);
            }
            if (SUCCEEDED(hr))
            {
                hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_MAX_VERTICAL_SIZE, &lVerMax);

            }
            if (SUCCEEDED(hr))
            {
                if ((lHorExtent < lHorMin) || (lHorExtent > lHorMax) ||
                    (lVerExtent < lVerMin) || (lVerExtent > lVerMax))
                {
                    hr = E_INVALIDARG;
                }
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_XPOS, &xpos);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_YPOS, &ypos);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_XEXTENT, &width);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_YEXTENT, &height);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyBSTR(WIA_IPA_ITEM_NAME, &bstrItemName);
            if (SUCCEEDED(hr) && !bstrItemName)
            {
                hr = E_UNEXPECTED;
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyBSTR(WIA_IPA_FULL_ITEM_NAME, &bstrFullItemName);
            if (SUCCEEDED(hr) && !bstrFullItemName)
            {
                hr = E_UNEXPECTED;
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_BRIGHTNESS, &lBrightness);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_CONTRAST, &lContrast);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_ROTATION, &lRotation);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_DESKEW_X, &lDeskewX);
        }

        if (SUCCEEDED(hr))
        {
            hr = pWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_DESKEW_Y, &lDeskewY);
        }

        if(SUCCEEDED(hr))
        {
            GUID guidItemFormat = {0};

            hr = pWiaItemWrapper->ReadRequiredPropertyGUID(WIA_IPA_FORMAT, &guidItemFormat);
            if((SUCCEEDED(hr)) && (IsEqualGUID(guidItemFormat, WiaImgFmt_RAW)))
            {
                hr = ConvertRawImageToBMP(pInputStream, &tempStream);

                if (SUCCEEDED(hr) && tempStream)
                {
                    bConvertedRawImage = TRUE;
                    pInputStream = tempStream;
                }
            }
        }

        if (pWiaItemWrapper)
        {
            delete pWiaItemWrapper;
        }
    }

    //
    // If the upper left corner of the passed image does not correspond to (0,0)
    // on the flatbed we have to adjust xpos and ypos accordingly in order for us
    // to "cut out" the correct region represented by pWiaChildItem
    //
    if (SUCCEEDED(hr))
    {
        xpos = xpos - InputImageExtents.left;
        ypos = ypos - InputImageExtents.top;
    }

    //
    // Now get the application stream and write to it
    //
    if (SUCCEEDED(hr))
    {
        hr = m_pAppWiaTransferCallback->GetNextStream(0, bstrItemName, bstrFullItemName, &pAppStream);
        if (SUCCEEDED(hr) && !pAppStream)
        {
            hr = E_UNEXPECTED;
        }
    }


    if (SUCCEEDED(hr))
    {
        if (bConvertedRawImage)
        {

            hr = CreateStreamOnHGlobal(0, TRUE, &tempOutStream);
            if (SUCCEEDED(hr))
            {
                ULONG64 ulDummy = 0;

                hr = DoFiltering(lBrightness,
                                 lContrast,
                                 lRotation,
                                 lDeskewX,
                                 lDeskewY,
                                 pInputStream,
                                 tempOutStream,
                                 &ulDummy,
                                 xpos,
                                 ypos,
                                 width,
                                 height
                                 );
            }

            if (SUCCEEDED(hr))
            {
                hr = ConvertBMPImageToRaw(tempOutStream, pAppStream,&ulBytesWrittenToOutputStream);
            }

        }
        else
        {
            hr = DoFiltering(lBrightness,
                             lContrast,
                             lRotation,
                             lDeskewX,
                             lDeskewY,
                             pInputStream,
                             pAppStream,
                             &ulBytesWrittenToOutputStream,
                             xpos,
                             ypos,
                             width,
                             height
                             );
        }
    }

    if (pAppStream)
    {
        pAppStream->Release();
    }

    if (tempStream)
    {
        tempStream->Release();
    }

    if (tempOutStream)
    {
        tempOutStream->Release();
    }

    return hr;
}


/*****************************************************************************
 *
 *  @func STDMETHODIMP | CImageFilter::ApplyProperties | Apply properties after filtering.
 *
 *  @parm   IWiaPropertyStorage | pWiaPropertyStorage |
 *          Pointer to property storage that the image processing filter can write properties to.
 *
 *  @comm
 *  ApplyProperties is called by the WIA service after the image processing filter has processed
 *  the raw data. This method allows the image processing filter to write data back to the driver and device.
 *  This may be necessary for filters that implement things such as auto-exposure.
 *  Note, an image processing filter should only use the WriteMultiple method to write properties into
 *  the provided storage.
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXX   |
 *              The function failed
 *
 *****************************************************************************/
STDMETHODIMP
CImageFilter::ApplyProperties(
    _Inout_    IN  IWiaPropertyStorage       *pWiaPropertyStorage)
{
    HRESULT hr = S_OK;

    hr = pWiaPropertyStorage ? S_OK : E_INVALIDARG;

    //
    // This filter only writes the MY_TEST_FILTER_PROP property for
    // illustrational purposes.
    // In general if a filter does not need to write any properties it
    // should just return S_OK.
    //
    if (SUCCEEDED(hr))
    {
        PROPSPEC    PropSpec[1]    = {0};
        PROPVARIANT PropVariant[1] = {0};

        PropVariantInit(PropVariant);

        PropSpec[0].ulKind  = PRSPEC_PROPID;
        PropSpec[0].propid  = MY_TEST_FILTER_PROP;
        PropVariant[0].vt   = VT_I4;
        PropVariant[0].lVal = 1;

        //
        // Set the properties
        //
        hr = pWiaPropertyStorage->WriteMultiple( 1, PropSpec, PropVariant, WIA_IPA_FIRST );
    }

    return hr;
}


/*****************************************************************************
 *
 *  @func STDMETHODIMP | CImageFilter::TransferCallback | TransferCallback implementation
 *

 *  @parm   LONG | lFlags |
 *          Flags
 *
 *  @parm   WiaTransferParams | pWiaTransferParams |
 *          Contains transfer status
 *
 *  @comm
 *  TransferCallback delegates to the application's callback. It changes the
 *  number of bytes written since we always cache all the data before writing to
 *  the application's stream. We do however not change the percentage since this
 *  represents percentage of total transfer time (a "real" implementation probably
 *  would take the filtering into account here).
 *  We do not write the data to the application's stream until when we receive
 *  a WIA_TRANSFER_MSG_END_OF_STREAM message.
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXX   |
 *              The function failed
 *
 *****************************************************************************/
STDMETHODIMP
CImageFilter::TransferCallback(
            IN  LONG                lFlags,
    _In_    IN  WiaTransferParams   *pWiaTransferParams)
{
    HRESULT     hr = S_OK;

    if (!m_pAppWiaTransferCallback)
    {
        hr =  E_UNEXPECTED;
    }

    if ((SUCCEEDED(hr)) && (!pWiaTransferParams))
    {
        hr = E_INVALIDARG;
    }

    if (SUCCEEDED(hr))
    {
        if (m_pCurrentStream)
        {
            pWiaTransferParams->ulTransferredBytes = m_pCurrentStream->m_cBytesWritten;
        }

        //
        // Note the percent reflects the amount of scanning the driver reports
        // whereas the "BytesWritten" member is the actual number of bytes
        // that we have sent to the application stream.
        //
        if (m_pCurrentStream && (pWiaTransferParams->lMessage == WIA_TRANSFER_MSG_END_OF_STREAM))
        {
            if (!m_bTransferCancelled)
            {
                hr = m_pCurrentStream->Flush();
                pWiaTransferParams->ulTransferredBytes = m_pCurrentStream->m_cBytesWritten;
            }
            m_pCurrentStream -> ReleaseStreams();
        }

        //
        // Call this regardless of hr because applications need termination messages
        //
        HRESULT hrInner = m_pAppWiaTransferCallback->TransferCallback(lFlags, pWiaTransferParams);

        //
        // Don't overwrite the original error if there was one
        //
        if (SUCCEEDED(hr))
        {
            hr = hrInner;
        }


        if (m_pCurrentStream && (pWiaTransferParams->lMessage == WIA_TRANSFER_MSG_END_OF_STREAM))
        {
            m_pCurrentStream->Release();
            m_pCurrentStream = NULL;
        }

        //
        // To indicate not to write to the stream later
        //
        if ( S_OK != hr)
        {
            m_bTransferCancelled = TRUE;
        }
    }

    return hr;
}

/*****************************************************************************
 *
 *  @func STDMETHODIMP | CImageFilter::GetNextStream | Implementation of GetNextStream
 *
 *  @parm   LONG | lFlags |
 *          Flags
 *
 *  @parm   BSTR | bstrItemName |
 *          Name of item
 *
 *  @parm   BSTR | bstrFullItemName |
 *          Full name of item
 *
 *  @parm   IStream | ppDestination |
 *          Upon successful return this will contain the filtering stream
 *
 *  @comm
 *  GetNextStream creates a filtering stream. Since the item represented by
 *  bstrFullItemName may be a child item of the item passed into InitializeFilter
 *  we have to call FindItemByName to retrieve the actual item.
 *
 *  @rvalue S_OK    |
 *              The function succeeded.
 *  @rvalue E_XXXXXX    |
 *              Failure
 *
 *****************************************************************************/
STDMETHODIMP
#pragma warning(suppress: 6101)
CImageFilter::GetNextStream(
            LONG                lFlags,
    _In_z_  BSTR                bstrItemName,
    _In_z_  BSTR                bstrFullItemName,
    _Outptr_result_maybenull_ _At_(*ppDestination, _When_(return == S_OK, _Post_notnull_))
            IStream             **ppDestination)
{
    HRESULT     hr;
    IStream     *pAppStream      = NULL;
    IWiaItem2   *pCurrentWiaItem = NULL;
    BOOL        bStorageItem     = FALSE;
    LONG        lBrightness      = 0;
    LONG        lContrast        = 0;
    LONG        lDeskewX         = 0;
    LONG        lDeskewY         = 0;
    LONG        lRotation        = PORTRAIT;
    LONG        lXExtent         = 0;
    LONG        lYExtent         = 0;
    LONG        lBitDepth        = 0;
    GUID guidItemFormat = {0};

    hr = (bstrItemName && bstrFullItemName && ppDestination) ? S_OK : E_INVALIDARG;

    if (SUCCEEDED(hr))
    {
        *ppDestination = NULL;

        hr = m_pAppWiaTransferCallback ? S_OK : E_UNEXPECTED;
    }

    if (m_pCurrentStream)
    {
        m_pCurrentStream->Release();
        m_pCurrentStream = NULL;
    }

    if (SUCCEEDED(hr))
    {
        hr = m_pAppWiaTransferCallback->GetNextStream(lFlags, bstrItemName, bstrFullItemName, &pAppStream);
        if (SUCCEEDED(hr) && !pAppStream)
        {
            hr = E_UNEXPECTED;
        }
    }

    //
    // Return immediately following cancellations or skips
    //
    if ((S_FALSE == hr) || (WIA_STATUS_SKIP_ITEM == hr))
    {
        return hr;
    }

    if (SUCCEEDED(hr))
    {
        hr = m_pWiaItem->FindItemByName(0, bstrFullItemName, &pCurrentWiaItem);
    }

    //
    // Here we read all properties from pCurrentWiaItem that we need in order to
    // do the the filtering - in this specific case only brightness.
    //
    if (SUCCEEDED(hr))
    {
        CWiaItem    *pIWiaItemWrapper = NULL;

        pIWiaItemWrapper = new CWiaItem();

        hr = pIWiaItemWrapper ? S_OK : E_OUTOFMEMORY;

        if (SUCCEEDED(hr))
        {
            hr = pIWiaItemWrapper->SetIWiaItem(pCurrentWiaItem);
        }

        if (SUCCEEDED(hr))
        {
            GUID        guidItemCategory = {0};

            hr = pIWiaItemWrapper->ReadRequiredPropertyGUID(WIA_IPA_ITEM_CATEGORY,&guidItemCategory);

            bStorageItem = ((guidItemCategory == WIA_CATEGORY_FINISHED_FILE) || (WIA_CATEGORY_FOLDER == guidItemCategory));
        }

        if(SUCCEEDED(hr))
        {
            hr = pIWiaItemWrapper->ReadRequiredPropertyGUID(WIA_IPA_FORMAT, &guidItemFormat);
        }

        if (!bStorageItem)
        {
            if (SUCCEEDED(hr))
            {
                hr = pIWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_BRIGHTNESS,&lBrightness);
            }

            if (SUCCEEDED(hr))
            {
                hr = pIWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_CONTRAST,&lContrast);
            }

            if (SUCCEEDED(hr))
            {
                hr = pIWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_ROTATION, &lRotation);
            }

            if (SUCCEEDED(hr))
            {
                hr = pIWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_DESKEW_X, &lDeskewX);
            }

            if (SUCCEEDED(hr))
            {
                hr = pIWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_DESKEW_Y, &lDeskewY);
            }

            if (SUCCEEDED(hr))
            {
                hr = pIWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_XEXTENT, &lXExtent);
            }

            if (SUCCEEDED(hr))
            {
                hr = pIWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPS_YEXTENT, &lYExtent);
            }

            if (SUCCEEDED(hr))
            {
                hr = pIWiaItemWrapper->ReadRequiredPropertyLong(WIA_IPA_DEPTH, &lBitDepth);
            }
        }

        if (pIWiaItemWrapper)
        {
            delete pIWiaItemWrapper;
        }
    }

    if (SUCCEEDED(hr))
    {
        if (!bStorageItem)
        {
            //
            // We could easily improve the performace by creating a separate filtering stream
            // which simply delegates all calls directly to the application's stream in case
            // Rotation, DeskewX, DeskewY, Brightness and Contrast are all set to 0.
            //
            m_pCurrentStream = new CMyFilterStream();

            if (m_pCurrentStream)
            {
                hr = m_pCurrentStream->Initialize(pAppStream,
                                                  lBrightness,
                                                  lContrast,
                                                  lRotation,
                                                  lDeskewX,
                                                  lDeskewY,
                                                  lXExtent,
                                                  lYExtent,
                                                  lBitDepth,
                                                  guidItemFormat);
            }
            else
            {
                hr = E_OUTOFMEMORY;
            }
        }
        else
        {
            (*ppDestination) = pAppStream;
            (*ppDestination)->AddRef();
        }
    }

    if (SUCCEEDED(hr) && m_pCurrentStream)
    {
        hr = m_pCurrentStream->QueryInterface(IID_IStream, (void**)ppDestination);
    }

    if (pAppStream)
    {
        pAppStream->Release();
    }

    if (pCurrentWiaItem)
    {
        pCurrentWiaItem->Release();
    }

    return hr;
}

/*****************************************************************************
 *
 *  Class Object
 *
 *******************************************************************************/
class CFilterClass : public IClassFactory
{
public:

    STDMETHODIMP
    QueryInterface(_In_ const IID& iid_requested, _Out_ void** ppInterfaceOut)
    {
        HRESULT hr = S_OK;

        hr = ppInterfaceOut ? S_OK : E_POINTER;

        if (SUCCEEDED(hr))
        {
            *ppInterfaceOut = NULL;
        }

        //
        //  We support IID_IUnknown and IID_IClassFactory
        //
        if (SUCCEEDED(hr))
        {
            if (IID_IUnknown == iid_requested)
            {
                *ppInterfaceOut = static_cast<IUnknown*>(this);
            }
            else if (IID_IClassFactory == iid_requested)
            {
                *ppInterfaceOut = static_cast<IClassFactory*>(this);
            }
            else
            {
                hr = E_NOINTERFACE;
            }
        }

        if (SUCCEEDED(hr))
        {
            reinterpret_cast<IUnknown*>(*ppInterfaceOut)->AddRef();
        }

        return hr;
    }

    STDMETHODIMP_(ULONG)
    AddRef(void)
    {
        LockModule();
        return 2;
    }

    STDMETHODIMP_(ULONG)
    Release(void)
    {
        UnlockModule();
        return 1;
    }

    STDMETHODIMP
    CreateInstance(_In_     IUnknown *pUnkOuter,
                   _In_     REFIID   riid,
                   _Out_    void     **ppv)
    {
        CImageFilter   *pImageFilter = NULL;
        HRESULT     hr;

        hr = ppv ? S_OK : E_POINTER;

        if (SUCCEEDED(hr))
        {
            *ppv = 0;
        }

        if (SUCCEEDED(hr))
        {
            if (pUnkOuter)
            {
                hr = CLASS_E_NOAGGREGATION;
            }
        }

        if (SUCCEEDED(hr))
        {
            pImageFilter = new CImageFilter();

            hr = pImageFilter ? S_OK : E_OUTOFMEMORY;
        }

        if (SUCCEEDED(hr))
        {
            pImageFilter->AddRef();
            hr = pImageFilter->QueryInterface(riid, ppv);
            pImageFilter->Release();
        }

        return hr;
    }

    STDMETHODIMP
    LockServer(BOOL bLock)
    {
        if (bLock)
        {
            LockModule();
        }
        else
        {
            UnlockModule();
        }

        return S_OK;
    }
};

STDAPI DllCanUnloadNow(void)
{
    return (g_cLocks == 0) ? S_OK : S_FALSE;
}

STDAPI DllGetClassObject(_In_           REFCLSID   rclsid,
                         _In_           REFIID     riid,
                         _Outptr_    void       **ppv)
{
    static  CFilterClass s_FilterClass;

    if (rclsid == CLSID_WiaImageFilter)
    {
        return s_FilterClass.QueryInterface(riid, ppv);
    }

    *ppv = 0;

    return CLASS_E_CLASSNOTAVAILABLE;
}

//
// Registered in driver INF file - what about un-regestering?
//
STDAPI DllUnregisterServer()
{
    return S_OK;
}

STDAPI DllRegisterServer()
{
    return S_OK;
}