ImfTiledOutputFile.cpp 42.2 KB
Newer Older
wester committed
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
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, 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 TiledOutputFile
//
//-----------------------------------------------------------------------------

#include <ImfTiledOutputFile.h>
#include <ImfTiledInputFile.h>
#include <ImfInputFile.h>
#include <ImfTileDescriptionAttribute.h>
#include <ImfPreviewImageAttribute.h>
#include <ImfChannelList.h>
#include <ImfMisc.h>
#include <ImfTiledMisc.h>
#include <ImfStdIO.h>
#include <ImfCompressor.h>
#include "ImathBox.h"
#include <ImfArray.h>
#include <ImfXdr.h>
#include <ImfVersion.h>
#include <ImfTileOffsets.h>
#include <ImfThreading.h>
#include "IlmThreadPool.h"
#include "IlmThreadSemaphore.h"
#include "IlmThreadMutex.h"
#include "Iex.h"
#include <string>
#include <vector>
#include <fstream>
#include <assert.h>
#include <map>
#include <algorithm> // for std::max()


namespace Imf {

using Imath::Box2i;
using Imath::V2i;
using std::string;
using std::vector;
using std::ofstream;
using std::map;
using std::min;
using std::max;
using std::swap;
using IlmThread::Mutex;
using IlmThread::Lock;
using IlmThread::Semaphore;
using IlmThread::Task;
using IlmThread::TaskGroup;
using IlmThread::ThreadPool;

namespace {

struct TOutSliceInfo
{
    PixelType		type;
    const char *	base;
    size_t		xStride;
    size_t		yStride;
    bool		zero;
    int                 xTileCoords;
    int                 yTileCoords;

    TOutSliceInfo (PixelType type = HALF,
               const char *base = 0,
               size_t xStride = 0,
               size_t yStride = 0,
               bool zero = false,
                   int xTileCoords = 0,
                   int yTileCoords = 0);
};


TOutSliceInfo::TOutSliceInfo (PixelType t,
                      const char *b,
                  size_t xs, size_t ys,
                  bool z,
                              int xtc,
                              int ytc)
:
    type (t),
    base (b),
    xStride (xs),
    yStride (ys),
    zero (z),
    xTileCoords (xtc),
    yTileCoords (ytc)
{
    // empty
}


struct TileCoord
{
    int		dx;
    int		dy;
    int		lx;
    int		ly;


    TileCoord (int xTile = 0, int yTile = 0,
           int xLevel = 0, int yLevel = 0)
    :
        dx (xTile),  dy (yTile),
    lx (xLevel), ly (yLevel)
    {
        // empty
    }


    bool
    operator < (const TileCoord &other) const
    {
        return (ly < other.ly) ||
           (ly == other.ly && lx < other.lx) ||
           ((ly == other.ly && lx == other.lx) &&
            ((dy < other.dy) || (dy == other.dy && dx < other.dx)));
    }


    bool
    operator == (const TileCoord &other) const
    {
        return lx == other.lx &&
           ly == other.ly &&
           dx == other.dx &&
           dy == other.dy;
    }
};


struct BufferedTile
{
    char *	pixelData;
    int		pixelDataSize;

    BufferedTile (const char *data, int size):
    pixelData (0),
    pixelDataSize(size)
    {
    pixelData = new char[pixelDataSize];
    memcpy (pixelData, data, pixelDataSize);
    }

    ~BufferedTile()
    {
    delete [] pixelData;
    }
};


typedef map <TileCoord, BufferedTile *> TileMap;


struct TileBuffer
{
    Array<char>		buffer;
    const char *	dataPtr;
    int			dataSize;
    Compressor *	compressor;
    TileCoord		tileCoord;
    bool		hasException;
    string		exception;

     TileBuffer (Compressor *comp);
    ~TileBuffer ();

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

  protected:

