ImfDeepTiledInputFile.cpp 60.4 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
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////

//-----------------------------------------------------------------------------
//
//      class DeepTiledInputFile
//
//-----------------------------------------------------------------------------

#include <ImfDeepTiledInputFile.h>
#include <ImfTileDescriptionAttribute.h>
#include <ImfChannelList.h>
#include <ImfMisc.h>
#include <ImfTiledMisc.h>
#include <ImfStdIO.h>
#include <ImfCompressor.h>
#include "ImathBox.h"
#include <ImfXdr.h>
#include <ImfConvert.h>
#include <ImfVersion.h>
#include <ImfTileOffsets.h>
#include <ImfThreading.h>
#include <ImfPartType.h>
#include <ImfMultiPartInputFile.h>
#include "IlmThreadPool.h"
#include "IlmThreadSemaphore.h"
#include "IlmThreadMutex.h"
#include "ImfInputStreamMutex.h"
#include "ImfInputPartData.h"
#include "ImathVec.h"
#include "Iex.h"
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <limits>

#include "ImfNamespace.h"

OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER

using IMATH_NAMESPACE::Box2i;
using IMATH_NAMESPACE::V2i;
using std::string;
using std::vector;
using std::min;
using std::max;
using ILMTHREAD_NAMESPACE::Mutex;
using ILMTHREAD_NAMESPACE::Lock;
using ILMTHREAD_NAMESPACE::Semaphore;
using ILMTHREAD_NAMESPACE::Task;
using ILMTHREAD_NAMESPACE::TaskGroup;
using ILMTHREAD_NAMESPACE::ThreadPool;

namespace {

struct TInSliceInfo
{
    PixelType           typeInFrameBuffer;
    PixelType           typeInFile;
    char*               pointerArrayBase;
    size_t              xStride;
    size_t              yStride;
    ptrdiff_t           sampleStride;
    bool                fill;
    bool                skip;
    double              fillValue;
    int                 xTileCoords;
    int                 yTileCoords;

    TInSliceInfo (PixelType typeInFrameBuffer = HALF,
                  char * base = NULL,
                  PixelType typeInFile = HALF,
                  size_t xStride = 0,
                  size_t yStride = 0,
                  ptrdiff_t sampleStride = 0,
                  bool fill = false,
                  bool skip = false,
                  double fillValue = 0.0,
                  int xTileCoords = 0,
                  int yTileCoords = 0);
};


TInSliceInfo::TInSliceInfo (PixelType tifb,
                            char * b,
                            PixelType tifl,
                            size_t xs, size_t ys,
                            ptrdiff_t spst,
                            bool f, bool s,
                            double fv,
                            int xtc,
                            int ytc)
:
    typeInFrameBuffer (tifb),
    typeInFile (tifl),
    pointerArrayBase (b),
    xStride (xs),
    yStride (ys),
    sampleStride (spst),
    fill (f),
    skip (s),
    fillValue (fv),
    xTileCoords (xtc),
    yTileCoords (ytc)
{
    // empty
}


struct TileBuffer
{
    Array2D<unsigned int>       sampleCount;
    const char *                uncompressedData;
    char *                      buffer;
    Int64                         dataSize;
    Int64                         uncompressedDataSize;
    Compressor *                compressor;
    Compressor::Format          format;
    int                         dx;
    int                         dy;
    int                         lx;
    int                         ly;
    bool                        hasException;
    string                      exception;

     TileBuffer ();
    ~TileBuffer ();

    inline void         wait () {_sem.wait();}
    inline void         post () {_sem.post();}

 protected:

    Semaphore _sem;
};


TileBuffer::TileBuffer ():
    uncompressedData (0),
    buffer (0),
    dataSize (0),
    compressor (0),
    format (defaultFormat (compressor)),
    dx (-1),
    dy (-1),
    lx (-1),
    ly (-1),
    hasException (false),
    exception (),
    _sem (1)
{
    // empty
}


TileBuffer::~TileBuffer ()
{
    delete compressor;
}

} // namespace


class MultiPartInputFile;


//
// struct TiledInputFile::Data stores things that will be
// needed between calls to readTile()
//

struct DeepTiledInputFile::Data: public Mutex
{
    Header          header;                         // the image header
    TileDescription tileDesc;                       // describes the tile layout
    int             version;                        // file's version
    DeepFrameBuffer frameBuffer;                    // framebuffer to write into
    LineOrder       lineOrder;                      // the file's lineorder
    int             minX;                           // data window's min x coord
    int             maxX;                           // data window's max x coord
    int             minY;                           // data window's min y coord
    int             maxY;                           // data window's max x coord

    int             numXLevels;                     // number of x levels
    int             numYLevels;                     // number of y levels
    int *           numXTiles;                      // number of x tiles at a level
    int *           numYTiles;                      // number of y tiles at a level

    TileOffsets     tileOffsets;                    // stores offsets in file for
    // each tile

    bool            fileIsComplete;                 // True if no tiles are missing
                                                    // in the file

    vector<TInSliceInfo*> slices;                    // info about channels in file

                                                    // ourselves? or does someone
                                                    // else do it?

    int             partNumber;                     // part number

    bool            multiPartBackwardSupport;       // if we are reading a multipart file
                                                    // using OpenEXR 1.7 API

    int             numThreads;                     // number of threads

    MultiPartInputFile* multiPartFile;              // the MultiPartInputFile used to
                                                    // support backward compatibility

    vector<TileBuffer*> tileBuffers;                // each holds a single tile

    bool            memoryMapped;                   // if the stream is memory mapped

    char*           sampleCountSliceBase;           // pointer to the start of
                                                    // the sample count array
    ptrdiff_t       sampleCountXStride;             // x stride of the sample count array
    ptrdiff_t       sampleCountYStride;             // y stride of the sample count array

    int             sampleCountXTileCoords;         // the value of xTileCoords from the
                                                    // sample count slice
    int             sampleCountYTileCoords;         // the value of yTileCoords from the
                                                    // sample count slice

    Array<char>     sampleCountTableBuffer;         // the buffer for sample count table

    Compressor*     sampleCountTableComp;           // the decompressor for sample count table

    Int64           maxSampleCountTableSize;        // the max size in bytes for a pixel
                                                    // sample count table
    int             combinedSampleSize;             // total size of all channels combined to check sampletable size
                                                    
    InputStreamMutex *  _streamData;
    bool                _deleteStream; // should we delete the stream
     Data (int numThreads);
    ~Data ();

    inline TileBuffer * getTileBuffer (int number);
                                                    // hash function from tile indices
                                                    // into our vector of tile buffers

    int&                getSampleCount(int x, int y);
                                                    // get the number of samples
                                                    // in each pixel
};


