Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

[752123]: src / foreign / vigra / vigra / cachedfileimage.hxx Maximize Restore History

Download this file

cachedfileimage.hxx    2146 lines (1835 with data), 80.3 kB

   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
/*
* Copyright (C) 2004 Andrew Mihal
*
* This software is an extension of the VIGRA computer vision library.
* ( Version 1.2.0, Aug 07 2003 )
* You may use, modify, and distribute this software according
* to the terms stated in the LICENSE file included in
* the VIGRA distribution.
*
* VIGRA is Copyright 1998-2002 by Ullrich Koethe
* Cognitive Systems Group, University of Hamburg, Germany
*
* The VIGRA Website is
* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/
* Please direct questions, bug reports, and contributions to
* koethe@informatik.uni-hamburg.de
*
* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef VIGRA_EXT_CACHEDFILEIMAGE_HXX
#define VIGRA_EXT_CACHEDFILEIMAGE_HXX
#include <errno.h>
#include <map>
#include <iostream>
#include <list>
#include <stdio.h>
#include <cstring>
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#endif
#ifndef _WIN32
#include <unistd.h>
#include <signal.h>
#endif
#ifdef __GW32C__
#define fseeko fseeko64
#undef malloc
#endif
#include <boost/static_assert.hpp>
#include <boost/pool/pool.hpp>
#include <vigra/error.hxx>
#include <vigra/metaprogramming.hxx>
#include <vigra/utilities.hxx>
using std::cout;
using std::cerr;
using std::endl;
using std::list;
using std::map;
using std::min;
#ifdef _WIN32
#define mktemp _mktemp
#endif
namespace vigra {
/** Abstract base class for CachedFileImages. */
class CachedFileImageBase {
public:
virtual ~CachedFileImageBase() { }
virtual int numBlocksAllocated() const = 0;
virtual int numBlocksNeeded() const = 0;
virtual void swapOutBlock() const = 0;
virtual void printBlockStats() const = 0;
};
// Forward declaration.
template <class PIXELTYPE> class CachedFileImage;
/** A singleton that manages memory for several CachedFileImages.
*/
class CachedFileImageDirector {
public:
~CachedFileImageDirector() {
// This is no longer necessary. temp files get unlinked on creation.
//// Make sure all image caches get destroyed and
//// temp backing files get deleted.
//if (!imageList.empty()) {
// cout << endl << "Cleaning up temporary files." << endl;
// while (!imageList.empty()) {
// CachedFileImageBase const *image = imageList.front();
// //cout << "deleting image " << image << endl;
// // Remember that this delete call modifies imageList.
// delete image;
// }
//}
//delete pool;
}
// Obtain a reference to the singleton.
static CachedFileImageDirector &v() {
static CachedFileImageDirector instance;
return instance;
}
// Obtain a pointer to a blocksize chunk of memory.
void* allocateBlock() {
void *block = pool->malloc();
// Prevent the pool from allocating more than one block
// at a time from the system. Otherwise the pool will grab
// more blocks than managedBlocks.
pool->set_next_size(1);
if (block == NULL) throw std::bad_alloc();
return block;
}
void deallocateBlock(void* block) {
if (block != NULL) pool->free(block);
}
// Set the number of bytes this director manages.
void setAllocation(long long bytes) {
// This may not be changed after images have been created.
vigra_precondition(imageList.empty(), "CachedFileImageDirector: "
"attempt to change allocation after images have already "
"been created.");
managedBytes = bytes;
// Recalculate the number of blocks available.
managedBlocks = (int)ceil(managedBytes / (double)blocksize);
blocksAvailable = managedBlocks;
//cout << "director.setAllocation: managedBlocks=" << managedBlocks
// << " blocksAvailable=" << blocksAvailable << endl;
}
// Set the cache block size. This is the minimum amount that is
// moved between the caches and the backing files.
void setBlockSize(int bytes) {
// This may not be changed after images have been created.
vigra_precondition(imageList.empty(), "CachedFileImageDirector: "
"attempt to change block size after images have already "
"been created.");
blocksize = bytes;
delete pool;
pool = new boost::pool<>(blocksize);
// Recalculate the number of blocks available.
managedBlocks = (int)ceil(managedBytes / (double)blocksize);
blocksAvailable = managedBlocks;
//cout << "director.setBlockSize: managedBlocks=" << managedBlocks
// << " blocksAvailable=" << blocksAvailable << endl;
}
long long getAllocation() const {
return managedBytes;
}
// Get the cache block size.
int getBlockSize() const {
return blocksize;
}
int getManagedBlocks() const {
return managedBlocks;
}
int getBlocksAvailable() const {
return blocksAvailable;
}
// Request a certain number of blocks for a new image.
// Returns the number of blocks the new image may use.
int requestBlocksForNewImage(int blocks, CachedFileImageBase const * image) {
//cout << "director.requestBlocksForNewImage(blocks=" << blocks
// << " image=" << image << endl;
int blocksAllocated = 0;
if (blocksAvailable > 0) {
blocksAllocated = 1;
blocksAvailable--;
} else {
// Zero blocks available.
// Try to free a block by forcing another image to swap.
blocksAvailable += freeBlock(image);
if (blocksAvailable == 0) {
// Attempt to free a block was a failure.
vigra_fail("CachedFileImageDirector::requestBlocksForNewImage(): "
"no blocks available and attempt to free blocks failed.");
}
blocksAllocated = blocksAvailable;
blocksAvailable = 0;
}
// Register the new image.
// By placing it at the back, it is marked as the
// most-recently-swapped image.
imageList.push_back(image);
// Initialize the cache miss counter for this image.
imageToMissMap[image] = 0LL;
//cout << "director.requestBlocksForNewImage: blocksAllocated="
// << blocksAllocated << " blocksAvailable=" << blocksAvailable << endl;
//cout << "director.imageList=";
//std::copy(imageList.begin(), imageList.end(),
// std::ostream_iterator<CachedFileImageBase const *>(cout, " "));
//cout << endl;
return blocksAllocated;
}
// Unregister a CachedFileImage with the director.
void returnBlocksUnregisterImage(int blocks, CachedFileImageBase const * image) {
blocksAvailable += blocks;
imageList.remove(image);
//cout << "director.returnBlocks: blocks=" << blocks
// << " image=" << image << endl;
//cout << "director.returnBlocks: blocksAvailable=" << blocksAvailable
// << endl;
//cout << "director.returnBlocks: imageList=";
//std::copy(imageList.begin(), imageList.end(),
// std::ostream_iterator<CachedFileImageBase const *>(cout, " "));
//cout << endl;
}
// Tell the director that a cache miss has occured for this image.
// The director may decide to allocate more blocks to the image.
// If so it returns a nonzero number.
int registerCacheMiss(CachedFileImageBase const * image) {
cacheMisses++;
imageToMissMap[image]++;
// Remove image from list.
imageList.remove(image);
if (blocksAvailable == 0) {
// Try to free a block from an image that has not
// missed recently. If this fails then we just won't
// give the calling image more blocks.
blocksAvailable += freeBlock(image);
}
// Add image to back of list.
// This marks it most-recently-swapped
imageList.push_back(image);
if (blocksAvailable > 0) {
// There are more blocks available to give out.
// Give the image one more block.
blocksAvailable--;
//cout << "director.registerCacheMiss(image=" << image << ")"
// << " blocksAvailable=" << blocksAvailable << " return 1" << endl;
return 1;
} else {
//cout << "director.registerCacheMiss(image=" << image << ")"
// << " blocksAvailable=" << blocksAvailable << " return 0" << endl;
return 0;
}
}
// How many cache misses have occured in total.
long long getCacheMisses() {
return cacheMisses;
}
// How many cache misses have occured for the given image.
long long getCacheMisses(CachedFileImageBase const * image) {
return imageToMissMap[image];
}
// Reset all cache miss counters.
void resetCacheMisses() {
cacheMisses = 0LL;
map<CachedFileImageBase const *, long long>::iterator i;
for (i = imageToMissMap.begin(); i != imageToMissMap.end(); i++) {
(*i).second = 0LL;
}
}
// Print general stats about allocated blocks and cache misses.
void printStats() {
cout << "Summary: cache misses="
<< cacheMisses
<< " blocks managed="
<< managedBlocks
<< " allocated="
<< (managedBlocks - blocksAvailable)
<< " free="
<< blocksAvailable
<< endl;
}
// Print stats about a particular image.
void printStats(const char * imageName, const CachedFileImageBase * image) {
cout << imageName << " " << image << ":"
<< " cache misses=" << imageToMissMap[image]
<< " blocks allocated=" << image->numBlocksAllocated()
<< " blocks required=" << image->numBlocksNeeded()
<< endl;
}
// Print stats about a particular image.
// Add an integer suffix to the image's name.
void printStats(const char * imageName, const int imageNumber,
const CachedFileImageBase * image) {
cout << imageName << imageNumber << " " << image << ":"
<< " cache misses=" << imageToMissMap[image]
<< " blocks allocated=" << image->numBlocksAllocated()
<< " blocks required=" << image->numBlocksNeeded()
<< endl;
}
// Print stats on all images.
void printAllBlockStats() {
list<CachedFileImageBase const *>::iterator i;
for (i = imageList.begin(); i != imageList.end(); i++) {
(*i)->printBlockStats();
}
}
protected:
// Singleton constructor.
CachedFileImageDirector()
: blocksize(2<<20),
managedBytes(1LL<<30),
cacheMisses(0),
imageList(),
imageToMissMap()
{
// Recalculate the number of blocks available.
managedBlocks = (int)ceil(managedBytes / (double)blocksize);
blocksAvailable = managedBlocks;
pool = new boost::pool<>(blocksize);
}
// Free a block for the given image.
// Find another image with proportionally more blocks than image.
int freeBlock(CachedFileImageBase const * image) {
// Try to free a block from an image.
// Check least-recently-missed images first.
list<CachedFileImageBase const *>::iterator i;
for (i = imageList.begin(); i != imageList.end(); i++) {
CachedFileImageBase const * candidate = *i;
//cout << "director.freeBlock candidate=" << candidate
// << " candidate_blocks=" << candidate->numBlocksAllocated()
// << " image_blocks=" << image->numBlocksAllocated() << endl;
//// Don't try to break close ties - else if blocks cannot be divided up
//// evenly the remainder will just get rotated around.
//if (candidate->numBlocksAllocated() > (1+image->numBlocksAllocated())) {
// //cout << "director.freeBlock(image=" << image << ")"
// // << " candidate=" << candidate << " return 1" << endl;
// candidate->swapOutBlock();
// // mark candidate as most-recently-missed.
// imageList.erase(i);
// imageList.push_back(candidate);
// return 1;
//}
// 20080221: If an image is at the front of the list, it has not missed recently.
// Take a block from it. Don't move it to the end of the list. This only happens
// if there is a miss on that image.
if (candidate->numBlocksAllocated() > 0) {
candidate->swapOutBlock();
return 1;
}
}
// Try harder to get another block for image?
// Otherwise the thrash exception will be thrown.
//if (image->numBlocksAllocated() == 1 && image->numBlocksNeeded() > 1) {
// // Look for images that have one block allocated and only need one
// // block. Make them swap. Put donor to rear of list.
//}
// Try even harder?
// do the above and also turn off rotation constraint?
//cout << "director.freeBlock(image=" << image << ") return 0" << endl;
// No blocks could be freed from other images.
return 0;
}
int blocksize;
long long managedBytes;
int managedBlocks;
int blocksAvailable;
long long cacheMisses;
// Pool for blocks
boost::pool<> *pool;
// List of images.
// Front is least-recently-missed image
// Back is most-recently-missed image
list<CachedFileImageBase const *> imageList;
// Map of images to cache miss counters.
map<CachedFileImageBase const *, long long> imageToMissMap;
};
/** A policy for iterating over all pixels in a CachedFileImage sequentially. */
template <class Iterator>
class CachedFileSequentialAccessIteratorPolicy
{
public:
typedef Iterator BaseType;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::difference_type::MoveX difference_type;
typedef typename Iterator::reference reference;
typedef typename Iterator::index_reference index_reference;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::iterator_category iterator_category;
static void initialize(BaseType & d) { }
static reference dereference(BaseType const & d) {
return *d;
}
static index_reference dereference(BaseType const & d, difference_type n) {
int width = d.i->width();
int dy = n / width;
int dx = n % width;
if (d.x() + dx >= width) {dy++; dx -= width;}
else if (d.x() + dx < 0) {dy--; dx += width;}
return d(dx, dy);
}
static bool equal(BaseType const & d1, BaseType const & d2) {
int width1 = d1.i->width();
int width2 = d2.i->width();
return (d1.y()*width1 + d1.x()) == (d2.y()*width2 + d2.x());
}
static bool less(BaseType const & d1, BaseType const & d2) {
int width1 = d1.i->width();
int width2 = d2.i->width();
return (d1.y()*width1 + d1.x()) < (d2.y()*width2 + d2.x());
}
static difference_type difference(BaseType const & d1, BaseType const & d2) {
int width1 = d1.i->width();
int width2 = d2.i->width();
return (d1.y()*width1 + d1.x()) - (d2.y()*width2 + d2.x());
}
static void increment(BaseType & d) {
++d.x;
if (d.x() == d.i->width()) {
d.x = 0;
++d.y;
}
}
static void decrement(BaseType & d) {
--d.x;
if (d.x() < 0) {
d.x = d.i->width() - 1;
--d.y;
}
}
static void advance(BaseType & d, difference_type n) {
int width = d.i->width();
int dy = n / width;
int dx = n % width;
d.x += dx;
d.y += dy;
if (d.x() >= width) {++d.y; d.x -= width;}
if (d.x() < 0) {--d.y; d.x += width;}
}
};
namespace cfi_detail {
template <class StridedOrUnstrided, class T>
class DirectionSelector;
template <class T>
class DirectionSelector<UnstridedArrayTag, T>
{
public:
DirectionSelector(T base=0) : current_(base) {}
DirectionSelector(DirectionSelector const & rhs) : current_(rhs.current_) {}
DirectionSelector & operator=(DirectionSelector const & rhs) {
current_ = rhs.current_;
return *this;
}
void operator++() { ++current_; }
void operator++(int) { ++current_; }
void operator--() { --current_; }
void operator--(int) { --current_; }
void operator+=(int dx) { current_ += dx; }
void operator-=(int dx) { current_ -= dx; }
bool operator==(DirectionSelector const & rhs) const { return (current_ == rhs.current_); }
bool operator!=(DirectionSelector const & rhs) const { return (current_ != rhs.current_); }
bool operator<(DirectionSelector const & rhs) const { return (current_ < rhs.current_); }
bool operator<=(DirectionSelector const & rhs) const { return (current_ <= rhs.current_); }
bool operator>(DirectionSelector const & rhs) const { return (current_ > rhs.current_); }
bool operator>=(DirectionSelector const & rhs) const { return (current_ >= rhs.current_); }
int operator-(DirectionSelector const & rhs) const { return (current_ - rhs.current_); }
T operator()() const { return current_; }
T operator()(int d) const { return (current_ + d); }
T current_;
};
template <class T>
class DirectionSelector<StridedArrayTag, T> {
public:
DirectionSelector(int stride=1, T base=0) : stride_(stride), current_(base) {}
DirectionSelector(DirectionSelector const & rhs) : stride_(rhs.stride_), current_(rhs.current_) {}
DirectionSelector & operator=(DirectionSelector const & rhs) {
stride_ = rhs.stride_;
current_ = rhs.current_;
return *this;
}
void operator++() { current_ += stride_; }
void operator++(int) { current_ += stride_; }
void operator--() { current_ -= stride_; }
void operator--(int) { current_ -= stride_; }
void operator+=(int dy) { current_ += dy*stride_; }
void operator-=(int dy) { current_ -= dy*stride_; }
bool operator==(DirectionSelector const & rhs) const { return (current_ == rhs.current_); }
bool operator!=(DirectionSelector const & rhs) const { return (current_ != rhs.current_); }
bool operator<(DirectionSelector const & rhs) const { return (current_ < rhs.current_); }
bool operator<=(DirectionSelector const & rhs) const { return (current_ <= rhs.current_); }
bool operator>(DirectionSelector const & rhs) const { return (current_ > rhs.current_); }
bool operator>=(DirectionSelector const & rhs) const { return (current_ >= rhs.current_); }
int operator-(DirectionSelector const & rhs) const { return (current_ - rhs.current_) / stride_; }
T operator()() const { return current_; }
T operator()(int d) const { return current_ + d*stride_; }
int stride_;
T current_;
};
template <class StridedOrUnstrided, class T, class Notify>
class NotifyingDirectionSelector;
template <class T, class Notify>
class NotifyingDirectionSelector<UnstridedArrayTag, T, Notify>
{
#if defined __GNUC__ && !defined __clang__
friend class Notify::self_type;
#else
friend typename Notify::self_type;
#endif
protected:
NotifyingDirectionSelector(T base = 0) : current_(base), notify_(NULL) {}
NotifyingDirectionSelector(NotifyingDirectionSelector const & rhs) : current_(rhs.current_), notify_(NULL) {}
void setNotify(Notify *n) { notify_ = n; }
public:
NotifyingDirectionSelector & operator=(NotifyingDirectionSelector const & rhs) {
notify_->_notify(current_, rhs.current_);
current_ = rhs.current_;
return *this;
}
void operator++() { notify_->_notify(current_, current_+1); ++current_; }
void operator++(int) { notify_->_notify(current_, current_+1); ++current_; }
void operator--() { notify_->_notify(current_, current_-1); --current_; }
void operator--(int) { notify_->_notify(current_, current_-1); --current_; }
void operator+=(int dx) { notify_->_notify(current_, current_+dx); current_ += dx; }
void operator-=(int dx) { notify_->_notify(current_, current_-dx); current_ -= dx; }
bool operator==(NotifyingDirectionSelector const & rhs) const { return (current_ == rhs.current_); }
bool operator!=(NotifyingDirectionSelector const & rhs) const { return (current_ != rhs.current_); }
bool operator<(NotifyingDirectionSelector const & rhs) const { return (current_ < rhs.current_); }
bool operator<=(NotifyingDirectionSelector const & rhs) const { return (current_ <= rhs.current_); }
bool operator>(NotifyingDirectionSelector const & rhs) const { return (current_ > rhs.current_); }
bool operator>=(NotifyingDirectionSelector const & rhs) const { return (current_ >= rhs.current_); }
int operator-(NotifyingDirectionSelector const & rhs) const { return (current_ - rhs.current_); }
T operator()() const { return current_; }
T operator()(int d) const { return (current_ + d); }
T current_;
private:
Notify *notify_;
};
template <class T, class Notify>
class NotifyingDirectionSelector<StridedArrayTag, T, Notify> {
#ifdef __GNUC__
friend class Notify::self_type;
#else
friend typename Notify::self_type;
#endif
protected:
NotifyingDirectionSelector(int stride = 1, T base = 0) : stride_(stride), current_(base), notify_(NULL) {}
NotifyingDirectionSelector(NotifyingDirectionSelector const & rhs) : stride_(rhs.stride_), current_(rhs.current_), notify_(NULL) {}
void setNotify(Notify *n) { notify_ = n; }
public:
NotifyingDirectionSelector & operator=(NotifyingDirectionSelector const & rhs) {
notify_->_notify(current_, rhs.current_);
stride_ = rhs.stride_;
current_ = rhs.current_;
return *this;
}
void operator++() { notify_->_notify(current_, current_+stride_); current_ += stride_; }
void operator++(int) { notify_->_notify(current_, current_+stride_); current_ += stride_; }
void operator--() { notify_->_notify(current_, current_-stride_); current_ -= stride_; }
void operator--(int) { notify_->_notify(current_, current_-stride_); current_ -= stride_; }
void operator+=(int dy) { notify_->_notify(current_, current_+dy*stride_); current_ += dy*stride_; }
void operator-=(int dy) { notify_->_notify(current_, current_-dy*stride_); current_ -= dy*stride_; }
bool operator==(NotifyingDirectionSelector const & rhs) const { return (current_ == rhs.current_); }
bool operator!=(NotifyingDirectionSelector const & rhs) const { return (current_ != rhs.current_); }
bool operator<(NotifyingDirectionSelector const & rhs) const { return (current_ < rhs.current_); }
bool operator<=(NotifyingDirectionSelector const & rhs) const { return (current_ <= rhs.current_); }
bool operator>(NotifyingDirectionSelector const & rhs) const { return (current_ > rhs.current_); }
bool operator>=(NotifyingDirectionSelector const & rhs) const { return (current_ >= rhs.current_); }
int operator-(NotifyingDirectionSelector const & rhs) const { return (current_ - rhs.current_) / stride_; }
T operator()() const { return current_; }
T operator()(int d) const { return current_ + d*stride_; }
int stride_;
T current_;
private:
Notify *notify_;
};
} // namespace cfi_detail
/** Base class for CachedFileImage traversers. */
template <class IMAGEITERATOR, class IMAGETYPE, class PIXELTYPE, class REFERENCE, class POINTER,
class StridedOrUnstrided=UnstridedArrayTag>
class CachedFileImageIteratorBase
{
public:
typedef CachedFileImageIteratorBase<IMAGEITERATOR,
IMAGETYPE, PIXELTYPE, REFERENCE, POINTER, StridedOrUnstrided> self_type;
typedef IMAGETYPE image_type;
typedef PIXELTYPE value_type;
typedef PIXELTYPE PixelType;
typedef REFERENCE reference;
typedef REFERENCE index_reference;
typedef POINTER pointer;
typedef Diff2D difference_type;
typedef image_traverser_tag iterator_category;
typedef RowIterator<IMAGEITERATOR> row_iterator;
typedef ColumnIterator<IMAGEITERATOR> column_iterator;
typedef typename cfi_detail::DirectionSelector<StridedOrUnstrided, int> MoveX;
friend class cfi_detail::DirectionSelector<StridedOrUnstrided, int>;
typedef typename cfi_detail::NotifyingDirectionSelector<StridedOrUnstrided, int, self_type> MoveY;
friend class cfi_detail::NotifyingDirectionSelector<StridedOrUnstrided, int, self_type>;
friend class CachedFileSequentialAccessIteratorPolicy<IMAGEITERATOR>;
MoveX x;
MoveY y;
IMAGEITERATOR & operator+=(difference_type const & s) {
x += s.x;
y += s.y;
return static_cast<IMAGEITERATOR &>(*this);
}
IMAGEITERATOR & operator-=(difference_type const & s) {
x -= s.x;
y -= s.y;
return static_cast<IMAGEITERATOR &>(*this);
}
IMAGEITERATOR operator+(difference_type const & s) const {
IMAGEITERATOR ret(static_cast<IMAGEITERATOR const &>(*this));
ret += s;
return ret;
}
IMAGEITERATOR operator-(difference_type const & s) const {
IMAGEITERATOR ret(static_cast<IMAGEITERATOR const &>(*this));
ret -= s;
return ret;
}
difference_type operator-(CachedFileImageIteratorBase const & rhs) const {
return difference_type(x-rhs.x, y-rhs.y);
}
bool operator==(CachedFileImageIteratorBase const & rhs) const {
return (x == rhs.x) && (y == rhs.y);
}
bool operator!=(CachedFileImageIteratorBase const & rhs) const {
return (x != rhs.x) || (y != rhs.y);
}
reference operator*() const {
//std::cout << "iterator=" << this << " currentRow=" << (void*)currentRow << " modifying pixel at (" << x << "," << y._y << ") = " << (void*)(&currentRow[x]) << std::endl;
return currentRow[x()];
//return (*i)(x, y);
}
// FIXME pointer is supposed to be a weak_ptr
pointer operator->() const {
//BOOST_STATIC_ASSERT(false);
return (*i)[y()] + x();
}
index_reference operator[](difference_type const & d) const {
if (d.y == 0) {
return currentRow[x(d.x)];
} else {
return (*i)(x(d.x), y(d.y));
}
}
index_reference operator()(int dx, int dy) const {
if (dy == 0) {
return currentRow[x(dx)];
} else {
return (*i)(x(dx), y(dy));
}
}
// FIXME pointer is supposed to be a weak_ptr
pointer operator[](int dy) const {
//BOOST_STATIC_ASSERT(false);
return (*i)[y(dy)] + x();
}
row_iterator rowIterator() const {
return row_iterator(static_cast<IMAGEITERATOR const &>(*this));
}
column_iterator columnIterator() const {
return column_iterator(static_cast<IMAGEITERATOR const &>(*this));
}
protected:
CachedFileImageIteratorBase(const int X, const int Y, image_type * const I) : x(X), y(Y), i(I), currentRow(NULL) {
y.setNotify(this);
_notify(y());
}
// Constructor only for strided iterators
CachedFileImageIteratorBase(const int X, const int Y, image_type * const I, int xstride, int ystride) : x(xstride, X), y(ystride, Y), i(I), currentRow(NULL) {
y.setNotify(this);
_notify(y());
}
CachedFileImageIteratorBase(const CachedFileImageIteratorBase &r) : x(r.x), y(r.y), i(r.i), currentRow(NULL) {
y.setNotify(this);
_notify(y());
}
CachedFileImageIteratorBase& operator=(const CachedFileImageIteratorBase &r) {
// Note that we change i first so that the assignment to y causes us to get notified
// about the new y coordinate in the new image.
currentRow = NULL;
i = r.i;
x = r.x;
y = r.y;
return *this;
}
void _notify(int initialY) {
// Y has been initialized to initialY.
if (i) currentRow = (*i)[initialY];
//std::cout << "iterator " << this << " _notify(" << initialY << ") currentRow=" << (void*)currentRow << std::endl;
}
void _notify(int oldY, int newY) {
// Y has changed from oldY to newY
if (i) currentRow = (*i)[newY];
//std::cout << "iterator " << this << " _notify(" << oldY << ", " << newY << ") currentRow=" << (void*)currentRow << std::endl;
}
image_type *i;
pointer currentRow;
};
/** Forward declarations */
template <class PIXELTYPE>
class StridedCachedFileImageIterator;
template <class PIXELTYPE>
class ConstStridedCachedFileImageIterator;
/** Regular CachedFileImage traverser. */
template <class PIXELTYPE>
class CachedFileImageIterator
: public CachedFileImageIteratorBase<CachedFileImageIterator<PIXELTYPE>,
CachedFileImage<PIXELTYPE>,
PIXELTYPE, PIXELTYPE &, PIXELTYPE *>
// FIXME this needs to be a weak_ptr ^^^^^^^^^^^
// in case someone uses the iterator to get a pointer to cached data.
{
public:
typedef CachedFileImageIteratorBase<CachedFileImageIterator,
CachedFileImage<PIXELTYPE>,
PIXELTYPE, PIXELTYPE &, PIXELTYPE *> Base;
CachedFileImageIterator(const int x = 0,
const int y = 0,
CachedFileImage<PIXELTYPE> * const i = NULL)
: Base(x, y, i)
{}
friend class StridedCachedFileImageIterator<PIXELTYPE>;
friend class ConstStridedCachedFileImageIterator<PIXELTYPE>;
};
/** Traverser over const CachedFileImage. */
template <class PIXELTYPE>
class ConstCachedFileImageIterator
: public CachedFileImageIteratorBase<ConstCachedFileImageIterator<PIXELTYPE>,
const CachedFileImage<PIXELTYPE>,
PIXELTYPE, PIXELTYPE const &, PIXELTYPE const *>
// FIXME this needs to be a weak_ptr ^^^^^^^^^^^^^^^^^
// in case someone uses the iterator to get a pointer to cached data.
{
public:
typedef CachedFileImageIteratorBase<ConstCachedFileImageIterator,
const CachedFileImage<PIXELTYPE>,
PIXELTYPE, PIXELTYPE const &, PIXELTYPE const *> Base;
// FIXME this needs to be a weak_ptr ^^^^^^^^^^^^^^^^^
ConstCachedFileImageIterator(const int x = 0,
const int y = 0,
const CachedFileImage<PIXELTYPE> * const i = NULL)
: Base(x, y, i)
{}
// FIXME functions to copy CachedFileImageIterator to ConstCachedFileImageIterator are broken
//ConstCachedFileImageIterator(CachedFileImageIterator<PIXELTYPE> const & rhs)
//: Base(0, 0, NULL)
//{
// Base::x = rhs.x;
// Base::y = rhs.y;
// Base::i = rhs.i;
// Base::currentRow = NULL;
// Base::y.setNotify(this);
// Base::_notify(Base::y());
//}
//ConstCachedFileImageIterator &
//operator=(CachedFileImageIterator<PIXELTYPE> const & rhs)
//{
// Base::x = rhs.x;
// Base::y = rhs.y;
// Base::i = rhs.i;
// Base::currentRow = NULL;
// Base::y.setNotify(this);
// Base::_notify(Base::y());
// return *this;
//}
friend class ConstStridedCachedFileImageIterator<PIXELTYPE>;
};
/** Regular CachedFileImage traverser. */
template <class PIXELTYPE>
class StridedCachedFileImageIterator
: public CachedFileImageIteratorBase<StridedCachedFileImageIterator<PIXELTYPE>,
CachedFileImage<PIXELTYPE>,
PIXELTYPE, PIXELTYPE &, PIXELTYPE *, StridedArrayTag>
// FIXME this needs to be a weak_ptr ^^^^^^^^^^^
// in case someone uses the iterator to get a pointer to cached data.
{
public:
typedef CachedFileImageIteratorBase<StridedCachedFileImageIterator,
CachedFileImage<PIXELTYPE>,
PIXELTYPE, PIXELTYPE &, PIXELTYPE *, StridedArrayTag> Base;
StridedCachedFileImageIterator(const int x = 0,
const int y = 0,
CachedFileImage<PIXELTYPE> * const i = NULL,
const int xstride = 1,
const int ystride = 1)
: Base(x, y, i, xstride, ystride)
{}
StridedCachedFileImageIterator(CachedFileImageIterator<PIXELTYPE> const & r,
const int xstride,
const int ystride)
: Base(r.x(), r.y(), r.i, xstride, ystride)
{}
};
/** Traverser over const CachedFileImage. */
template <class PIXELTYPE>
class ConstStridedCachedFileImageIterator
: public CachedFileImageIteratorBase<ConstStridedCachedFileImageIterator<PIXELTYPE>,
const CachedFileImage<PIXELTYPE>,
PIXELTYPE, PIXELTYPE const &, PIXELTYPE const *, StridedArrayTag>
// FIXME this needs to be a weak_ptr ^^^^^^^^^^^^^^^^^
// in case someone uses the iterator to get a pointer to cached data.
{
public:
typedef CachedFileImageIteratorBase<ConstStridedCachedFileImageIterator,
const CachedFileImage<PIXELTYPE>,
PIXELTYPE, PIXELTYPE const &, PIXELTYPE const *, StridedArrayTag> Base;
// FIXME this needs to be a weak_ptr ^^^^^^^^^^^^^^^^^
ConstStridedCachedFileImageIterator(const int x = 0,
const int y = 0,
const CachedFileImage<PIXELTYPE> * const i = NULL,
const int xstride = 1,
const int ystride = 1)
: Base(x, y, i, xstride, ystride)
{}
ConstStridedCachedFileImageIterator(ConstCachedFileImageIterator<PIXELTYPE> const & r,
const int xstride,
const int ystride)
: Base(r.x(), r.y(), r.i, xstride, ystride)
{}
ConstStridedCachedFileImageIterator(CachedFileImageIterator<PIXELTYPE> const & r,
const int xstride,
const int ystride)
: Base(r.x(), r.y(), r.i, xstride, ystride)
{}
// FIXME functions to copy StridedCachedFileImageIterator to ConstStridedCachedFileImageIterator are broken
//ConstStridedCachedFileImageIterator(StridedCachedFileImageIterator<PIXELTYPE> const & rhs)
//: Base(0, 0, NULL, 1, 1)
//{
// Base::x = rhs.x;
// Base::y = rhs.y;
// Base::i = rhs.i;
// Base::currentRow = NULL;
// Base::y.setNotify(this);
// Base::_notify(Base::y());
//}
//ConstStridedCachedFileImageIterator &
//operator=(StridedCachedFileImageIterator<PIXELTYPE> const & rhs)
//{
// Base::x = rhs.x;
// Base::y = rhs.y;
// Base::i = rhs.i;
// Base::currentRow = NULL;
// Base::y.setNotify(this);
// Base::_notify(Base::y());
// return *this;
//}
};
// Forward declaration.
template <class T> struct IteratorTraits;
/** Basic CachedFileImage */
template <class PIXELTYPE>
class CachedFileImage : public CachedFileImageBase {
public:
typedef PIXELTYPE value_type;
typedef PIXELTYPE PixelType;
typedef PIXELTYPE & reference;
typedef PIXELTYPE const & const_reference;
// FIXME these need to be weak_ptrs
typedef PIXELTYPE * pointer;
typedef PIXELTYPE const * const_pointer;
typedef CachedFileImageIterator<PIXELTYPE> traverser;
typedef ConstCachedFileImageIterator<PIXELTYPE> const_traverser;
typedef IteratorAdaptor<CachedFileSequentialAccessIteratorPolicy<traverser> > iterator;
typedef IteratorAdaptor<CachedFileSequentialAccessIteratorPolicy<const_traverser> > const_iterator;
typedef Diff2D difference_type;
typedef Size2D size_type;
typedef typename IteratorTraits<traverser>::DefaultAccessor Accessor;
typedef typename IteratorTraits<const_traverser>::DefaultAccessor ConstAccessor;
CachedFileImage() {
initMembers();
}
CachedFileImage(int width, int height) {
vigra_precondition((width >= 0) && (height >= 0),
"CachedFileImage::CachedFileImage(int width, int height): "
"width and height must be >= 0.\n");
initMembers();
resize(width, height, value_type());
}
explicit CachedFileImage(difference_type const & size, value_type const & d = value_type()) {
vigra_precondition((size.x >= 0) && (size.y >= 0),
"CachedFileImage::CachedFileImage(Diff2D size): "
"size.x and size.y must be >= 0.\n");
initMembers();
resize(size.x, size.y, d);
}
CachedFileImage(int width, int height, value_type const & d) {
vigra_precondition((width >= 0) && (height >= 0),
"CachedFileImage::CachedFileImage(int width, int height, value_type const & ): "
"width and height must be >= 0.\n");
initMembers();
resize(width, height, d);
}
CachedFileImage(const CachedFileImage & rhs) {
initMembers();
resizeCopy(rhs);
}
virtual ~CachedFileImage() {
deallocate();
}
CachedFileImage & operator=(const CachedFileImage &rhs);
CachedFileImage & init(value_type const & pixel);
void resize(int width, int height) {
resize(width, height, value_type());
}
void resize(difference_type const & size) {
resize(size.x, size.y, value_type());
}
void resize(int width, int height, value_type const & d);
void resizeCopy(const CachedFileImage & rhs);
void swap( CachedFileImage<PIXELTYPE>& rhs );
int width() const {
return width_;
}
int height() const {
return height_;
}
size_type size() const {
return size_type(width(), height());
}
bool isInside(difference_type const & d) const {
return d.x >= 0 && d.y >= 0 &&
d.x < width() && d.y < height();
}
reference operator[](difference_type const & d) {
return (getLinePointerDirty(d.y))[d.x];
}
const_reference operator[](difference_type const & d) const {
return (getLinePointer(d.y))[d.x];
}
reference operator()(int dx, int dy) {
return (getLinePointerDirty(dy))[dx];
}
const_reference operator()(int dx, int dy) const {
return (getLinePointer(dy))[dx];
}
// FIXME - needs to return a weak_ptr
pointer operator[](int dy) {
//BOOST_STATIC_ASSERT(false);
//cout << "fetching line pointer for row " << dy << endl;
if (dy < 0 || dy >= height_) return NULL;
else return getLinePointerDirty(dy);
}
// FIXME - needs to return a weak_ptr
const_pointer operator[](int dy) const {
//BOOST_STATIC_ASSERT(false);
//cout << "fetching line pointer for row " << dy << endl;
if (dy < 0 || dy >= height_) return NULL;
else return getLinePointer(dy);
}
traverser upperLeft() {
//vigra_precondition(width_ > 0 && height_ > 0,
vigra_assert(width_ > 0 && height_ > 0,
"CachedFileImage::upperLeft(): image must have non-zero size.");
return traverser(0, 0, this);
}
traverser lowerRight() {
//vigra_precondition(width_ > 0 && height_ > 0,
vigra_assert(width_ > 0 && height_ > 0,
"CachedFileImage::lowerRight(): image must have non-zero size.");
return traverser(width_, height_, this);
}
const_traverser upperLeft() const {
//vigra_precondition(width_ > 0 && height_ > 0,
vigra_assert(width_ > 0 && height_ > 0,
"CachedFileImage::upperLeft(): image must have non-zero size.");
return const_traverser(0, 0, this);
}
const_traverser lowerRight() const {
//vigra_precondition(width_ > 0 && height_ > 0,
vigra_assert(width_ > 0 && height_ > 0,
"CachedFileImage::lowerRight(): image must have non-zero size.");
return const_traverser(width_, height_, this);
}
iterator begin() {
//vigra_precondition(width_ > 0 && height_ > 0,
vigra_assert(width_ > 0 && height_ > 0,
"CachedFileImage::begin(): image must have non-zero size.");
return iterator(traverser(0, 0, this));
}
iterator end() {
//vigra_precondition(width_ > 0 && height_ > 0,
vigra_assert(width_ > 0 && height_ > 0,
"CachedFileImage::end(): image must have non-zero size.");
return iterator(traverser(0, height_, this));
}
const_iterator begin() const {
//vigra_precondition(width_ > 0 && height_ > 0,
vigra_assert(width_ > 0 && height_ > 0,
"CachedFileImage::begin(): image must have non-zero size.");
return const_iterator(const_traverser(0, 0, this));
}
const_iterator end() const {
//vigra_precondition(width_ > 0 && height_ > 0,
vigra_assert(width_ > 0 && height_ > 0,
"CachedFileImage::end(): image must have non-zero size.");
return const_iterator(const_traverser(0, height_, this));
}
Accessor accessor() {
return Accessor();
}
ConstAccessor accessor() const {
return ConstAccessor();
}
int numBlocksAllocated() const {
return blocksAllocated_;
}
int numBlocksNeeded() const {
return blocksNeeded_;
}
void printBlockStats() const {
cout << "image " << this
<< " blocksAllocated=" << blocksAllocated_
<< "/" << blocksNeeded_
<< " mrl=" << *mostRecentlyLoadedBlockIterator_
<< " blocksInMemory={";
std::copy(blocksInMemory_->begin(), blocksInMemory_->end(),
std::ostream_iterator<int>(cout, " "));
cout << "}" << endl;
}
private:
// Data value used to initialize previously unused pixels.
PIXELTYPE initPixel;
void deallocate();
// Init the cache data structures once we know the size of the image.
void initLineStartArray();
// obtain a pointer to the beginning of a line.
// split into two functions for efficiency.
// getLinePointer can then be inlined, and we only incur the function
// call overhead on cache misses.
PIXELTYPE * getLinePointer(const int dy) const;
PIXELTYPE * getLinePointerDirty(const int dy);
PIXELTYPE * getLinePointerCacheMiss(const int dy) const;
// Free space by swapping out a block of lines to the file.
void swapOutBlock() const;
// Lazy creation of tmp file for swapping image data to disk
void initTmpfile() const;
void initMembers() {
initPixel = value_type();
linesPerBlocksize_ = 0;
linesPerBlocksizeLog2_ = 0;
blocksAllocated_ = 0;
blocksNeeded_ = 0;
blocksInMemory_ = NULL;
lines_ = NULL;
blockIsClean_ = NULL;
blockInFile_ = NULL;
width_ = 0;
height_ = 0;
#ifdef _WIN32
hTempFile_ = INVALID_HANDLE_VALUE;
#else
tmpFile_ = NULL;
#endif
tmpFilename_ = NULL;
}
// how many image lines are loaded in one fread
int linesPerBlocksize_;
int linesPerBlocksizeLog2_;
// How many blocks are currently cached in memory.
mutable int blocksAllocated_;
// How many blocks are needed for the entire image.
int blocksNeeded_;
// List of blocks in memory.
// Blocks are in sequential order.
mutable list<int> *blocksInMemory_;
// An iterator that points to the most recently loaded block
// in the blocksInMemory_ list.
mutable list<int>::iterator mostRecentlyLoadedBlockIterator_;
// Array of pointers to first pixel in each line.
mutable PIXELTYPE ** lines_;
// For each block, indicate if that block is dirty.
// Dirty blocks get swapped to disk when they are deallocated.
// Clean blocks are simply deallocated.
mutable bool * blockIsClean_;
// For each block, indicate if that block is in the file.
// Blocks in the file get read from disk when the block is swapped in.
// Blocks not in the file get initialized with initPixel instead.
mutable bool * blockInFile_;
int width_, height_;
#ifdef _WIN32
mutable HANDLE hTempFile_;
#else
mutable FILE *tmpFile_;
#endif
mutable char *tmpFilename_;
};
template <class PIXELTYPE>
void CachedFileImage<PIXELTYPE>::deallocate() {
// Unregister the image with the director.
//cout << "image " << this << ".deallocate" << endl;
CachedFileImageDirector::v().returnBlocksUnregisterImage(blocksAllocated_, this);
delete blocksInMemory_;
// Deallocate all the blocks in use.
if (lines_ != NULL) {
int line = 0;
for (int block = 0; block < blocksNeeded_; block++) {
int firstLineInBlock = line;
for (int subblock = 0; subblock < linesPerBlocksize_; subblock++, line++) {
if (line >= height_) break;
PIXELTYPE *p = lines_[line];
if (p != NULL) {
for (int column = 0; column < width_; column++) {
//FIXME if pixel type is not a simple data type
// and this destructor actually does
// something, then we are in big trouble.
(p[column]).~PIXELTYPE();
}
}
}
CachedFileImageDirector::v().deallocateBlock(lines_[firstLineInBlock]);
if (line >= height_) break;
}
delete[] lines_;
}
delete[] blockIsClean_;
delete[] blockInFile_;
// Close and delete the tmp file if it exists.
#ifdef _WIN32
if (hTempFile_ != INVALID_HANDLE_VALUE) {
CloseHandle(hTempFile_);
}
#else
if (tmpFile_ != NULL) {
fclose(tmpFile_);
}
#endif
// unlink(tmpFilename_);
//}
delete[] tmpFilename_;
};
/** Perform initialization of internal data structures once image size is known. */
template <class PIXELTYPE>
void CachedFileImage<PIXELTYPE>::initLineStartArray() {
// Number of lines to load in one block.
linesPerBlocksize_ = (int)floor(
((double)CachedFileImageDirector::v().getBlockSize())
/ (width_ * sizeof(PIXELTYPE)));
// Round this down to the nearest power of two.
// This will let us divide using right-shift to calculate block number from line number.
linesPerBlocksizeLog2_ = (int)floor(log((double)linesPerBlocksize_)/log(2.0));
linesPerBlocksize_ = 1 << linesPerBlocksizeLog2_;
//cout << "linesPerBlocksizeLog2=" << linesPerBlocksizeLog2_ << endl;
//cout << "linesPerBlocksize=" << linesPerBlocksize_ << endl;
// This is no longer necessary with SKIPSM pyramid operations.
//// Need a minimum of 3 lines per block to support 5-line sliding windows.
//if (linesPerBlocksize_ < 3) {
// vigra_fail("Image cache block size is too small. Use the -b flag to "
// "increase the cache block size.");
//}
blocksNeeded_ = (int)ceil(((double)height_) / linesPerBlocksize_);
//cout << "image.initLineStartArray this=" << this
// << " linesPerBlocksize=" << linesPerBlocksize_
// << " blocksNeeded=" << blocksNeeded_ << endl;
// Request blocks from the director.
int blocksAllowed = CachedFileImageDirector::v().requestBlocksForNewImage(
blocksNeeded_, this);
//cout << "image.initLineStartArray this=" << this
// << " blocksAllowed=" << blocksAllowed << endl;
// Create the blockLRU list.
blocksInMemory_ = new list<int>();
lines_ = new PIXELTYPE*[height_];
blockIsClean_ = new bool[blocksNeeded_];
blockInFile_ = new bool[blocksNeeded_];
// Initialize blockIsClean / blockInFile vectors.
for (int block = 0; block < blocksNeeded_; block++) {
blockIsClean_[block] = true;
blockInFile_[block] = false;
}
// Allocate mem for the first linesPerBlocksize_*blocksAllowed lines.
int line = 0;
for (int block = 0; block < blocksAllowed; block++) {
blocksInMemory_->push_back(block);
blocksAllocated_++;
// Get a block from the director.
PIXELTYPE* blockStart = (PIXELTYPE*)CachedFileImageDirector::v().allocateBlock();
// Divide the block up amongst the lines in the block.
for (int subblock = 0; subblock < linesPerBlocksize_; subblock++, line++, blockStart+=width_) {
if (line >= height_) break;
lines_[line] = blockStart;
// Fill the line with initPixel.
std::uninitialized_fill_n(lines_[line], width_, initPixel);
}
if (line >= height_) break;
}
// All remaining lines (if any) are null (swapped out)
for (; line < height_; line++) {
lines_[line] = NULL;
}
//cout << "image.initLineStartArray this=" << this << " blocksInMemory=";
//std::copy(blocksInMemory_->begin(), blocksInMemory_->end(),
// std::ostream_iterator<int>(cout, " "));
//cout << endl;
mostRecentlyLoadedBlockIterator_ = blocksInMemory_->begin();
return;
};
/** Obtain a pointer to the beginning of a row.
* Marks the block that owns that row dirty.
*/
template <class PIXELTYPE>
inline PIXELTYPE * CachedFileImage<PIXELTYPE>::getLinePointerDirty(const int dy) {
PIXELTYPE *line = lines_[dy];
// Check if line dy is swapped out.
if (line == NULL) line = getLinePointerCacheMiss(dy);
// Mark this block as dirty.
//blockIsClean_[dy / linesPerBlocksize_] = false;
blockIsClean_[dy >> linesPerBlocksizeLog2_] = false;
return line;
};
/** Obtain a pointer to the beginning of a row.
* This is for clean dereferences.
*/
template <class PIXELTYPE>
inline PIXELTYPE * CachedFileImage<PIXELTYPE>::getLinePointer(const int dy) const {
PIXELTYPE *line = lines_[dy];
// Check if line dy is swapped out.
if (line == NULL) line = getLinePointerCacheMiss(dy);
return line;
};
/** Swap in the requested line. */
template <class PIXELTYPE>
PIXELTYPE * CachedFileImage<PIXELTYPE>::getLinePointerCacheMiss(const int dy) const {
//int blockNumber = dy / linesPerBlocksize_;
int blockNumber = dy >> linesPerBlocksizeLog2_;
//int firstLineInBlock = blockNumber * linesPerBlocksize_;
int firstLineInBlock = blockNumber << linesPerBlocksizeLog2_;
//cout << "-------------------------------------------------------" << endl;
//cout << "image " << this << " cache miss:"
// << " line=" << dy
// << " block=" << blockNumber
// << " firstLineInBlock=" << firstLineInBlock
// << " blocksAllocated=" << blocksAllocated_
// << " blocksInMemory={";
//std::copy(blocksInMemory_->begin(), blocksInMemory_->end(),
// std::ostream_iterator<int>(cout, " "));
//cout << "}" << endl;
int moreBlocks = CachedFileImageDirector::v().registerCacheMiss(this);
if (moreBlocks == 0 && blocksAllocated_ == 0) {
vigra_fail("enblend: Out of memory blocks. Try using the -m flag to "
"increase the amount of memory to use, or use the -b flag to "
"decrease the block size\n"
"reason: cache miss, 0 blocks allocated, 0 blocks available.");
} else if (moreBlocks == 0) {
// Make space for new block.
swapOutBlock();
}
// Allocate a block.
PIXELTYPE* blockStart = (PIXELTYPE*)CachedFileImageDirector::v().allocateBlock();
// The number of lines in the block and the number of pixels in the block.
int numLinesInBlock = min(height_, firstLineInBlock + linesPerBlocksize_)
- firstLineInBlock;
int pixelsToRead = numLinesInBlock * width_;
if (blockInFile_[blockNumber]) {
// Find the right spot in the file.
#ifdef _WIN32
DWORD dwError = NO_ERROR;
LONGLONG offset = (LONGLONG)width_
* (LONGLONG)firstLineInBlock
* (LONGLONG)sizeof(PIXELTYPE);
LARGE_INTEGER liOffset;
liOffset.QuadPart = offset;
liOffset.LowPart = SetFilePointer(hTempFile_, liOffset.LowPart, &liOffset.HighPart, FILE_BEGIN);
if (liOffset.LowPart == INVALID_SET_FILE_POINTER && (dwError = GetLastError()) != NO_ERROR) {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL);
cerr << endl << lpMsgBuf << endl;
LocalFree(lpMsgBuf);
vigra_fail("Unable to seek within temporary file.\n"
"This error is specific to the Windows version of Enblend.");
}
#else
off_t offset = (off_t)width_
* (off_t)firstLineInBlock
* (off_t)sizeof(PIXELTYPE);
if (fseeko(tmpFile_, offset, SEEK_SET) != 0) {
vigra_fail(strerror(errno));
}
#endif
// Fill the block with data from the file.
// FIXME: should use compression
#ifdef _WIN32
DWORD bytesRead;
if (0 == ReadFile(hTempFile_,
blockStart,
sizeof(PIXELTYPE) * pixelsToRead,
&bytesRead,
NULL)) {
DWORD dwError = GetLastError();
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL);
cerr << endl << lpMsgBuf << endl;
LocalFree(lpMsgBuf);
vigra_fail("enblend: error reading from image swap file.\n");
}
#else
clearerr(tmpFile_);
int itemsRead = fread(blockStart, sizeof(PIXELTYPE), pixelsToRead, tmpFile_);
if (itemsRead < pixelsToRead) {
perror("enblend");
vigra_fail("enblend: error reading from image swap file.\n");
}
#endif
}
else {
// File does not have data for this block.
// Fill lines with initPixel.
std::uninitialized_fill_n(blockStart, pixelsToRead, initPixel);
}
// Divide the block up amongst the lines in the block.
for (int l = 0; l < linesPerBlocksize_; l++, blockStart+=width_) {
int absoluteLineNumber = l + firstLineInBlock;
if (absoluteLineNumber >= height_) break;
lines_[absoluteLineNumber] = blockStart;
}
// Mark this block as clean.
blockIsClean_[blockNumber] = true;
// Add this block to the list in the right spot.
list<int>::iterator i = blocksInMemory_->begin();
for (; i != blocksInMemory_->end(); ++i) {
if (*i > blockNumber) break;
}
blocksInMemory_->insert(i, blockNumber);
// Push mostRecentlyLoadedBlockIterator to the end of a sequential sequence
// of blocks in memory.
mostRecentlyLoadedBlockIterator_ = --i;
for (++i; i != blocksInMemory_->end(); ++i) {
if (*i == ++blockNumber) mostRecentlyLoadedBlockIterator_ = i;
else break;
}
blocksAllocated_++;
//cout << "image.after-swap-in this=" << this
// << " blocksAllocated=" << blocksAllocated_
// << " mostRecentlyLoadedBlock=" << *mostRecentlyLoadedBlockIterator_
// << " blocksInMemory=";
//std::copy(blocksInMemory_->begin(), blocksInMemory_->end(),
// std::ostream_iterator<int>(cout, " "));
//cout << endl;
//CachedFileImageDirector::v().printAllBlockStats();
return lines_[dy];
};
/** Swap a block out to disk. */
template <class PIXELTYPE>
void CachedFileImage<PIXELTYPE>::swapOutBlock() const {
if (blocksAllocated_ == 0) {
vigra_fail("Attempt to free a block from an image that has no blocks.");
}
//cout << "swapOutBlock image=" << this
// << " blocksAllocated=" << blocksAllocated_
// << " block list before:";
//std::copy(blocksInMemory_->begin(), blocksInMemory_->end(),
// std::ostream_iterator<int>(cout, " "));
//cout << endl;
// Choose a block to swap out.
int blockNumber = 0;
// This is no longer necessary with SKIPSM-based reduce.
//if (blocksAllocated_ == 1 && blocksNeeded_ > 1) {
// // Never swap out our only block (if we need more than one).
// // Enblend iterates over images in 5-line sliding windows (in reduce).
// // This is to avoid thrashing.
// vigra_fail("enblend: Out of memory blocks. Try using the -m flag to "
// "increase the amount of memory to use, or use the -b flag to "
// "decrease the block size\n"
// "reason: probable thrash, 1 blocks allocated, 0 blocks available.");
//} else {
if (mostRecentlyLoadedBlockIterator_ == blocksInMemory_->begin()) {
// We're at the beginning of the image.
// The last block in memory is the one least likely to be used next,
// assuming forward iteration through the image.
blockNumber = blocksInMemory_->back();
blocksInMemory_->pop_back();
} else {
// Try the block before mostRecentlyLoadedBlockIterator.
// Keep the m-r-l block for the 5-line sliding window.
// The block just before that is least likely to be used next,
// assuming forward iteration through the image.
list<int>::iterator candidate = mostRecentlyLoadedBlockIterator_;
--candidate;
blockNumber = *candidate;
blocksInMemory_->erase(candidate);
}
//}
//cout << "swapOutBlock image=" << this << " mRLBI=" << *mostRecentlyLoadedBlockIterator_
// << " after list remove block=" << blockNumber << ": ";
//std::copy(blocksInMemory_->begin(), blocksInMemory_->end(),
// std::ostream_iterator<int>(cout, " "));
//cout << endl;
//int firstLineInBlock = blockNumber * linesPerBlocksize_;
int firstLineInBlock = blockNumber << linesPerBlocksizeLog2_;
PIXELTYPE *blockStart = lines_[firstLineInBlock];
// If block is dirty, swap it to the file.
if (!blockIsClean_[blockNumber]) {
blockInFile_[blockNumber] = true;
// Lazy init the temp file.
#ifdef _WIN32
if (hTempFile_ == INVALID_HANDLE_VALUE)
#else
if (tmpFile_ == NULL)
#endif
initTmpfile();
// Find the right spot in the file.
#ifdef _WIN32
DWORD dwError = NO_ERROR;
LONGLONG offset = (LONGLONG)width_
* (LONGLONG)firstLineInBlock
* (LONGLONG)sizeof(PIXELTYPE);
LARGE_INTEGER liOffset;
liOffset.QuadPart = offset;
liOffset.LowPart = SetFilePointer(hTempFile_, liOffset.LowPart, &liOffset.HighPart, FILE_BEGIN);
if (liOffset.LowPart == INVALID_SET_FILE_POINTER && (dwError = GetLastError()) != NO_ERROR) {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL);
cerr << endl << lpMsgBuf << endl;
LocalFree(lpMsgBuf);
vigra_fail("Unable to seek within temporary file.\n"
"This error is specific to the Windows version of Enblend.");
}
#else
off_t offset = (off_t)width_
* (off_t)firstLineInBlock
* (off_t)sizeof(PIXELTYPE);
if (fseeko(tmpFile_, offset, SEEK_SET) != 0) {
vigra_fail(strerror(errno));
}
#endif
int numLinesInBlock = min(height_, firstLineInBlock + linesPerBlocksize_)
- firstLineInBlock;
int pixelsToWrite = numLinesInBlock * width_;
//FIXME this should use compression.
#ifdef _WIN32
DWORD bytesWritten;
if (0 == WriteFile(hTempFile_,
blockStart,
sizeof(PIXELTYPE) * pixelsToWrite,
&bytesWritten,
NULL)) {
DWORD dwError = GetLastError();
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL);
cerr << endl << lpMsgBuf << endl;
LocalFree(lpMsgBuf);
vigra_fail("enblend: error writing to image swap file.\nMost likely cause: No space for temporary files.\nMake sure that there is enough space in the temporary directory\n");
}
#else
clearerr(tmpFile_);
int itemsWritten = fwrite(blockStart, sizeof(PIXELTYPE), pixelsToWrite, tmpFile_);
if (itemsWritten < pixelsToWrite) {
perror("enblend");
vigra_fail("enblend: error writing to image swap file.\nMost likely cause: No space for temporary files.\nMake sure that there is enough space in the temporary directory\n");
}
#endif
}
// Deallocate lines in block.
for (int l = 0; l < linesPerBlocksize_; l++) {
int absoluteLineNumber = l + firstLineInBlock;
if (absoluteLineNumber >= height_) break;
PIXELTYPE *p = lines_[absoluteLineNumber];
for (int column = 0; column <= width_; column++) {
//FIXME if pixel type is not a simple data type and
// this destructor actually does
// something, then we are in big trouble.
(p[column]).~PIXELTYPE();
}
lines_[absoluteLineNumber] = NULL;
}
// Return block to the director.
CachedFileImageDirector::v().deallocateBlock(blockStart);
blocksAllocated_--;
//cout << "swapOutBlock image=" << this << " after swapout:"
// << " blocksAllocated=" << blocksAllocated_
// << " blocksInMemory=";
//std::copy(blocksInMemory_->begin(), blocksInMemory_->end(),
// std::ostream_iterator<int>(cout, " "));
//cout << endl;
};
/** Create the tmp file to store swapped-out blocks. */
template <class PIXELTYPE>
void CachedFileImage<PIXELTYPE>::initTmpfile() const {
#ifdef _WIN32
const DWORD BUFSIZE=MAX_PATH;
char filenameTemplate[BUFSIZE];
char lpPathBuffer[BUFSIZE];
DWORD dwRetVal;
// Get the temp path.
dwRetVal = GetTempPath(BUFSIZE, // length of the buffer
lpPathBuffer); // buffer for path
if (dwRetVal > BUFSIZE || (dwRetVal == 0))
{
vigra_fail ("GetTempPath failed.");
}
if (! GetTempFileNameA(lpPathBuffer, // directory for temp files
".en", // temp file prefix
0, // create unique name
filenameTemplate)) // buffer for name
{
vigra_fail("enblend: unable to create image swap file name.\n");
}
hTempFile_ = CreateFileA(filenameTemplate,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ, // share mode
NULL, // security attributes
CREATE_ALWAYS, // create mode
FILE_FLAG_DELETE_ON_CLOSE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_TEMPORARY, // file attributes
NULL);
if (hTempFile_ == INVALID_HANDLE_VALUE) {
vigra_fail(strerror(errno));
}
#else
sigset_t oldsigmask;
sigset_t SigintMask;
sigprocmask(SIG_BLOCK, &SigintMask, &oldsigmask);
char * filenameTemplate;
char * tmpdir = getenv("TMPDIR");
if (tmpdir) {
int len = strlen(tmpdir) + 22;
if (len > 0) {
filenameTemplate = (char *) malloc(strlen(tmpdir)+ 22);
strncpy(filenameTemplate, tmpdir, len);
if (filenameTemplate[len-1] != '/') {
strncat(filenameTemplate, "/", len);
}
strncat(filenameTemplate, ".enblend_tmpXXXXXX", len);
} else {
filenameTemplate = strdup("/tmp/.enblend_tmpXXXXXX");
}
} else {
filenameTemplate = strdup("/tmp/.enblend_tmpXXXXXX");
}
#if defined(HAVE_MKSTEMP)
int tmpFD = mkstemp(filenameTemplate);
if (tmpFD < 0) {
vigra_fail("enblend: unable to create image swap file.\n");
}
tmpFile_ = fdopen(tmpFD, "wb+");
#else // HAVE_MKSTEMP
char *tmpReturn = mktemp(filenameTemplate);
if (tmpReturn == NULL) {
vigra_fail("enblend: unable to create image swap file.\n");
}
tmpFile_ = fopen(filenameTemplate, "wb+");
#endif // !HAVE_MKSTEMP
if (tmpFile_ == NULL) {
vigra_fail(strerror(errno));
}
#endif // ! _WIN32
unsigned int filenameTemplateLength = (unsigned int)strlen(filenameTemplate) + 1;
tmpFilename_ = new char[filenameTemplateLength];
strncpy(tmpFilename_, filenameTemplate, filenameTemplateLength);
#ifndef _WIN32
unlink(tmpFilename_);
sigprocmask(SIG_SETMASK, &oldsigmask, NULL);
free(filenameTemplate);
#endif
// This doesn't seem to help.
//if (setvbuf(tmpFile_, NULL, _IONBF, 0) != 0) {
// vigra_fail(strerror(errno));
//}
};
template <class PIXELTYPE>
CachedFileImage<PIXELTYPE> &
CachedFileImage<PIXELTYPE>::operator=(const CachedFileImage<PIXELTYPE> & rhs) {
if (this != &rhs) {
if ((width() != rhs.width()) ||
(height() != rhs.height())) {
resizeCopy(rhs);
}
else {
const_iterator is = rhs.begin();
const_iterator iend = rhs.end();
iterator id = begin();
for(; is != iend; ++is, ++id) *id = *is;
}
}
return *this;
};
template <class PIXELTYPE>
CachedFileImage<PIXELTYPE> &
CachedFileImage<PIXELTYPE>::init(value_type const & pixel) {
initPixel = pixel;
// Mark all blocks as clean
// Mark all blocks as absent from the backing file.
// This will effectively discard all current pixel data in the file.
for (int block = 0; block < blocksNeeded_; block++) {
blockIsClean_[block] = true;
blockInFile_[block] = false;
}
// For any lines that are currently allocated, fill them with initPixel.
// This will discard all current pixel data in memory.
for (int line = 0; line < height_; line++) {
PIXELTYPE *p = lines_[line];
if (lines_[line] != NULL) {
for (int column = 0; column <= width_; column++) {
//FIXME if pixel type is not a simple data type and this
// destructor actually does
// something, then we are in big trouble.
(p[column]).~PIXELTYPE();
}
// Fill the line with initPixel.
std::uninitialized_fill_n(lines_[line], width_, initPixel);
}
}
return *this;
};
template <class PIXELTYPE>
void CachedFileImage<PIXELTYPE>::resize(int width, int height, value_type const & d) {
vigra_precondition((width >= 0) && (height >= 0),
"CachedFileImage::resize(int width, int height, value_type const &): "
"width and height must be >= 0.\n");
deallocate();
initMembers();
initPixel = d;
width_ = width;
height_ = height;
initLineStartArray();
};
template <class PIXELTYPE>
void CachedFileImage<PIXELTYPE>::resizeCopy(const CachedFileImage & rhs) {
deallocate();
initMembers();
if (rhs.width() * rhs.height() > 0) {
width_ = rhs.width();
height_ = rhs.height();
initLineStartArray();
const_iterator is = rhs.begin();
const_iterator iend = rhs.end();
iterator id = begin();
for(; is != iend; ++is, ++id) *id = *is;
}
};
template <class PIXELTYPE>
void CachedFileImage<PIXELTYPE>::swap( CachedFileImage<PIXELTYPE>& rhs ) {
if (&rhs != this) {
std::swap(initPixel, rhs.initPixel);
std::swap(linesPerBlocksize_, rhs.linesPerBlocksize_);
std::swap(linesPerBlocksizeLog2_, rhs.linesPerBlocksizeLog2_);
std::swap(blocksAllocated_, rhs.blocksAllocated_);
std::swap(blocksNeeded_, rhs.blocksNeeded_);
std::swap(blocksInMemory_, rhs.blocksInMemory_);
std::swap(mostRecentlyLoadedBlockIterator_, rhs.mostRecentlyLoadedBlockIterator_);
std::swap(lines_, rhs.lines_);
std::swap(blockIsClean_, rhs.blockIsClean_);
std::swap(blockInFile_, rhs.blockInFile_);
std::swap(width_, rhs.width_);
std::swap(height_, rhs.height_);
#ifdef _WIN32
std::swap(hTempFile_, rhs.hTempFile_);
#else
std::swap(tmpFile_, rhs.tmpFile_);
#endif
std::swap(tmpFilename_, rhs.tmpFilename_);
}
};
/********************************************************/
/* */
/* argument object factories */
/* */
/********************************************************/
template <class PixelType, class Accessor>
inline triple<typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::const_traverser, Accessor>
srcImageRange(CachedFileImage<PixelType> const & img, Accessor a)
{
return triple<typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::const_traverser,
Accessor>(img.upperLeft(),
img.lowerRight(),
a);
}
template <class PixelType, class Accessor>
inline pair<typename CachedFileImage<PixelType>::const_traverser, Accessor>
srcImage(CachedFileImage<PixelType> const & img, Accessor a)
{
return pair<typename CachedFileImage<PixelType>::const_traverser,
Accessor>(img.upperLeft(), a);
}
template <class PixelType, class Accessor>
inline triple<typename CachedFileImage<PixelType>::traverser,
typename CachedFileImage<PixelType>::traverser, Accessor>
destImageRange(CachedFileImage<PixelType> & img, Accessor a)
{
return triple<typename CachedFileImage<PixelType>::traverser,
typename CachedFileImage<PixelType>::traverser,
Accessor>(img.upperLeft(),
img.lowerRight(),
a);
}
template <class PixelType, class Accessor>
inline pair<typename CachedFileImage<PixelType>::traverser, Accessor>
destImage(CachedFileImage<PixelType> & img, Accessor a)
{
return pair<typename CachedFileImage<PixelType>::traverser,
Accessor>(img.upperLeft(), a);
}
template <class PixelType, class Accessor>
inline pair<typename CachedFileImage<PixelType>::const_traverser, Accessor>
maskImage(CachedFileImage<PixelType> const & img, Accessor a)
{
return pair<typename CachedFileImage<PixelType>::const_traverser,
Accessor>(img.upperLeft(), a);
}
/****************************************************************/
template <class PixelType>
inline triple<typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::ConstAccessor>
srcImageRange(CachedFileImage<PixelType> const & img)
{
return triple<typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::ConstAccessor>(img.upperLeft(),
img.lowerRight(),
img.accessor());
}
template <class PixelType>
inline pair< typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::ConstAccessor>
srcImage(CachedFileImage<PixelType> const & img)
{
return pair<typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::ConstAccessor>(img.upperLeft(),
img.accessor());
}
template <class PixelType>
inline triple< typename CachedFileImage<PixelType>::traverser,
typename CachedFileImage<PixelType>::traverser,
typename CachedFileImage<PixelType>::Accessor>
destImageRange(CachedFileImage<PixelType> & img)
{
return triple<typename CachedFileImage<PixelType>::traverser,
typename CachedFileImage<PixelType>::traverser,
typename CachedFileImage<PixelType>::Accessor>(img.upperLeft(),
img.lowerRight(),
img.accessor());
}
template <class PixelType>
inline pair< typename CachedFileImage<PixelType>::traverser,
typename CachedFileImage<PixelType>::Accessor>
destImage(CachedFileImage<PixelType> & img)
{
return pair<typename CachedFileImage<PixelType>::traverser,
typename CachedFileImage<PixelType>::Accessor>(img.upperLeft(),
img.accessor());
}
template <class PixelType>
inline pair< typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::ConstAccessor>
maskImage(CachedFileImage<PixelType> const & img)
{
return pair<typename CachedFileImage<PixelType>::const_traverser,
typename CachedFileImage<PixelType>::ConstAccessor>(img.upperLeft(),
img.accessor());
}
template <class PixelType>
inline pair< ConstStridedCachedFileImageIterator<PixelType>,
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor>
maskStrideIter(CachedFileImageIterator<PixelType> const & upperLeft, int xstride, int ystride)
{
return pair< ConstStridedCachedFileImageIterator<PixelType>,
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor >
(ConstStridedCachedFileImageIterator<PixelType>(upperLeft, xstride, ystride),
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor());
}
template <class PixelType>
inline pair< ConstStridedCachedFileImageIterator<PixelType>,
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor>
maskStrideIter(ConstCachedFileImageIterator<PixelType> const & upperLeft, int xstride, int ystride)
{
return pair< ConstStridedCachedFileImageIterator<PixelType>,
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor >
(ConstStridedCachedFileImageIterator<PixelType>(upperLeft, xstride, ystride),
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor());
}
template <class PixelType>
inline triple< ConstStridedCachedFileImageIterator<PixelType>,
ConstStridedCachedFileImageIterator<PixelType>,
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor>
maskStrideIterRange(CachedFileImageIterator<PixelType> const & upperLeft,
CachedFileImageIterator<PixelType> const & lowerRight,
int xstride, int ystride)
{
return triple< ConstStridedCachedFileImageIterator<PixelType>,
ConstStridedCachedFileImageIterator<PixelType>,
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor >
(ConstStridedCachedFileImageIterator<PixelType>(upperLeft, xstride, ystride),
ConstStridedCachedFileImageIterator<PixelType>(lowerRight, xstride, ystride),
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor());
}
template <class PixelType>
inline triple< ConstStridedCachedFileImageIterator<PixelType>,
ConstStridedCachedFileImageIterator<PixelType>,
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor>
maskStrideIterRange(ConstCachedFileImageIterator<PixelType> const & upperLeft,
ConstCachedFileImageIterator<PixelType> const & lowerRight,
int xstride, int ystride)
{
return triple< ConstStridedCachedFileImageIterator<PixelType>,
ConstStridedCachedFileImageIterator<PixelType>,
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor >
(ConstStridedCachedFileImageIterator<PixelType>(upperLeft, xstride, ystride),
ConstStridedCachedFileImageIterator<PixelType>(lowerRight, xstride, ystride),
typename IteratorTraits<ConstStridedCachedFileImageIterator<PixelType> >::DefaultAccessor());
}
template <typename PixelType, typename ImgAccessor>
vigra::triple<StridedCachedFileImageIterator<PixelType>, StridedCachedFileImageIterator<PixelType>, ImgAccessor>
stride(int xstride, int ystride, vigra::triple<CachedFileImageIterator<PixelType>, CachedFileImageIterator<PixelType>, ImgAccessor> image) {
Diff2D diff = image.second - image.first;
if (diff.x % xstride) diff.x += (xstride - (diff.x % xstride));
if (diff.y % ystride) diff.y += (ystride - (diff.y % ystride));
//cout << "stride(" << xstride << ", " << ystride << ", " << (image.second - image.first) << ", " << diff << ")" << endl;
return vigra::make_triple(StridedCachedFileImageIterator<PixelType>(image.first, xstride, ystride),
StridedCachedFileImageIterator<PixelType>(image.first + diff, xstride, ystride),
image.third);
};
template <typename PixelType, typename ImgAccessor>
vigra::triple<ConstStridedCachedFileImageIterator<PixelType>, ConstStridedCachedFileImageIterator<PixelType>, ImgAccessor>
stride(int xstride, int ystride, vigra::triple<ConstCachedFileImageIterator<PixelType>, ConstCachedFileImageIterator<PixelType>, ImgAccessor> image) {
Diff2D diff = image.second - image.first;
if (diff.x % xstride) diff.x += (xstride - (diff.x % xstride));
if (diff.y % ystride) diff.y += (ystride - (diff.y % ystride));
//cout << "stride(" << xstride << ", " << ystride << ", " << (image.second - image.first) << ", " << diff << ")" << endl;
return vigra::make_triple(ConstStridedCachedFileImageIterator<PixelType>(image.first, xstride, ystride),
ConstStridedCachedFileImageIterator<PixelType>(image.first + diff, xstride, ystride),
image.third);
};
template <typename PixelType, typename ImgAccessor>
std::pair<StridedCachedFileImageIterator<PixelType>, ImgAccessor>
stride(int xstride, int ystride, std::pair<CachedFileImageIterator<PixelType>, ImgAccessor> image) {
return std::make_pair(StridedCachedFileImageIterator<PixelType>(image.first, xstride, ystride), image.second);
};
template <typename PixelType, typename ImgAccessor>
std::pair<ConstStridedCachedFileImageIterator<PixelType>, ImgAccessor>
stride(int xstride, int ystride, std::pair<ConstCachedFileImageIterator<PixelType>, ImgAccessor> image) {
return std::make_pair(ConstStridedCachedFileImageIterator<PixelType>(image.first, xstride, ystride), image.second);
};
} // namespace vigra
#endif /* VIGRA_EXT_CACHEDFILEIMAGE_HXX */