    Semaphore		_sem;
};


TileBuffer::TileBuffer (Compressor *comp):
    dataPtr (0),
    dataSize (0),
    compressor (comp),
    hasException (false),
    exception (),
    _sem (1)
{
    // empty
}


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


} // namespace


struct TiledOutputFile::Data: public Mutex
{
    Header		header;			// the image header
    int			version;		// file format version
    TileDescription	tileDesc;		// describes the tile layout
    FrameBuffer		frameBuffer;		// framebuffer to write into
    Int64		previewPosition;
    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

    Compressor::Format	format;			// compressor's data format
    vector<TOutSliceInfo> slices;		// info about channels in file
    OStream *		os;			// file stream to write to
    bool		deleteStream;

    size_t		maxBytesPerTileLine;	// combined size of a tile line
                        // over all channels


    vector<TileBuffer*> tileBuffers;
    size_t		tileBufferSize;         // size of a tile buffer

    Int64		tileOffsetsPosition;	// position of the tile index
    Int64		currentPosition;	// current position in the file

    TileMap		tileMap;
    TileCoord		nextTileToWrite;

     Data (bool del, int numThreads);
    ~Data ();

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

    TileCoord		nextTileCoord (const TileCoord &a);
};


TiledOutputFile::Data::Data (bool del, int numThreads):
    numXTiles(0),
    numYTiles(0),
    os (0),
    deleteStream (del),
    tileOffsetsPosition (0)
{
    //
    // 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));
}


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

    if (deleteStream)
    delete os;

    //
    // Delete all the tile buffers, if any still happen to exist
    //