DeepTiledInputFile::Data::Data (int numThreads):
    numXTiles (0),
    numYTiles (0),
    partNumber (-1),
    multiPartBackwardSupport(false),
    numThreads(numThreads),
    memoryMapped(false),
    _streamData(NULL),
    _deleteStream(false)
{
    //
    // We need at least one tileBuffer, but if threading is used,
    // to keep n threads busy we need 2*n tileBuffers
    //

    tileBuffers.resize (max (1, 2 * numThreads));
}


DeepTiledInputFile::Data::~Data ()
{
    delete [] numXTiles;
    delete [] numYTiles;

    for (size_t i = 0; i < tileBuffers.size(); i++)
        delete tileBuffers[i];

    if (multiPartBackwardSupport)
        delete multiPartFile;

    for (size_t i = 0; i < slices.size(); i++)
        delete slices[i];
}


TileBuffer*
DeepTiledInputFile::Data::getTileBuffer (int number)
{
    return tileBuffers[number % tileBuffers.size()];
}


int&
DeepTiledInputFile::Data::getSampleCount(int x, int y)
{
    return sampleCount(sampleCountSliceBase,
                       sampleCountXStride,
                       sampleCountYStride,
                       x, y);
}


namespace {

void
readTileData (InputStreamMutex *streamData,
              DeepTiledInputFile::Data *ifd,
              int dx, int dy,
              int lx, int ly,
              char *&buffer,
              Int64 &dataSize,
              Int64 &unpackedDataSize)
{
    //
    // Read a single tile block from the file and into the array pointed
    // to by buffer.  If the file is memory-mapped, then we change where
    // buffer points instead of writing into the array (hence buffer needs
    // to be a reference to a char *).
    //

    //
    // Look up the location for this tile in the Index and
    // seek to that position if necessary
    //

    Int64 tileOffset = ifd->tileOffsets (dx, dy, lx, ly);

    if (tileOffset == 0)
    {
        THROW (IEX_NAMESPACE::InputExc, "Tile (" << dx << ", " << dy << ", " <<
                              lx << ", " << ly << ") is missing.");
    }

    //
    // In a multi-part file, the next chunk does not need to
    // belong to the same part, so we have to compare the
    // offset here.
    //

    if ( !isMultiPart(ifd->version) )
    {
        if (streamData->currentPosition != tileOffset)
            streamData->is->seekg(tileOffset);
    }
    else
    {
        //
        // In a multi-part file, the file pointer may be moved by other
        // parts, so we have to ask tellg() where we are.
        //
        if (streamData->is->tellg() != tileOffset)
            streamData->is->seekg (tileOffset);
    }

    //
    // Read the first few bytes of the tile (the header).
    // Verify that the tile coordinates and the level number
    // are correct.
    //

    int tileXCoord, tileYCoord, levelX, levelY;

    if (isMultiPart(ifd->version))
    {
        int partNumber;
        Xdr::read <StreamIO> (*streamData->is, partNumber);
        if (partNumber != ifd->partNumber)
        {
            THROW (IEX_NAMESPACE::ArgExc, "Unexpected part number " << partNumber
                   << ", should be " << ifd->partNumber << ".");
        }
    }

    Xdr::read <StreamIO> (*streamData->is, tileXCoord);
    Xdr::read <StreamIO> (*streamData->is, tileYCoord);
    Xdr::read <StreamIO> (*streamData->is, levelX);
    Xdr::read <StreamIO> (*streamData->is, levelY);

    Int64 tableSize;
    Xdr::read <StreamIO> (*streamData->is, tableSize);

    Xdr::read <StreamIO> (*streamData->is, dataSize);
    Xdr::read <StreamIO> (*streamData->is, unpackedDataSize);


    //
    // Skip the pixel sample count table because we have read this data.
    //

    Xdr::skip <StreamIO> (*streamData->is, tableSize);


    if (tileXCoord != dx)
        throw IEX_NAMESPACE::InputExc ("Unexpected tile x coordinate.");

    if (tileYCoord != dy)
        throw IEX_NAMESPACE::InputExc ("Unexpected tile y coordinate.");

    if (levelX != lx)
        throw IEX_NAMESPACE::InputExc ("Unexpected tile x level number coordinate.");

    if (levelY != ly)
        throw IEX_NAMESPACE::InputExc ("Unexpected tile y level number coordinate.");

    //
    // Read the pixel data.
    //

    if (streamData->is->isMemoryMapped ())
        buffer = streamData->is->readMemoryMapped (dataSize);
    else
    {
        // (TODO) check if the packed data size is too big?
        // (TODO) better memory management here. Don't delete buffer everytime.
        if (buffer != 0) delete[] buffer;
        buffer = new char[dataSize];
        streamData->is->read (buffer, dataSize);
    }

    //
    // Keep track of which tile is the next one in
    // the file, so that we can avoid redundant seekg()
    // operations (seekg() can be fairly expensive).
    //

    streamData->currentPosition = tileOffset + 4 * Xdr::size<int>() +
                                  3 * Xdr::size<Int64>()            +
                                  tableSize                         +
                                  dataSize;
}


void
readNextTileData (InputStreamMutex *streamData,
                  DeepTiledInputFile::Data *ifd,
                  int &dx, int &dy,
                  int &lx, int &ly,
                  char * & buffer,
                  Int64 &dataSize,
                  Int64 &unpackedDataSize)
{
    //
    // Read the next tile block from the file
    //

    //
    // Read the first few bytes of the tile (the header).
    //

    Xdr::read <StreamIO> (*streamData->is, dx);
    Xdr::read <StreamIO> (*streamData->is, dy);
    Xdr::read <StreamIO> (*streamData->is, lx);
    Xdr::read <StreamIO> (*streamData->is, ly);

    Int64 tableSize;
    Xdr::read <StreamIO> (*streamData->is, tableSize);

    Xdr::read <StreamIO> (*streamData->is, dataSize);
    Xdr::read <StreamIO> (*streamData->is, unpackedDataSize);

    //
    // Skip the pixel sample count table because we have read this data.
    //

    Xdr::skip <StreamIO> (*streamData->is, tableSize);

    //
    // Read the pixel data.
    //

    streamData->is->read (buffer, dataSize);

    //
    // Keep track of which tile is the next one in
    // the file, so that we can avoid redundant seekg()
    // operations (seekg() can be fairly expensive).
    //

    streamData->currentPosition += 4 * Xdr::size<int>()   +
                                   3 * Xdr::size<Int64>() +
                                   tableSize              +
                                   dataSize;
}


//
// A TileBufferTask encapsulates the task of uncompressing
// a single tile and copying it into the frame buffer.
//

class TileBufferTask : public Task
{
  public:

    TileBufferTask (TaskGroup *group,
                    DeepTiledInputFile::Data *ifd,
                    TileBuffer *tileBuffer);

    virtual ~TileBufferTask ();

    virtual void                execute ();

  private:

    DeepTiledInputFile::Data *      _ifd;
    TileBuffer *                _tileBuffer;
};


TileBufferTask::TileBufferTask
    (TaskGroup *group,
     DeepTiledInputFile::Data *ifd,
     TileBuffer *tileBuffer)
:
    Task (group),
    _ifd (ifd),
    _tileBuffer (tileBuffer)
{
    // empty
}


TileBufferTask::~TileBufferTask ()
{
    //
    // Signal that the tile buffer is now free
    //

    _tileBuffer->post ();
}


void
TileBufferTask::execute ()
{
    try
    {
        //
        // Calculate information about the tile
        //

        Box2i tileRange = OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile (
                _ifd->tileDesc,
                _ifd->minX, _ifd->maxX,
                _ifd->minY, _ifd->maxY,
                _tileBuffer->dx,
                _tileBuffer->dy,
                _tileBuffer->lx,
                _tileBuffer->ly);

        //
        // Get the size of the tile.
        //

        Array<unsigned int> numPixelsPerScanLine;
        numPixelsPerScanLine.resizeErase(tileRange.max.y - tileRange.min.y + 1);

        int sizeOfTile = 0;
        int maxBytesPerTileLine = 0;

        for (int y = tileRange.min.y; y <= tileRange.max.y; y++)
        {
            numPixelsPerScanLine[y - tileRange.min.y] = 0;

            int bytesPerLine = 0;

            for (int x = tileRange.min.x; x <= tileRange.max.x; x++)
            {
                int xOffset = _ifd->sampleCountXTileCoords * tileRange.min.x;
                int yOffset = _ifd->sampleCountYTileCoords * tileRange.min.y;

                int count = _ifd->getSampleCount(x - xOffset, y - yOffset);
                for (unsigned int c = 0; c < _ifd->slices.size(); ++c)
                {
                    sizeOfTile += count * pixelTypeSize(_ifd->slices[c]->typeInFile);
                    bytesPerLine += count * pixelTypeSize(_ifd->slices[c]->typeInFile);
                }
                numPixelsPerScanLine[y - tileRange.min.y] += count;
            }

            if (bytesPerLine > maxBytesPerTileLine)
                maxBytesPerTileLine = bytesPerLine;
        }

        // (TODO) don't do this every time.
        if (_tileBuffer->compressor != 0)
            delete _tileBuffer->compressor;
        _tileBuffer->compressor = newTileCompressor
                                  (_ifd->header.compression(),
                                   maxBytesPerTileLine,
                                   _ifd->tileDesc.ySize,
                                   _ifd->header);

        //
        // Uncompress the data, if necessary
        //

        if (_tileBuffer->compressor && _tileBuffer->dataSize < Int64(sizeOfTile))
        {
            _tileBuffer->format = _tileBuffer->compressor->format();

            _tileBuffer->dataSize = _tileBuffer->compressor->uncompressTile
                (_tileBuffer->buffer, _tileBuffer->dataSize,
                 tileRange, _tileBuffer->uncompressedData);
        }
        else
        {
            //
            // If the line is uncompressed, it's in XDR format,
            // regardless of the compressor's output format.
            //

            _tileBuffer->format = Compressor::XDR;
            _tileBuffer->uncompressedData = _tileBuffer->buffer;
        }

        //
        // Convert the tile of pixel data back from the machine-independent
        // representation, and store the result in the frame buffer.
        //

        const char *readPtr = _tileBuffer->uncompressedData;
                                                        // points to where we
                                                        // read from in the
                                                        // tile block

        //
        // Iterate over the scan lines in the tile.
        //

        for (int y = tileRange.min.y; y <= tileRange.max.y; ++y)
        {
            //
            // Iterate over all image channels.
            //

            for (unsigned int i = 0; i < _ifd->slices.size(); ++i)
            {
                TInSliceInfo &slice = *_ifd->slices[i];

                //
                // These offsets are used to facilitate both
                // absolute and tile-relative pixel coordinates.
                //

                int xOffsetForData = (slice.xTileCoords == 0) ? 0 : tileRange.min.x;
                int yOffsetForData = (slice.yTileCoords == 0) ? 0 : tileRange.min.y;
                int xOffsetForSampleCount =
                        (_ifd->sampleCountXTileCoords == 0) ? 0 : tileRange.min.x;
                int yOffsetForSampleCount =
                        (_ifd->sampleCountYTileCoords == 0) ? 0 : tileRange.min.y;

                //
                // Fill the frame buffer with pixel data.
                //

                if (slice.skip)
                {
                    //
                    // The file contains data for this channel, but
                    // the frame buffer contains no slice for this channel.
                    //

                    skipChannel (readPtr, slice.typeInFile,
                                 numPixelsPerScanLine[y - tileRange.min.y]);
                }
                else
                {
                    //
                    // The frame buffer contains a slice for this channel.
                    //

                    copyIntoDeepFrameBuffer (readPtr, slice.pointerArrayBase,
                                             _ifd->sampleCountSliceBase,
                                             _ifd->sampleCountXStride,
                                             _ifd->sampleCountYStride,
                                             y,
                                             tileRange.min.x,
                                             tileRange.max.x,
                                             xOffsetForSampleCount, yOffsetForSampleCount,
                                             xOffsetForData, yOffsetForData,
                                             slice.sampleStride, 
                                             slice.xStride,
                                             slice.yStride,
                                             slice.fill,
                                             slice.fillValue, _tileBuffer->format,
                                             slice.typeInFrameBuffer,
                                             slice.typeInFile);
                }
            }
        }
    }
    catch (std::exception &e)
    {
        if (!_tileBuffer->hasException)
        {
            _tileBuffer->exception = e.what ();
            _tileBuffer->hasException = true;
        }
    }
    catch (...)
    {
        if (!_tileBuffer->hasException)
        {
            _tileBuffer->exception = "unrecognized exception";
            _tileBuffer->hasException = true;
        }
    }
}


TileBufferTask *
newTileBufferTask
    (TaskGroup *group,
     DeepTiledInputFile::Data *ifd,
     int number,
     int dx, int dy,
     int lx, int ly)
{
    //
    // Wait for a tile buffer to become available,
    // fill the buffer with raw data from the file,
    // and create a new TileBufferTask whose execute()
    // method will uncompress the tile and copy the
    // tile's pixels into the frame buffer.
    //

    TileBuffer *tileBuffer = ifd->getTileBuffer (number);

    try
    {
        tileBuffer->wait();

        tileBuffer->dx = dx;
        tileBuffer->dy = dy;
        tileBuffer->lx = lx;
        tileBuffer->ly = ly;

        tileBuffer->uncompressedData = 0;

        readTileData (ifd->_streamData, ifd, dx, dy, lx, ly,
                      tileBuffer->buffer,
                      tileBuffer->dataSize,
                      tileBuffer->uncompressedDataSize);
    }
    catch (...)
    {
        //
        // Reading from the file caused an exception.
        // Signal that the tile buffer is free, and
        // re-throw the exception.
        //

        tileBuffer->post();
        throw;
    }

    return new TileBufferTask (group, ifd, tileBuffer);
}


} // namespace


DeepTiledInputFile::DeepTiledInputFile (const char fileName[], int numThreads):
    _data (new Data (numThreads))
{
    _data->_deleteStream=true;
    //
    // This constructor is called when a user
    // explicitly wants to read a tiled file.
    //

    IStream* is = 0;
    try
    {
        is = new StdIFStream (fileName);
        readMagicNumberAndVersionField(*is, _data->version);

        //
        // Compatibility to read multpart file.
        //
        if (isMultiPart(_data->version))
        {
            compatibilityInitialize(*is);
        }
        else
        {
            _data->_streamData = new InputStreamMutex();
            _data->_streamData->is = is;
            _data->header.readFrom (*_data->_streamData->is, _data->version);
            initialize();
            _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,true);
            _data->_streamData->currentPosition = _data->_streamData->is->tellg();
        }
    }
    catch (IEX_NAMESPACE::BaseExc &e)
    {
        if (is)          delete is;
        if (_data && !_data->multiPartBackwardSupport && _data->_streamData) delete _data->_streamData;
        if (_data)       delete _data;

        REPLACE_EXC (e, "Cannot open image file "
                     "\"" << fileName << "\". " << e.what());
        throw;
    }
    catch (...)
    {
        if (is)          delete is;
        if (_data && !_data->multiPartBackwardSupport && _data->_streamData) delete _data->_streamData;
        if (_data)       delete _data;

        throw;
    }
}


DeepTiledInputFile::DeepTiledInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int numThreads):
    _data (new Data (numThreads))
{
    _data->_streamData=0;
    _data->_deleteStream=false;
    
    //
    // This constructor is called when a user
    // explicitly wants to read a tiled file.
    //

    try
    {
        readMagicNumberAndVersionField(is, _data->version);

        //
        // Backward compatibility to read multpart file.
        //
        if (isMultiPart(_data->version))
        {
            compatibilityInitialize(is);
        }
        else
        {
            _data->_streamData = new InputStreamMutex();
            _data->_streamData->is = &is;
            _data->header.readFrom (*_data->_streamData->is, _data->version);
            initialize();
            // file is guaranteed not to be multipart, but is deep
            _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete, false,true);
            _data->memoryMapped = _data->_streamData->is->isMemoryMapped();
            _data->_streamData->currentPosition = _data->_streamData->is->tellg();
        }
    }
    catch (IEX_NAMESPACE::BaseExc &e)
    {
        if (_data && !_data->multiPartBackwardSupport && _data->_streamData) delete _data->_streamData;
        if (_data)       delete _data;

        REPLACE_EXC (e, "Cannot open image file "
                     "\"" << is.fileName() << "\". " << e.what());
        throw;
    }
    catch (...)
    {
        if (_data && !_data->multiPartBackwardSupport && _data->_streamData) delete _data->_streamData;
        if (_data)       delete _data;

        throw;
    }
}


DeepTiledInputFile::DeepTiledInputFile (const Header &header,
                                        OPENEXR_IMF_INTERNAL_NAMESPACE::IStream *is,
                                        int version,
                                        int numThreads) :
    _data (new Data (numThreads))
    
{
    _data->_streamData->is = is;
    _data->_deleteStream=false;
    
    //
    // This constructor called by class Imf::InputFile
    // when a user wants to just read an image file, and
    // doesn't care or know if the file is tiled.
    // No need to have backward compatibility here, because
    // we have the header.
    //

    _data->header = header;
    _data->version = version;
    initialize();
    _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,true);
    _data->memoryMapped = is->isMemoryMapped();
    _data->_streamData->currentPosition = _data->_streamData->is->tellg();
}


DeepTiledInputFile::DeepTiledInputFile (InputPartData* part) :
    _data (new Data (part->numThreads))
{
    _data->_deleteStream=false;
    multiPartInitialize(part);
}


void
DeepTiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is)
{
    is.seekg(0);
    //
    // Construct a MultiPartInputFile, initialize TiledInputFile
    // with the part 0 data.
    // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later.
    //
    _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads);
    _data->multiPartBackwardSupport = true;
    InputPartData* part = _data->multiPartFile->getPart(0);

    multiPartInitialize(part);
}


void
DeepTiledInputFile::multiPartInitialize(InputPartData* part)
{
    if (isTiled(part->header.type()) == false)
        THROW (IEX_NAMESPACE::ArgExc, "Can't build a DeepTiledInputFile from a part of type " << part->header.type());

    _data->_streamData = part->mutex;
    _data->header = part->header;
    _data->version = part->version;
    _data->partNumber = part->partNumber;
    _data->memoryMapped = _data->_streamData->is->isMemoryMapped();
    initialize();
    _data->tileOffsets.readFrom(part->chunkOffsets , _data->fileIsComplete);
    _data->_streamData->currentPosition = _data->_streamData->is->tellg();
}


void
DeepTiledInputFile::initialize ()
{
    if (_data->partNumber == -1)
        if (_data->header.type() != DEEPTILE)
            throw IEX_NAMESPACE::ArgExc ("Expected a deep tiled file but the file is not deep tiled.");
   if(_data->header.version()!=1)
   {
       THROW(IEX_NAMESPACE::ArgExc, "Version " << _data->header.version() << " not supported for deeptiled images in this version of the library");
   }
        
    _data->header.sanityCheck (true);

    _data->tileDesc = _data->header.tileDescription();
    _data->lineOrder = _data->header.lineOrder();

    //
    // Save the dataWindow information
    //

    const Box2i &dataWindow = _data->header.dataWindow();
    _data->minX = dataWindow.min.x;
    _data->maxX = dataWindow.max.x;
    _data->minY = dataWindow.min.y;
    _data->maxY = dataWindow.max.y;

    //
    // Precompute level and tile information to speed up utility functions
    //

    precalculateTileInfo (_data->tileDesc,
                          _data->minX, _data->maxX,
                          _data->minY, _data->maxY,
                          _data->numXTiles, _data->numYTiles,
                          _data->numXLevels, _data->numYLevels);

    //
    // Create all the TileBuffers and allocate their internal buffers
    //

    _data->tileOffsets = TileOffsets (_data->tileDesc.mode,
                                      _data->numXLevels,
                                      _data->numYLevels,
                                      _data->numXTiles,
                                      _data->numYTiles);

    for (size_t i = 0; i < _data->tileBuffers.size(); i++)
        _data->tileBuffers[i] = new TileBuffer ();

    _data->maxSampleCountTableSize = _data->tileDesc.ySize *
                                     _data->tileDesc.xSize *
                                     sizeof(int);

    _data->sampleCountTableBuffer.resizeErase(_data->maxSampleCountTableSize);

    _data->sampleCountTableComp = newCompressor(_data->header.compression(),
                                                _data->maxSampleCountTableSize,
                                                _data->header);
                                                
                                                
    const ChannelList & c=_data->header.channels();
    _data->combinedSampleSize=0;
    for(ChannelList::ConstIterator i=c.begin();i!=c.end();i++)
    {
        switch( i.channel().type )
        {
            case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF  :
                _data->combinedSampleSize+=Xdr::size<half>();
                break;
            case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT :
                _data->combinedSampleSize+=Xdr::size<float>();
                break;
            case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT  :
                _data->combinedSampleSize+=Xdr::size<unsigned int>();
                break;
            default :
                THROW(IEX_NAMESPACE::ArgExc, "Bad type for channel " << i.name() << " initializing deepscanline reader");
        }
    }
                                                  
}