    for (TileMap::iterator i = tileMap.begin(); i != tileMap.end(); ++i)
    delete i->second;

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


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


TileCoord
TiledOutputFile::Data::nextTileCoord (const TileCoord &a)
{
    TileCoord b = a;

    if (lineOrder == INCREASING_Y)
    {
        b.dx++;

        if (b.dx >= numXTiles[b.lx])
        {
            b.dx = 0;
            b.dy++;

            if (b.dy >= numYTiles[b.ly])
            {
        //
        // the next tile is in the next level
        //

                b.dy = 0;

                switch (tileDesc.mode)
                {
                  case ONE_LEVEL:
                  case MIPMAP_LEVELS:

                    b.lx++;
                    b.ly++;
                    break;

                  case RIPMAP_LEVELS:

                    b.lx++;

                    if (b.lx >= numXLevels)
                    {
                        b.lx = 0;
                        b.ly++;

            #ifdef DEBUG
                assert (b.ly <= numYLevels);
            #endif
                    }
                    break;
                }
            }
        }
    }
    else if (lineOrder == DECREASING_Y)
    {
        b.dx++;

        if (b.dx >= numXTiles[b.lx])
        {
            b.dx = 0;
            b.dy--;

            if (b.dy < 0)
            {
        //
        // the next tile is in the next level
        //

                switch (tileDesc.mode)
                {
                  case ONE_LEVEL:
                  case MIPMAP_LEVELS:

                    b.lx++;
                    b.ly++;
                    break;

                  case RIPMAP_LEVELS:

                    b.lx++;

                    if (b.lx >= numXLevels)
                    {
                        b.lx = 0;
                        b.ly++;

            #ifdef DEBUG
                assert (b.ly <= numYLevels);
            #endif
                    }
                    break;
                }

        if (b.ly < numYLevels)
            b.dy = numYTiles[b.ly] - 1;
            }
        }
    }

    return b;
}


namespace {

void
writeTileData (TiledOutputFile::Data *ofd,
               int dx, int dy,
           int lx, int ly,
               const char pixelData[],
               int pixelDataSize)
{
    //
    // Store a block of pixel data in the output file, and try
    // to keep track of the current writing position the file,
    // without calling tellp() (tellp() can be fairly expensive).
    //

    Int64 currentPosition = ofd->currentPosition;
    ofd->currentPosition = 0;

    if (currentPosition == 0)
        currentPosition = ofd->os->tellp();

    ofd->tileOffsets (dx, dy, lx, ly) = currentPosition;

    #ifdef DEBUG
    assert (ofd->os->tellp() == currentPosition);
    #endif

    //
    // Write the tile header.
    //

    Xdr::write <StreamIO> (*ofd->os, dx);
    Xdr::write <StreamIO> (*ofd->os, dy);
    Xdr::write <StreamIO> (*ofd->os, lx);
    Xdr::write <StreamIO> (*ofd->os, ly);
    Xdr::write <StreamIO> (*ofd->os, pixelDataSize);

    ofd->os->write (pixelData, pixelDataSize);

    //
    // Keep current position in the file so that we can avoid
    // redundant seekg() operations (seekg() can be fairly expensive).
    //

    ofd->currentPosition = currentPosition +
                           5 * Xdr::size<int>() +
                           pixelDataSize;
}



void
bufferedTileWrite (TiledOutputFile::Data *ofd,
                   int dx, int dy,
           int lx, int ly,
                   const char pixelData[],
                   int pixelDataSize)
{
    //
    // Check if a tile with coordinates (dx,dy,lx,ly) has already been written.
    //

    if (ofd->tileOffsets (dx, dy, lx, ly))
    {
    THROW (Iex::ArgExc,
           "Attempt to write tile "
           "(" << dx << ", " << dy << ", " << lx << "," << ly << ") "
           "more than once.");
    }

    //
    // If tiles can be written in random order, then don't buffer anything.
    //

    if (ofd->lineOrder == RANDOM_Y)
    {
        writeTileData (ofd, dx, dy, lx, ly, pixelData, pixelDataSize);
        return;
    }

    //
    // If the tiles cannot be written in random order, then check if a
    // tile with coordinates (dx,dy,lx,ly) has already been buffered.
    //

    TileCoord currentTile = TileCoord(dx, dy, lx, ly);

    if (ofd->tileMap.find (currentTile) != ofd->tileMap.end())
    {
    THROW (Iex::ArgExc,
           "Attempt to write tile "
           "(" << dx << ", " << dy << ", " << lx << "," << ly << ") "
           "more than once.");
    }

    //
    // If all the tiles before this one have already been written to the file,
    // then write this tile immediately and check if we have buffered tiles
    // that can be written after this tile.
    //
    // Otherwise, buffer the tile so it can be written to file later.
    //

    if (ofd->nextTileToWrite == currentTile)
    {
        writeTileData (ofd, dx, dy, lx, ly, pixelData, pixelDataSize);
        ofd->nextTileToWrite = ofd->nextTileCoord (ofd->nextTileToWrite);

        TileMap::iterator i = ofd->tileMap.find (ofd->nextTileToWrite);

        //
        // Step through the tiles and write all successive buffered tiles after
        // the current one.
        //

        while(i != ofd->tileMap.end())
        {
            //
            // Write the tile, and then delete the tile's buffered data
            //

            writeTileData (ofd,
               i->first.dx, i->first.dy,
               i->first.lx, i->first.ly,
               i->second->pixelData,
               i->second->pixelDataSize);

            delete i->second;
            ofd->tileMap.erase (i);

            //
            // Proceed to the next tile
            //

            ofd->nextTileToWrite = ofd->nextTileCoord (ofd->nextTileToWrite);
            i = ofd->tileMap.find (ofd->nextTileToWrite);
        }
    }
    else
    {
        //
        // Create a new BufferedTile, copy the pixelData into it, and
        // insert it into the tileMap.
        //

    ofd->tileMap[currentTile] =
        new BufferedTile ((const char *)pixelData, pixelDataSize);
    }
}


void
convertToXdr (TiledOutputFile::Data *ofd,
              Array<char>& tileBuffer,
          int numScanLines,
          int numPixelsPerScanLine)
{
    //
    // Convert the contents of a TiledOutputFile's tileBuffer from the
    // machine's native representation to Xdr format. This function is called
    // by writeTile(), below, if the compressor wanted its input pixel data
    // in the machine's native format, but then failed to compress the data
    // (most compressors will expand rather than compress random input data).
    //
    // Note that this routine assumes that the machine's native representation
    // of the pixel data has the same size as the Xdr representation.  This
    // makes it possible to convert the pixel data in place, without an
    // intermediate temporary buffer.
    //

    //
    // Set these to point to the start of the tile.
    // We will write to toPtr, and read from fromPtr.
    //

    char *writePtr = tileBuffer;
    const char *readPtr = writePtr;

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

    for (int y = 0; y < numScanLines; ++y)
    {
    //
    // Iterate over all slices in the file.
    //

    for (unsigned int i = 0; i < ofd->slices.size(); ++i)
    {
        const TOutSliceInfo &slice = ofd->slices[i];

        //
        // Convert the samples in place.
        //

            convertInPlace (writePtr, readPtr, slice.type,
                            numPixelsPerScanLine);
    }
    }

    #ifdef DEBUG

    assert (writePtr == readPtr);

    #endif
}


//
// A TileBufferTask encapsulates the task of copying a tile from
// the user's framebuffer into a LineBuffer and compressing the data
// if necessary.
//

class TileBufferTask: public Task
{
  public:

    TileBufferTask (TaskGroup *group,
                    TiledOutputFile::Data *ofd,
                    int number,
            int dx, int dy,
            int lx, int ly);

    virtual ~TileBufferTask ();

    virtual void		execute ();

  private:

    TiledOutputFile::Data *	_ofd;
    TileBuffer *		_tileBuffer;
};


TileBufferTask::TileBufferTask
    (TaskGroup *group,
     TiledOutputFile::Data *ofd,
     int number,
     int dx, int dy,
     int lx, int ly)
:
    Task (group),
    _ofd (ofd),
    _tileBuffer (_ofd->getTileBuffer (number))
{
    //
    // Wait for the tileBuffer to become available
    //

    _tileBuffer->wait ();
    _tileBuffer->tileCoord = TileCoord (dx, dy, lx, ly);
}


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

    _tileBuffer->post ();
}


void
TileBufferTask::execute ()
{
    try
    {
        //
        // First copy the pixel data from the frame buffer
    // into the tile buffer
        //
        // Convert one tile's worth of pixel data to
        // a machine-independent representation, and store
        // the result in _tileBuffer->buffer.
        //

        char *writePtr = _tileBuffer->buffer;

        Box2i tileRange = Imf::dataWindowForTile (_ofd->tileDesc,
                                                  _ofd->minX, _ofd->maxX,
                                                  _ofd->minY, _ofd->maxY,
                                                  _tileBuffer->tileCoord.dx,
                                                  _tileBuffer->tileCoord.dy,
                                                  _tileBuffer->tileCoord.lx,
                                                  _tileBuffer->tileCoord.ly);

        int numScanLines = tileRange.max.y - tileRange.min.y + 1;
        int numPixelsPerScanLine = tileRange.max.x - tileRange.min.x + 1;

        //
        // 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 < _ofd->slices.size(); ++i)
            {
                const TOutSliceInfo &slice = _ofd->slices[i];

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

                int xOffset = slice.xTileCoords * tileRange.min.x;
                int yOffset = slice.yTileCoords * tileRange.min.y;

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

                if (slice.zero)
                {
                    //
                    // The frame buffer contains no data for this channel.
                    // Store zeroes in _data->tileBuffer.
                    //

                    fillChannelWithZeroes (writePtr, _ofd->format, slice.type,
                                           numPixelsPerScanLine);
                }
                else
                {
                    //
                    // The frame buffer contains data for this channel.
                    //

                    const char *readPtr = slice.base +
                                          (y - yOffset) * slice.yStride +
                                          (tileRange.min.x - xOffset) *
                                          slice.xStride;

                    const char *endPtr  = readPtr +
                                          (numPixelsPerScanLine - 1) *
                                          slice.xStride;

                    copyFromFrameBuffer (writePtr, readPtr, endPtr,
                                         slice.xStride, _ofd->format,
                                         slice.type);
                }
            }
        }

        //
        // Compress the contents of the tileBuffer,
        // and store the compressed data in the output file.
        //

        _tileBuffer->dataSize = writePtr - _tileBuffer->buffer;
        _tileBuffer->dataPtr = _tileBuffer->buffer;

        if (_tileBuffer->compressor)
        {
            const char *compPtr;

            int compSize = _tileBuffer->compressor->compressTile
                                                (_tileBuffer->dataPtr,
                                                 _tileBuffer->dataSize,
                                                 tileRange, compPtr);

            if (compSize < _tileBuffer->dataSize)
            {
                _tileBuffer->dataSize = compSize;
                _tileBuffer->dataPtr = compPtr;
            }
            else if (_ofd->format == Compressor::NATIVE)
            {
                //
                // The data did not shrink during compression, but
                // we cannot write to the file using native format,
                // so we need to convert the lineBuffer to Xdr.
                //

                convertToXdr (_ofd, _tileBuffer->buffer, numScanLines,
                              numPixelsPerScanLine);
            }
        }
    }
    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;
        }
    }
}

} // namespace