DeepTiledInputFile::~DeepTiledInputFile ()
{
    if (!_data->memoryMapped)
        for (size_t i = 0; i < _data->tileBuffers.size(); i++)
            if (_data->tileBuffers[i]->buffer != 0)
                delete [] _data->tileBuffers[i]->buffer;

    if (_data->_deleteStream)
        delete _data->_streamData->is;

    //
    // (TODO) we should have a way to tell if the stream data is owned by this file or
    // by a parent multipart file.
    //

    if (_data->partNumber == -1)
        delete _data->_streamData;

    delete _data;
}


const char *
DeepTiledInputFile::fileName () const
{
    return _data->_streamData->is->fileName();
}


const Header &
DeepTiledInputFile::header () const
{
    return _data->header;
}


int
DeepTiledInputFile::version () const
{
    return _data->version;
}


void
DeepTiledInputFile::setFrameBuffer (const DeepFrameBuffer &frameBuffer)
{
    Lock lock (*_data->_streamData);

    //
    // Set the frame buffer
    //

    //
    // Check if the new frame buffer descriptor is
    // compatible with the image file header.
    //

    const ChannelList &channels = _data->header.channels();

    for (DeepFrameBuffer::ConstIterator j = frameBuffer.begin();
         j != frameBuffer.end();
         ++j)
    {
        ChannelList::ConstIterator i = channels.find (j.name());

        if (i == channels.end())
            continue;

        if (i.channel().xSampling != j.slice().xSampling ||
            i.channel().ySampling != j.slice().ySampling)
            THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors "
                                "of \"" << i.name() << "\" channel "
                                "of input file \"" << fileName() << "\" are "
                                "not compatible with the frame buffer's "
                                "subsampling factors.");
    }

    //
    // Store the pixel sample count table.
    // (TODO) Support for different sampling rates?
    //

    const Slice& sampleCountSlice = frameBuffer.getSampleCountSlice();
    if (sampleCountSlice.base == 0)
    {
        throw IEX_NAMESPACE::ArgExc ("Invalid base pointer, please set a proper sample count slice.");
    }
    else
    {
        _data->sampleCountSliceBase = sampleCountSlice.base;
        _data->sampleCountXStride = sampleCountSlice.xStride;
        _data->sampleCountYStride = sampleCountSlice.yStride;
        _data->sampleCountXTileCoords = sampleCountSlice.xTileCoords;
        _data->sampleCountYTileCoords = sampleCountSlice.yTileCoords;
    }

    //
    // Initialize the slice table for readPixels().
    //

    vector<TInSliceInfo*> slices;
    ChannelList::ConstIterator i = channels.begin();

    for (DeepFrameBuffer::ConstIterator j = frameBuffer.begin();
         j != frameBuffer.end();
         ++j)
    {
        while (i != channels.end() && strcmp (i.name(), j.name()) < 0)
        {
            //
            // Channel i is present in the file but not
            // in the frame buffer; data for channel i
            // will be skipped during readPixels().
            //

            slices.push_back (new TInSliceInfo (i.channel().type,
                                                NULL,
                                                i.channel().type,
                                                0,      // xStride
                                                0,      // yStride
                                                0,      // sampleStride
                                                false,  // fill
                                                true,   // skip
                                                0.0));  // fillValue
            ++i;
        }

        bool fill = false;

        if (i == channels.end() || strcmp (i.name(), j.name()) > 0)
        {
            //
            // Channel i is present in the frame buffer, but not in the file.
            // In the frame buffer, slice j will be filled with a default value.
            //

            fill = true;
        }

        slices.push_back (new TInSliceInfo (j.slice().type,
                                            j.slice().base,
                                            fill? j.slice().type: i.channel().type,
                                            j.slice().xStride,
                                            j.slice().yStride,
                                            j.slice().sampleStride,
                                            fill,
                                            false, // skip
                                            j.slice().fillValue,
                                            (j.slice().xTileCoords)? 1: 0,
                                            (j.slice().yTileCoords)? 1: 0));


        if (i != channels.end() && !fill)
            ++i;
    }

    // (TODO) inspect the following code. It's additional to the scanline input file.
    // Is this needed?

    while (i != channels.end())
    {
        //
        // Channel i is present in the file but not
        // in the frame buffer; data for channel i
        // will be skipped during readPixels().
        //

        slices.push_back (new TInSliceInfo (i.channel().type,
                                            NULL,
                                            i.channel().type,
                                            0, // xStride
                                            0, // yStride
                                            0, // sampleStride
                                            false,  // fill
                                            true, // skip
                                            0.0)); // fillValue
        ++i;
    }

    //
    // Store the new frame buffer.
    //

    _data->frameBuffer = frameBuffer;

    for (size_t i = 0; i < _data->slices.size(); i++)
        delete _data->slices[i];
    _data->slices = slices;
}


const DeepFrameBuffer &
DeepTiledInputFile::frameBuffer () const
{
    Lock lock (*_data->_streamData);
    return _data->frameBuffer;
}


bool
DeepTiledInputFile::isComplete () const
{
    return _data->fileIsComplete;
}