TiledOutputFile::TiledOutputFile
    (const char fileName[],
     const Header &header,
     int numThreads)
:
    _data (new Data (true, numThreads))
{
    try
    {
    header.sanityCheck (true);
    _data->os = new StdOFStream (fileName);
    initialize (header);
    }
    catch (Iex::BaseExc &e)
    {
    delete _data;

    REPLACE_EXC (e, "Cannot open image file "
            "\"" << fileName << "\". " << e);
    throw;
    }
    catch (...)
    {
    delete _data;
        throw;
    }
}


TiledOutputFile::TiledOutputFile
    (OStream &os,
     const Header &header,
     int numThreads)
:
    _data (new Data (false, numThreads))
{
    try
    {
    header.sanityCheck(true);
    _data->os = &os;
    initialize (header);
    }
    catch (Iex::BaseExc &e)
    {
    delete _data;

    REPLACE_EXC (e, "Cannot open image file "
            "\"" << os.fileName() << "\". " << e);
    throw;
    }
    catch (...)
    {
    delete _data;
        throw;
    }
}


void
TiledOutputFile::initialize (const Header &header)
{
    _data->header = header;
    _data->lineOrder = _data->header.lineOrder();

    //
    // Check that the file is indeed tiled
    //

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

    //
    // 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);

    //
    // Determine the first tile coordinate that we will be writing
    // if the file is not RANDOM_Y.
    //

    _data->nextTileToWrite = (_data->lineOrder == INCREASING_Y)?
                   TileCoord (0, 0, 0, 0):
                   TileCoord (0, _data->numYTiles[0] - 1, 0, 0);

    _data->maxBytesPerTileLine =
        calculateBytesPerPixel (_data->header) * _data->tileDesc.xSize;

    _data->tileBufferSize = _data->maxBytesPerTileLine * _data->tileDesc.ySize;

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

    for (size_t i = 0; i < _data->tileBuffers.size(); i++)
    {
        _data->tileBuffers[i] = new TileBuffer (newTileCompressor
                          (_data->header.compression(),
                           _data->maxBytesPerTileLine,
                           _data->tileDesc.ySize,
                           _data->header));

        _data->tileBuffers[i]->buffer.resizeErase(_data->tileBufferSize);
    }

    _data->format = defaultFormat (_data->tileBuffers[0]->compressor);

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

    _data->previewPosition = _data->header.writeTo (*_data->os, true);

    _data->tileOffsetsPosition = _data->tileOffsets.writeTo (*_data->os);
    _data->currentPosition = _data->os->tellp();
}


TiledOutputFile::~TiledOutputFile ()
{
    if (_data)
    {
        {
            if (_data->tileOffsetsPosition > 0)
            {
                try
                {
                    _data->os->seekp (_data->tileOffsetsPosition);
                    _data->tileOffsets.writeTo (*_data->os);
                }
                catch (...)
                {
                    //
                    // We cannot safely throw any exceptions from here.
                    // This destructor may have been called because the
                    // stack is currently being unwound for another
                    // exception.
                    //
                }
            }
        }

        delete _data;
    }
}


const char *
TiledOutputFile::fileName () const
{
    return _data->os->fileName();
}


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


void
TiledOutputFile::setFrameBuffer (const FrameBuffer &frameBuffer)
{
    Lock lock (*_data);

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

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

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

    if (j == frameBuffer.end())
        continue;

    if (i.channel().type != j.slice().type)
        THROW (Iex::ArgExc, "Pixel type of \"" << i.name() << "\" channel "
                "of output file \"" << fileName() << "\" is "
                "not compatible with the frame buffer's "
                "pixel type.");

    if (j.slice().xSampling != 1 || j.slice().ySampling != 1)
        THROW (Iex::ArgExc, "All channels in a tiled file must have"
                "sampling (1,1).");
    }

    //
    // Initialize slice table for writePixels().
    //

    vector<TOutSliceInfo> slices;

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

    if (j == frameBuffer.end())
    {
        //
        // Channel i is not present in the frame buffer.
        // In the file, channel i will contain only zeroes.
        //

        slices.push_back (TOutSliceInfo (i.channel().type,
                         0, // base
                         0, // xStride,
                         0, // yStride,
                         true)); // zero
    }
    else
    {
        //
        // Channel i is present in the frame buffer.
        //

        slices.push_back (TOutSliceInfo (j.slice().type,
                         j.slice().base,
                         j.slice().xStride,
                         j.slice().yStride,
                         false, // zero
                                             (j.slice().xTileCoords)? 1: 0,
                                             (j.slice().yTileCoords)? 1: 0));
    }
    }

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

    _data->frameBuffer = frameBuffer;
    _data->slices = slices;
}


const FrameBuffer &
TiledOutputFile::frameBuffer () const
{
    Lock lock (*_data);
    return _data->frameBuffer;
}


void
TiledOutputFile::writeTiles (int dx1, int dx2, int dy1, int dy2,
                             int lx, int ly)
{
    try
    {
        Lock lock (*_data);

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

    if (!isValidTile (dx1, dy1, lx, ly) || !isValidTile (dx2, dy2, lx, ly))
        throw Iex::ArgExc ("Tile coordinates are invalid.");

        //
        // Determine the first and last tile coordinates in both dimensions
        // based on the file's lineOrder
        //

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

        if (dy1 > dy2)
            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;
        }

        int numTiles = (dx2 - dx1 + 1) * (dy2 - dy1 + 1);
        int numTasks = min ((int)_data->tileBuffers.size(), numTiles);

        //
        // 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;

            //
            // Add in the initial compression tasks to the thread pool
            //

            int nextCompBuffer = 0;
        int dxComp         = dx1;
        int dyComp         = dyStart;

            while (nextCompBuffer < numTasks)
            {
                ThreadPool::addGlobalTask (new TileBufferTask (&taskGroup,
                                                               _data,
                                                               nextCompBuffer++,
                                                               dxComp, dyComp,
                                                               lx, ly));
                dxComp++;

                if (dxComp > dx2)
                {
                    dxComp = dx1;
                    dyComp += dY;
                }
            }

            //
            // Write the compressed buffers and add in more compression
        // tasks until done
            //

            int nextWriteBuffer = 0;
        int dxWrite         = dx1;
        int dyWrite         = dyStart;

            while (nextWriteBuffer < numTiles)
            {
        //
                // Wait until the nextWriteBuffer is ready to be written
        //

                TileBuffer* writeBuffer =
                                    _data->getTileBuffer (nextWriteBuffer);

                writeBuffer->wait();

        //
                // Write the tilebuffer
        //

                bufferedTileWrite (_data, dxWrite, dyWrite, lx, ly,
                                   writeBuffer->dataPtr,
                                   writeBuffer->dataSize);

        //
                // Release the lock on nextWriteBuffer
        //

                writeBuffer->post();

        //
                // If there are no more tileBuffers to compress, then
        // only continue to write out remaining tileBuffers,
        // otherwise keep adding compression tasks.
        //

                if (nextCompBuffer < numTiles)
                {
            //
                    // add nextCompBuffer as a compression Task
            //

                    ThreadPool::addGlobalTask
            (new TileBufferTask (&taskGroup,
                         _data,
                         nextCompBuffer,
                                             dxComp, dyComp,
                         lx, ly));
                }

                nextWriteBuffer++;
                dxWrite++;

                if (dxWrite > dx2)
                {
                    dxWrite = dx1;
                    dyWrite += dY;
                }

                nextCompBuffer++;
                dxComp++;

                if (dxComp > dx2)
                {
                    dxComp = dx1;
                    dyComp += dY;
                }
            }

        //
            // 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 TiledOutputFile::writeTiles().
    // 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 (int 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::IoExc (*exception);
    }
    catch (Iex::BaseExc &e)
    {
        REPLACE_EXC (e, "Failed to write pixel data to image "
                        "file \"" << fileName() << "\". " << e);
        throw;
    }
}