void
DeepTiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int lx, int ly)
{
    //
    // Read a range of tiles from the file into the framebuffer
    //

    try
    {
        Lock lock (*_data->_streamData);

        if (_data->slices.size() == 0)
            throw IEX_NAMESPACE::ArgExc ("No frame buffer specified "
                               "as pixel data destination.");

        if (!isValidLevel (lx, ly))
            THROW (IEX_NAMESPACE::ArgExc,
                   "Level coordinate "
                   "(" << lx << ", " << ly << ") "
                   "is invalid.");

        //
        // Determine the first and last tile coordinates in both dimensions.
        // We always attempt to read the range of tiles in the order that
        // they are stored in the file.
        //

        if (dx1 > dx2)
            std::swap (dx1, dx2);

        if (dy1 > dy2)
            std::swap (dy1, dy2);

        int dyStart = dy1;
        int dyStop  = dy2 + 1;
        int dY      = 1;

        if (_data->lineOrder == DECREASING_Y)
        {
            dyStart = dy2;
            dyStop  = dy1 - 1;
            dY      = -1;
        }

        //
        // Create a task group for all tile buffer tasks.  When the
        // task group goes out of scope, the destructor waits until
        // all tasks are complete.
        //

        {
            TaskGroup taskGroup;
            int tileNumber = 0;

            for (int dy = dyStart; dy != dyStop; dy += dY)
            {
                for (int dx = dx1; dx <= dx2; dx++)
                {
                    if (!isValidTile (dx, dy, lx, ly))
                        THROW (IEX_NAMESPACE::ArgExc,
                               "Tile (" << dx << ", " << dy << ", " <<
                               lx << "," << ly << ") is not a valid tile.");

                    ThreadPool::addGlobalTask (newTileBufferTask (&taskGroup,
                                                                  _data,
                                                                  tileNumber++,
                                                                  dx, dy,
                                                                  lx, ly));
                }
            }

            //
            // finish all tasks
            //
        }

        //
        // Exeption handling:
        //
        // TileBufferTask::execute() may have encountered exceptions, but
        // those exceptions occurred in another thread, not in the thread
        // that is executing this call to TiledInputFile::readTiles().
        // TileBufferTask::execute() has caught all exceptions and stored
        // the exceptions' what() strings in the tile buffers.
        // Now we check if any tile buffer contains a stored exception; if
        // this is the case then we re-throw the exception in this thread.
        // (It is possible that multiple tile buffers contain stored
        // exceptions.  We re-throw the first exception we find and
        // ignore all others.)
        //

        const string *exception = 0;

        for (size_t i = 0; i < _data->tileBuffers.size(); ++i)
        {
            TileBuffer *tileBuffer = _data->tileBuffers[i];

            if (tileBuffer->hasException && !exception)
                exception = &tileBuffer->exception;

            tileBuffer->hasException = false;
        }

        if (exception)
            throw IEX_NAMESPACE::IoExc (*exception);
    }
    catch (IEX_NAMESPACE::BaseExc &e)
    {
        REPLACE_EXC (e, "Error reading pixel data from image "
                     "file \"" << fileName() << "\". " << e.what());
        throw;
    }
}


void
DeepTiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int l)
{
    readTiles (dx1, dx2, dy1, dy2, l, l);
}


void
DeepTiledInputFile::readTile (int dx, int dy, int lx, int ly)
{
    readTiles (dx, dx, dy, dy, lx, ly);
}


void
DeepTiledInputFile::readTile (int dx, int dy, int l)
{
    readTile (dx, dy, l, l);
}


void
DeepTiledInputFile::rawTileData (int &dx, int &dy,
                             int &lx, int &ly,
                             char * pixelData,
                             Int64 &pixelDataSize) const
{
     if (!isValidTile (dx, dy, lx, ly))
               throw IEX_NAMESPACE::ArgExc ("Tried to read a tile outside "
                                   "the image file's data window.");
    
     Int64 tileOffset = _data->tileOffsets (dx, dy, lx, ly);
                                   
     if(tileOffset == 0)
     {
        THROW (IEX_NAMESPACE::InputExc, "Tile (" << dx << ", " << dy << ", " <<
        lx << ", " << ly << ") is missing.");
     }
     
     Lock lock(*_data->_streamData);
                                   
     if (_data->_streamData->is->tellg() != tileOffset)
                                          _data->_streamData->is->seekg (tileOffset);
                                   
     
     //
     // Read the first few bytes of the tile (the header).
     // Verify that the tile coordinates and the level number
     // are correct.
     //
     
     int tileXCoord, tileYCoord, levelX, levelY;
     
     if (isMultiPart(_data->version))
     {
         int partNumber;
         Xdr::read <StreamIO> (*_data->_streamData->is, partNumber);
         if (partNumber != _data->partNumber)
         {
             THROW (IEX_NAMESPACE::ArgExc, "Unexpected part number " << partNumber
             << ", should be " << _data->partNumber << ".");
         }
     }
     
     Xdr::read <StreamIO> (*_data->_streamData->is, tileXCoord);
     Xdr::read <StreamIO> (*_data->_streamData->is, tileYCoord);
     Xdr::read <StreamIO> (*_data->_streamData->is, levelX);
     Xdr::read <StreamIO> (*_data->_streamData->is, levelY);
     
     Int64 sampleCountTableSize;
     Int64 packedDataSize;
     Xdr::read <StreamIO> (*_data->_streamData->is, sampleCountTableSize);
     
     Xdr::read <StreamIO> (*_data->_streamData->is, packedDataSize);
     
          
     
     if (tileXCoord != dx)
         throw IEX_NAMESPACE::InputExc ("Unexpected tile x coordinate.");
     
     if (tileYCoord != dy)
         throw IEX_NAMESPACE::InputExc ("Unexpected tile y coordinate.");
     
     if (levelX != lx)
         throw IEX_NAMESPACE::InputExc ("Unexpected tile x level number coordinate.");
     
     if (levelY != ly)
         throw IEX_NAMESPACE::InputExc ("Unexpected tile y level number coordinate.");
     
     
     // total requirement for reading all the data
     
     Int64 totalSizeRequired=40+sampleCountTableSize+packedDataSize;
     
     bool big_enough = totalSizeRequired<=pixelDataSize;
     
     pixelDataSize = totalSizeRequired;
     
     // was the block we were given big enough?
     if(!big_enough || pixelData==NULL)
     {        
         // special case: seek stream back to start if we are at the beginning (regular reading pixels assumes it doesn't need to seek
         // in single part files)
         if(!isMultiPart(_data->version))
         {
             _data->_streamData->is->seekg(_data->_streamData->currentPosition); 
         }
         // leave lock here - bail before reading more data
         return;
     }
     
     // copy the values we have read into the output block
     *(int *) (pixelData+0) = dx;
     *(int *) (pixelData+4) = dy;
     *(int *) (pixelData+8) = levelX;
     *(int *) (pixelData+12) = levelY;
     *(Int64 *) (pixelData+16) =sampleCountTableSize;
     *(Int64 *) (pixelData+24) = packedDataSize;
     
     // didn't read the unpackedsize - do that now
     Xdr::read<StreamIO> (*_data->_streamData->is, *(Int64 *) (pixelData+32));
     
     // read the actual data
     _data->_streamData->is->read(pixelData+40, sampleCountTableSize+packedDataSize);
     
     
     if(!isMultiPart(_data->version))
     {
         _data->_streamData->currentPosition+=sampleCountTableSize+packedDataSize+40;
     }
     
     // leave lock here
     
     
}


unsigned int
DeepTiledInputFile::tileXSize () const
{
    return _data->tileDesc.xSize;
}