void
TiledOutputFile::writeTiles (int dx1, int dxMax, int dyMin, int dyMax, int l)
{
    writeTiles (dx1, dxMax, dyMin, dyMax, l, l);
}


void
TiledOutputFile::writeTile (int dx, int dy, int lx, int ly)
{
    writeTiles (dx, dx, dy, dy, lx, ly);
}


void
TiledOutputFile::writeTile (int dx, int dy, int l)
{
    writeTile(dx, dy, l, l);
}


void
TiledOutputFile::copyPixels (TiledInputFile &in)
{
    Lock lock (*_data);

    //
    // Check if this file's and and the InputFile's
    // headers are compatible.
    //

    const Header &hdr = _data->header;
    const Header &inHdr = in.header();

    if (!hdr.hasTileDescription() || !inHdr.hasTileDescription())
        THROW (Iex::ArgExc, "Cannot perform a quick pixel copy from image "
                "file \"" << in.fileName() << "\" to image "
                "file \"" << fileName() << "\".  The "
                            "output file is tiled, but the input file is not.  "
                            "Try using OutputFile::copyPixels() instead.");

    if (!(hdr.tileDescription() == inHdr.tileDescription()))
        THROW (Iex::ArgExc, "Quick pixel copy from image "
                "file \"" << in.fileName() << "\" to image "
                "file \"" << fileName() << "\" failed. "
                "The files have different tile descriptions.");

    if (!(hdr.dataWindow() == inHdr.dataWindow()))
        THROW (Iex::ArgExc, "Cannot copy pixels from image "
                "file \"" << in.fileName() << "\" to image "
                "file \"" << fileName() << "\". The "
                            "files have different data windows.");

    if (!(hdr.lineOrder() == inHdr.lineOrder()))
        THROW (Iex::ArgExc, "Quick pixel copy from image "
                "file \"" << in.fileName() << "\" to image "
                "file \"" << fileName() << "\" failed. "
                "The files have different line orders.");

    if (!(hdr.compression() == inHdr.compression()))
        THROW (Iex::ArgExc, "Quick pixel copy from image "
                "file \"" << in.fileName() << "\" to image "
                "file \"" << fileName() << "\" failed. "
                "The files use different compression methods.");

    if (!(hdr.channels() == inHdr.channels()))
        THROW (Iex::ArgExc, "Quick pixel copy from image "
                 "file \"" << in.fileName() << "\" to image "
                 "file \"" << fileName() << "\" "
                             "failed.  The files have different channel "
                             "lists.");

    //
    // Verify that no pixel data have been written to this file yet.
    //

    if (!_data->tileOffsets.isEmpty())
        THROW (Iex::LogicExc, "Quick pixel copy from image "
                  "file \"" << in.fileName() << "\" to image "
                  "file \"" << _data->os->fileName() << "\" "
                              "failed. \"" << fileName() << "\" "
                              "already contains pixel data.");

    //
    // Calculate the total number of tiles in the file
    //

    int numAllTiles = 0;

    switch (levelMode ())
    {
      case ONE_LEVEL:
      case MIPMAP_LEVELS:

        for (size_t i_l = 0; i_l < numLevels (); ++i_l)
            numAllTiles += numXTiles (i_l) * numYTiles (i_l);

        break;

      case RIPMAP_LEVELS:

        for (size_t i_ly = 0; i_ly < numYLevels (); ++i_ly)
            for (size_t i_lx = 0; i_lx < numXLevels (); ++i_lx)
                numAllTiles += numXTiles (i_lx) * numYTiles (i_ly);

        break;

      default:

        throw Iex::ArgExc ("Unknown LevelMode format.");
    }

    for (int i = 0; i < numAllTiles; ++i)
    {
        const char *pixelData;
        int pixelDataSize;

        int dx = _data->nextTileToWrite.dx;
        int dy = _data->nextTileToWrite.dy;
        int lx = _data->nextTileToWrite.lx;
        int ly = _data->nextTileToWrite.ly;

        in.rawTileData (dx, dy, lx, ly, pixelData, pixelDataSize);
        writeTileData (_data, dx, dy, lx, ly, pixelData, pixelDataSize);
    }
}


void
TiledOutputFile::copyPixels (InputFile &in)
{
    copyPixels (*in.tFile());
}


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


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


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


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


int
TiledOutputFile::numLevels () const
{
    if (levelMode() == RIPMAP_LEVELS)
    THROW (Iex::LogicExc, "Error calling numLevels() on image "
                  "file \"" << fileName() << "\" "
                  "(numLevels() is not defined for RIPMAPs).");
    return _data->numXLevels;
}


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


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


bool
TiledOutputFile::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
TiledOutputFile::levelWidth (int lx) const
{
    try
    {
    int retVal = levelSize (_data->minX, _data->maxX, lx,
                    _data->tileDesc.roundingMode);

        return retVal;
    }
    catch (Iex::BaseExc &e)
    {
    REPLACE_EXC (e, "Error calling levelWidth() on image "
            "file \"" << fileName() << "\". " << e);
    throw;
    }
}


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


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

    return _data->numXTiles[lx];
}


int
TiledOutputFile::numYTiles (int ly) const
{
   if (ly < 0 || ly >= _data->numYLevels)
    THROW (Iex::LogicExc, "Error calling numXTiles() on image "
                  "file \"" << _data->os->fileName() << "\" "
                  "(Argument is not in valid range).");

    return _data->numYTiles[ly];
}


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


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


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


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

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


bool
TiledOutputFile::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
TiledOutputFile::updatePreviewImage (const PreviewRgba newPixels[])
{
    Lock lock (*_data);

    if (_data->previewPosition <= 0)
    THROW (Iex::LogicExc, "Cannot update preview image pixels. "
                  "File \"" << fileName() << "\" does not "
                  "contain a preview image.");

    //
    // Store the new pixels in the header's preview image attribute.
    //

    PreviewImageAttribute &pia =
    _data->header.typedAttribute <PreviewImageAttribute> ("preview");

    PreviewImage &pi = pia.value();
    PreviewRgba *pixels = pi.pixels();
    int numPixels = pi.width() * pi.height();

    for (int i = 0; i < numPixels; ++i)
    pixels[i] = newPixels[i];

    //
    // Save the current file position, jump to the position in
    // the file where the preview image starts, store the new
    // preview image, and jump back to the saved file position.
    //

    Int64 savedPosition = _data->os->tellp();

    try
    {
    _data->os->seekp (_data->previewPosition);
    pia.writeValueTo (*_data->os, _data->version);
    _data->os->seekp (savedPosition);
    }
    catch (Iex::BaseExc &e)
    {
    REPLACE_EXC (e, "Cannot update preview image pixels for "
            "file \"" << fileName() << "\". " << e);
    throw;
    }
}


void
TiledOutputFile::breakTile
    (int dx, int dy,
     int lx, int ly,
     int offset,
     int length,
     char c)
{
    Lock lock (*_data);

    Int64 position = _data->tileOffsets (dx, dy, lx, ly);

    if (!position)
    THROW (Iex::ArgExc,
           "Cannot overwrite tile "
           "(" << dx << ", " << dy << ", " << lx << "," << ly << "). "
           "The tile has not yet been stored in "
           "file \"" << fileName() << "\".");

    _data->currentPosition = 0;
    _data->os->seekp (position + offset);

    for (int i = 0; i < length; ++i)
    _data->os->write (&c, 1);
}

} // namespace Imf