unsigned int
DeepTiledInputFile::tileYSize () const
{
    return _data->tileDesc.ySize;
}


LevelMode
DeepTiledInputFile::levelMode () const
{
    return _data->tileDesc.mode;
}


LevelRoundingMode
DeepTiledInputFile::levelRoundingMode () const
{
    return _data->tileDesc.roundingMode;
}


int
DeepTiledInputFile::numLevels () const
{
    if (levelMode() == RIPMAP_LEVELS)
        THROW (IEX_NAMESPACE::LogicExc, "Error calling numLevels() on image "
                              "file \"" << fileName() << "\" "
                              "(numLevels() is not defined for files "
                              "with RIPMAP level mode).");

    return _data->numXLevels;
}


int
DeepTiledInputFile::numXLevels () const
{
    return _data->numXLevels;
}


int
DeepTiledInputFile::numYLevels () const
{
    return _data->numYLevels;
}


bool
DeepTiledInputFile::isValidLevel (int lx, int ly) const
{
    if (lx < 0 || ly < 0)
        return false;

    if (levelMode() == MIPMAP_LEVELS && lx != ly)
        return false;

    if (lx >= numXLevels() || ly >= numYLevels())
        return false;

    return true;
}


int
DeepTiledInputFile::levelWidth (int lx) const
{
    try
    {
        return levelSize (_data->minX, _data->maxX, lx,
                          _data->tileDesc.roundingMode);
    }
    catch (IEX_NAMESPACE::BaseExc &e)
    {
        REPLACE_EXC (e, "Error calling levelWidth() on image "
                     "file \"" << fileName() << "\". " << e.what());
        throw;
    }
}


int
DeepTiledInputFile::levelHeight (int ly) const
{
    try
    {
        return levelSize (_data->minY, _data->maxY, ly,
                          _data->tileDesc.roundingMode);
    }
    catch (IEX_NAMESPACE::BaseExc &e)
    {
        REPLACE_EXC (e, "Error calling levelHeight() on image "
                     "file \"" << fileName() << "\". " << e.what());
        throw;
    }
}


int
DeepTiledInputFile::numXTiles (int lx) const
{
    if (lx < 0 || lx >= _data->numXLevels)
    {
        THROW (IEX_NAMESPACE::ArgExc, "Error calling numXTiles() on image "
                            "file \"" << _data->_streamData->is->fileName() << "\" "
                            "(Argument is not in valid range).");

    }

    return _data->numXTiles[lx];
}


int
DeepTiledInputFile::numYTiles (int ly) const
{
    if (ly < 0 || ly >= _data->numYLevels)
    {
        THROW (IEX_NAMESPACE::ArgExc, "Error calling numYTiles() on image "
                            "file \"" << _data->_streamData->is->fileName() << "\" "
                            "(Argument is not in valid range).");
    }

    return _data->numYTiles[ly];
}


Box2i
DeepTiledInputFile::dataWindowForLevel (int l) const
{
    return dataWindowForLevel (l, l);
}


Box2i
DeepTiledInputFile::dataWindowForLevel (int lx, int ly) const
{
    try
    {
        return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForLevel (
                _data->tileDesc,
                _data->minX, _data->maxX,
                _data->minY, _data->maxY,
                lx, ly);
    }
    catch (IEX_NAMESPACE::BaseExc &e)
    {
        REPLACE_EXC (e, "Error calling dataWindowForLevel() on image "
                     "file \"" << fileName() << "\". " << e.what());
        throw;
    }
}


Box2i
DeepTiledInputFile::dataWindowForTile (int dx, int dy, int l) const
{
    return dataWindowForTile (dx, dy, l, l);
}


Box2i
DeepTiledInputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const
{
    try
    {
        if (!isValidTile (dx, dy, lx, ly))
            throw IEX_NAMESPACE::ArgExc ("Arguments not in valid range.");

        return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile (
                _data->tileDesc,
                _data->minX, _data->maxX,
                _data->minY, _data->maxY,
                dx, dy, lx, ly);
    }
    catch (IEX_NAMESPACE::BaseExc &e)
    {
        REPLACE_EXC (e, "Error calling dataWindowForTile() on image "
                     "file \"" << fileName() << "\". " << e.what());
        throw;
    }
}


bool
DeepTiledInputFile::isValidTile (int dx, int dy, int lx, int ly) const
{
    return ((lx < _data->numXLevels && lx >= 0) &&
            (ly < _data->numYLevels && ly >= 0) &&
            (dx < _data->numXTiles[lx] && dx >= 0) &&
            (dy < _data->numYTiles[ly] && dy >= 0));
}


void
DeepTiledInputFile::readPixelSampleCounts (int dx1, int dx2,
                                           int dy1, int dy2,
                                           int lx,  int ly)
{
    Int64 savedFilePos = 0;

    try
    {
        Lock lock (*_data->_streamData);

        savedFilePos = _data->_streamData->is->tellg();

        
        if (!isValidLevel (lx, ly))
        {
            THROW (IEX_NAMESPACE::ArgExc,
                   "Level coordinate "
                   "(" << lx << ", " << ly << ") "
                   "is invalid.");
        }
        
        if (dx1 > dx2)
            std::swap (dx1, dx2);

        if (dy1 > dy2)
            std::swap (dy1, dy2);

        int dyStart = dy1;
        int dyStop  = dy2 + 1;
        int dY      = 1;

        if (_data->lineOrder == DECREASING_Y)
        {
            dyStart = dy2;
            dyStop  = dy1 - 1;
            dY      = -1;
        }

        // (TODO) Check if we have read the sample counts for those tiles,
        // if we have, no need to read again.
        for (int dy = dyStart; dy != dyStop; dy += dY)
        {
            for (int dx = dx1; dx <= dx2; dx++)
            {
                
                if (!isValidTile (dx, dy, lx, ly))
                {
                    THROW (IEX_NAMESPACE::ArgExc,
                           "Tile (" << dx << ", " << dy << ", " <<
                           lx << "," << ly << ") is not a valid tile.");
                }
                
                Box2i tileRange = OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile (
                        _data->tileDesc,
                        _data->minX, _data->maxX,
                        _data->minY, _data->maxY,
                        dx, dy, lx, ly);

                int xOffset = _data->sampleCountXTileCoords * tileRange.min.x;
                int yOffset = _data->sampleCountYTileCoords * tileRange.min.y;

                //
                // Skip and check the tile coordinates.
                //

                _data->_streamData->is->seekg(_data->tileOffsets(dx, dy, lx, ly));

                if (isMultiPart(_data->version))
                {
                    int partNumber;
                    Xdr::read <StreamIO> (*_data->_streamData->is, partNumber);

                    if (partNumber != _data->partNumber)
                        throw IEX_NAMESPACE::InputExc ("Unexpected part number.");
                }

                int xInFile, yInFile, lxInFile, lyInFile;
                Xdr::read <StreamIO> (*_data->_streamData->is, xInFile);
                Xdr::read <StreamIO> (*_data->_streamData->is, yInFile);
                Xdr::read <StreamIO> (*_data->_streamData->is, lxInFile);
                Xdr::read <StreamIO> (*_data->_streamData->is, lyInFile);

                if (xInFile != dx)
                    throw IEX_NAMESPACE::InputExc ("Unexpected tile x coordinate.");

                if (yInFile != dy)
                    throw IEX_NAMESPACE::InputExc ("Unexpected tile y coordinate.");

                if (lxInFile != lx)
                    throw IEX_NAMESPACE::InputExc ("Unexpected tile x level number coordinate.");

                if (lyInFile != ly)
                    throw IEX_NAMESPACE::InputExc ("Unexpected tile y level number coordinate.");

                Int64 tableSize, dataSize, unpackedDataSize;
                Xdr::read <StreamIO> (*_data->_streamData->is, tableSize);
                Xdr::read <StreamIO> (*_data->_streamData->is, dataSize);
                Xdr::read <StreamIO> (*_data->_streamData->is, unpackedDataSize);

                
                if(tableSize>_data->maxSampleCountTableSize)
                {
                    THROW (IEX_NAMESPACE::ArgExc, "Bad sampleCountTableDataSize read from tile "<< dx << ',' << dy << ',' << lx << ',' << ly << ": expected " << _data->maxSampleCountTableSize << " or less, got "<< tableSize);
                }
                    
                
                //
                // We make a check on the data size requirements here.
                // Whilst we wish to store 64bit sizes on disk, not all the compressors
                // have been made to work with such data sizes and are still limited to
                // using signed 32 bit (int) for the data size. As such, this version
                // insists that we validate that the data size does not exceed the data
                // type max limit.
                // @TODO refactor the compressor code to ensure full 64-bit support.
                //

                Int64 compressorMaxDataSize = Int64(std::numeric_limits<int>::max());
                if (dataSize         > compressorMaxDataSize ||
                    unpackedDataSize > compressorMaxDataSize ||
                    tableSize        > compressorMaxDataSize)
                {
                    THROW (IEX_NAMESPACE::ArgExc, "This version of the library does not"
                          << "support the allocation of data with size  > "
                          << compressorMaxDataSize
                          << " file table size    :" << tableSize
                          << " file unpacked size :" << unpackedDataSize
                          << " file packed size   :" << dataSize << ".\n");
                }

                //
                // Read and uncompress the pixel sample count table.
                //

                _data->_streamData->is->read(_data->sampleCountTableBuffer, tableSize);

                const char* readPtr;

                if (tableSize < _data->maxSampleCountTableSize)
                {
                    if(!_data->sampleCountTableComp)
                    {
                        THROW(IEX_NAMESPACE::ArgExc,"Deep scanline data corrupt at tile " << dx << ',' << dy << ',' << lx << ',' <<  ly << " (sampleCountTableDataSize error)");
                    }
                    _data->sampleCountTableComp->uncompress(_data->sampleCountTableBuffer,
                                                            tableSize,
                                                            tileRange.min.y,
                                                            readPtr);
                }
                else
                    readPtr = _data->sampleCountTableBuffer;

                size_t cumulative_total_samples =0;
                int lastAccumulatedCount;
                for (int j = tileRange.min.y; j <= tileRange.max.y; j++)
                {
                    lastAccumulatedCount = 0;
                    for (int i = tileRange.min.x; i <= tileRange.max.x; i++)
                    {
                        int accumulatedCount;
                        Xdr::read <CharPtrIO> (readPtr, accumulatedCount);
                        
                        if (accumulatedCount < lastAccumulatedCount)
                        {
                            THROW(IEX_NAMESPACE::ArgExc,"Deep tile sampleCount data corrupt at tile " 
                                  << dx << ',' << dy << ',' << lx << ',' <<  ly << " (negative sample count detected)");
                        }

                        int count = accumulatedCount - lastAccumulatedCount;
                        lastAccumulatedCount = accumulatedCount;
                        
                        _data->getSampleCount(i - xOffset, j - yOffset) =count;
                    }
                    cumulative_total_samples += lastAccumulatedCount;
                }
                
                if(cumulative_total_samples * _data->combinedSampleSize > unpackedDataSize)
                {
                    THROW(IEX_NAMESPACE::ArgExc,"Deep scanline sampleCount data corrupt at tile " 
                                                << dx << ',' << dy << ',' << lx << ',' <<  ly 
                                                << ": pixel data only contains " << unpackedDataSize 
                                                << " bytes of data but table references at least " 
                                                << cumulative_total_samples*_data->combinedSampleSize << " bytes of sample data" );            
                }
                    
            }
        }

        _data->_streamData->is->seekg(savedFilePos);
    }
    catch (IEX_NAMESPACE::BaseExc &e)
    {
        REPLACE_EXC (e, "Error reading sample count data from image "
                     "file \"" << fileName() << "\". " << e.what());

         _data->_streamData->is->seekg(savedFilePos);

        throw;
    }
}


void
DeepTiledInputFile::readPixelSampleCount (int dx, int dy, int l)
{
    readPixelSampleCount (dx, dy, l, l);
}


void
DeepTiledInputFile::readPixelSampleCount (int dx, int dy, int lx, int ly)
{
    readPixelSampleCounts (dx, dx, dy, dy, lx, ly);
}


void
DeepTiledInputFile::readPixelSampleCounts (int dx1, int dx2,
                                           int dy1, int dy2,
                                           int l)
{
    readPixelSampleCounts (dx1, dx2, dy1, dy2, l, l);
}


size_t
DeepTiledInputFile::totalTiles() const
{
    //
    // Calculate the total number of tiles in the file
    //
    
    int numAllTiles = 0;
    
    switch (levelMode ())
    {
        case ONE_LEVEL:
        case MIPMAP_LEVELS:
            
            for (int i_l = 0; i_l < numLevels (); ++i_l)
                numAllTiles += numXTiles (i_l) * numYTiles (i_l);
            
            break;
            
        case RIPMAP_LEVELS:
            
            for (int i_ly = 0; i_ly < numYLevels (); ++i_ly)
                for (int i_lx = 0; i_lx < numXLevels (); ++i_lx)
                    numAllTiles += numXTiles (i_lx) * numYTiles (i_ly);
                
                break;
            
        default:
            
            throw IEX_NAMESPACE::ArgExc ("Unknown LevelMode format.");
    }
    return numAllTiles;
}




void 
DeepTiledInputFile::getTileOrder(int dx[],int dy[],int lx[],int ly[]) const
{
  return _data->tileOffsets.getTileOrder(dx,dy,lx,ly);
  
}

OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT