ImfRgbaFile.cpp 31.1 KB
Newer Older
1 2 3 4
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
5
//
6
// All rights reserved.
7
//
8 9 10 11 12 13 14 15 16 17 18
// 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
19 20
// from this software without specific prior written permission.
//
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
// 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 RgbaOutputFile
//	class RgbaInputFile
//
//-----------------------------------------------------------------------------

#include <ImfRgbaFile.h>
#include <ImfOutputFile.h>
#include <ImfInputFile.h>
#include <ImfChannelList.h>
#include <ImfRgbaYca.h>
#include <ImfStandardAttributes.h>
#include <ImathFun.h>
#include <IlmThreadMutex.h>
#include <Iex.h>
#include <string.h>
#include <algorithm>


namespace Imf {

using namespace std;
using namespace Imath;
using namespace RgbaYca;
using namespace IlmThread;

namespace {

void
insertChannels (Header &header, RgbaChannels rgbaChannels)
{
    ChannelList ch;

    if (rgbaChannels & (WRITE_Y | WRITE_C))
    {
71 72 73 74 75 76 77 78 79 80
    if (rgbaChannels & WRITE_Y)
    {
        ch.insert ("Y", Channel (HALF, 1, 1));
    }

    if (rgbaChannels & WRITE_C)
    {
        ch.insert ("RY", Channel (HALF, 2, 2, true));
        ch.insert ("BY", Channel (HALF, 2, 2, true));
    }
81 82 83
    }
    else
    {
84 85
    if (rgbaChannels & WRITE_R)
        ch.insert ("R", Channel (HALF, 1, 1));
86

87 88
    if (rgbaChannels & WRITE_G)
        ch.insert ("G", Channel (HALF, 1, 1));
89

90 91
    if (rgbaChannels & WRITE_B)
        ch.insert ("B", Channel (HALF, 1, 1));
92 93 94
    }

    if (rgbaChannels & WRITE_A)
95
    ch.insert ("A", Channel (HALF, 1, 1));
96 97 98 99 100 101 102 103 104 105 106

    header.channels() = ch;
}


RgbaChannels
rgbaChannels (const ChannelList &ch, const string &channelNamePrefix = "")
{
    int i = 0;

    if (ch.findChannel (channelNamePrefix + "R"))
107
    i |= WRITE_R;
108 109

    if (ch.findChannel (channelNamePrefix + "G"))
110 111
    i |= WRITE_G;

112
    if (ch.findChannel (channelNamePrefix + "B"))
113
    i |= WRITE_B;
114 115

    if (ch.findChannel (channelNamePrefix + "A"))
116
    i |= WRITE_A;
117 118

    if (ch.findChannel (channelNamePrefix + "Y"))
119
    i |= WRITE_Y;
120 121

    if (ch.findChannel (channelNamePrefix + "RY") ||
122 123
    ch.findChannel (channelNamePrefix + "BY"))
    i |= WRITE_C;
124 125 126 127 128 129 130 131 132

    return RgbaChannels (i);
}


string
prefixFromLayerName (const string &layerName, const Header &header)
{
    if (layerName.empty())
133
    return "";
134 135

    if (hasMultiView (header) && multiView(header)[0] == layerName)
136
    return "";
137 138 139 140 141 142 143 144 145 146 147

    return layerName + ".";
}


V3f
ywFromHeader (const Header &header)
{
    Chromaticities cr;

    if (hasChromaticities (header))
148
    cr = chromaticities (header);
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

    return computeYw (cr);
}


ptrdiff_t
cachePadding (ptrdiff_t size)
{
    //
    // Some of the buffers that are allocated by classes ToYca and
    // FromYca, below, may need to be padded to avoid cache thrashing.
    // If the difference between the buffer size and the nearest power
    // of two is less than CACHE_LINE_SIZE, then we add an appropriate
    // amount of padding.
    //
    // CACHE_LINE_SIZE must be a power of two, and it must be at
    // least as big as the true size of a cache line on the machine
    // we are running on.  (It is ok if CACHE_LINE_SIZE is larger
    // than a real cache line.)
    //

    static int LOG2_CACHE_LINE_SIZE = 8;
    static const ptrdiff_t CACHE_LINE_SIZE = (1 << LOG2_CACHE_LINE_SIZE);

    int i = LOG2_CACHE_LINE_SIZE + 2;

    while ((size >> i) > 1)
176
    ++i;
177 178

    if (size > (1 << (i + 1)) - 64)
179
    return 64 + ((1 << (i + 1)) - size);
180 181

    if (size < (1 << i) + 64)
182
    return 64 + ((1 << i) - size);
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

    return 0;
}

} // namespace


class RgbaOutputFile::ToYca: public Mutex
{
  public:

     ToYca (OutputFile &outputFile, RgbaChannels rgbaChannels);
    ~ToYca ();

    void		setYCRounding (unsigned int roundY,
198
                           unsigned int roundC);
199 200

    void		setFrameBuffer (const Rgba *base,
201 202
                    size_t xStride,
                    size_t yStride);
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

    void		writePixels (int numScanLines);
    int			currentScanLine () const;

  private:

    void		padTmpBuf ();
    void		rotateBuffers ();
    void		duplicateLastBuffer ();
    void		duplicateSecondToLastBuffer ();
    void		decimateChromaVertAndWriteScanLine ();

    OutputFile &	_outputFile;
    bool		_writeY;
    bool		_writeC;
    bool		_writeA;
    int			_xMin;
    int			_width;
    int			_height;
    int			_linesConverted;
    LineOrder		_lineOrder;
    int			_currentScanLine;
    V3f			_yw;
    Rgba *		_bufBase;
    Rgba *		_buf[N];
    Rgba *		_tmpBuf;
    const Rgba *	_fbBase;
    size_t		_fbXStride;
    size_t		_fbYStride;
    int			_roundY;
    int			_roundC;
};


RgbaOutputFile::ToYca::ToYca (OutputFile &outputFile,
238
                  RgbaChannels rgbaChannels)
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
:
    _outputFile (outputFile)
{
    _writeY = (rgbaChannels & WRITE_Y)? true: false;
    _writeC = (rgbaChannels & WRITE_C)? true: false;
    _writeA = (rgbaChannels & WRITE_A)? true: false;

    const Box2i dw = _outputFile.header().dataWindow();

    _xMin = dw.min.x;
    _width  = dw.max.x - dw.min.x + 1;
    _height = dw.max.y - dw.min.y + 1;

    _linesConverted = 0;
    _lineOrder = _outputFile.header().lineOrder();
254

255
    if (_lineOrder == INCREASING_Y)
256
    _currentScanLine = dw.min.y;
257
    else
258
    _currentScanLine = dw.max.y;
259 260 261 262 263 264 265 266

    _yw = ywFromHeader (_outputFile.header());

    ptrdiff_t pad = cachePadding (_width * sizeof (Rgba)) / sizeof (Rgba);

    _bufBase = new Rgba[(_width + pad) * N];

    for (int i = 0; i < N; ++i)
267
    _buf[i] = _bufBase + (i * (_width + pad));
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

    _tmpBuf = new Rgba[_width + N - 1];

    _fbBase = 0;
    _fbXStride = 0;
    _fbYStride = 0;

    _roundY = 7;
    _roundC = 5;
}


RgbaOutputFile::ToYca::~ToYca ()
{
    delete [] _bufBase;
    delete [] _tmpBuf;
}


void
RgbaOutputFile::ToYca::setYCRounding (unsigned int roundY,
289
                      unsigned int roundC)
290 291 292 293 294 295 296 297
{
    _roundY = roundY;
    _roundC = roundC;
}


void
RgbaOutputFile::ToYca::setFrameBuffer (const Rgba *base,
298 299
                       size_t xStride,
                       size_t yStride)
300 301 302
{
    if (_fbBase == 0)
    {
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
    FrameBuffer fb;

    if (_writeY)
    {
        fb.insert ("Y",
               Slice (HALF,				// type
                  (char *) &_tmpBuf[-_xMin].g,	// base
                  sizeof (Rgba),			// xStride
                  0,				// yStride
                  1,				// xSampling
                  1));				// ySampling
    }

    if (_writeC)
    {
        fb.insert ("RY",
               Slice (HALF,				// type
                  (char *) &_tmpBuf[-_xMin].r,	// base
                  sizeof (Rgba) * 2,		// xStride
                  0,				// yStride
                  2,				// xSampling
                  2));				// ySampling

        fb.insert ("BY",
               Slice (HALF,				// type
                  (char *) &_tmpBuf[-_xMin].b,	// base
                  sizeof (Rgba) * 2,		// xStride
                  0,				// yStride
                  2,				// xSampling
                  2));				// ySampling
    }

    if (_writeA)
    {
        fb.insert ("A",
               Slice (HALF,				// type
                  (char *) &_tmpBuf[-_xMin].a,	// base
                  sizeof (Rgba),			// xStride
                  0,				// yStride
                  1,				// xSampling
                  1));				// ySampling
    }

    _outputFile.setFrameBuffer (fb);
347 348 349 350 351 352 353 354 355 356 357 358 359
    }

    _fbBase = base;
    _fbXStride = xStride;
    _fbYStride = yStride;
}


void
RgbaOutputFile::ToYca::writePixels (int numScanLines)
{
    if (_fbBase == 0)
    {
360 361 362
    THROW (Iex::ArgExc, "No frame buffer was specified as the "
                "pixel data source for image file "
                "\"" << _outputFile.fileName() << "\".");
363 364 365 366
    }

    if (_writeY && !_writeC)
    {
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
    //
    // We are writing only luminance; filtering
    // and subsampling are not necessary.
    //

    for (int i = 0; i < numScanLines; ++i)
    {
        //
        // Copy the next scan line from the caller's
        // frame buffer into _tmpBuf.
        //

        for (int j = 0; j < _width; ++j)
        {
        _tmpBuf[j] = _fbBase[_fbYStride * _currentScanLine +
                     _fbXStride * (j + _xMin)];
        }

        //
        // Convert the scan line from RGB to luminance/chroma,
        // and store the result in the output file.
        //

        RGBAtoYCA (_yw, _width, _writeA, _tmpBuf, _tmpBuf);
        _outputFile.writePixels (1);

        ++_linesConverted;

        if (_lineOrder == INCREASING_Y)
        ++_currentScanLine;
        else
        --_currentScanLine;
    }
400 401 402
    }
    else
    {
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
    //
    // We are writing chroma; the pixels must be filtered and subsampled.
    //

    for (int i = 0; i < numScanLines; ++i)
    {
        //
        // Copy the next scan line from the caller's
        // frame buffer into _tmpBuf.
        //

        for (int j = 0; j < _width; ++j)
        {
        _tmpBuf[j + N2] = _fbBase[_fbYStride * _currentScanLine +
                      _fbXStride * (j + _xMin)];
        }

        //
        // Convert the scan line from RGB to luminance/chroma.
        //

        RGBAtoYCA (_yw, _width, _writeA, _tmpBuf + N2, _tmpBuf + N2);

        //
        // Append N2 copies of the first and last pixel to the
        // beginning and end of the scan line.
        //

        padTmpBuf ();

        //
        // Filter and subsample the scan line's chroma channels
        // horizontally; store the result in _buf.
        //

        rotateBuffers();
        decimateChromaHoriz (_width, _tmpBuf, _buf[N - 1]);

        //
        // If this is the first scan line in the image,
        // store N2 more copies of the scan line in _buf.
        //

        if (_linesConverted == 0)
        {
        for (int j = 0; j < N2; ++j)
            duplicateLastBuffer();
        }

        ++_linesConverted;

        //
        // If we have have converted at least N2 scan lines from
        // RGBA to luminance/chroma, then we can start to filter
        // and subsample vertically, and store pixels in the
        // output file.
        //

        if (_linesConverted > N2)
        decimateChromaVertAndWriteScanLine();

        //
        // If we have already converted the last scan line in
        // the image to luminance/chroma, filter, subsample and
        // store the remaining scan lines in _buf.
        //

        if (_linesConverted >= _height)
        {
        for (int j = 0; j < N2 - _height; ++j)
            duplicateLastBuffer();

        duplicateSecondToLastBuffer();
        ++_linesConverted;
        decimateChromaVertAndWriteScanLine();

        for (int j = 1; j < min (_height, N2); ++j)
        {
            duplicateLastBuffer();
            ++_linesConverted;
            decimateChromaVertAndWriteScanLine();
        }
        }

        if (_lineOrder == INCREASING_Y)
        ++_currentScanLine;
        else
        --_currentScanLine;
    }
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
    }
}


int
RgbaOutputFile::ToYca::currentScanLine () const
{
    return _currentScanLine;
}


void
RgbaOutputFile::ToYca::padTmpBuf ()
{
    for (int i = 0; i < N2; ++i)
    {
508 509
    _tmpBuf[i] = _tmpBuf[N2];
    _tmpBuf[_width + N2 + i] = _tmpBuf[_width + N2 - 2];
510 511 512 513 514 515 516 517 518 519
    }
}


void
RgbaOutputFile::ToYca::rotateBuffers ()
{
    Rgba *tmp = _buf[0];

    for (int i = 0; i < N - 1; ++i)
520
    _buf[i] = _buf[i + 1];
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

    _buf[N - 1] = tmp;
}


void
RgbaOutputFile::ToYca::duplicateLastBuffer ()
{
    rotateBuffers();
    memcpy (_buf[N - 1], _buf[N - 2], _width * sizeof (Rgba));
}


void
RgbaOutputFile::ToYca::duplicateSecondToLastBuffer ()
{
    rotateBuffers();
    memcpy (_buf[N - 1], _buf[N - 3], _width * sizeof (Rgba));
}


void
RgbaOutputFile::ToYca::decimateChromaVertAndWriteScanLine ()
{
    if (_linesConverted & 1)
546
    memcpy (_tmpBuf, _buf[N2], _width * sizeof (Rgba));
547
    else
548
    decimateChromaVert (_width, _buf, _tmpBuf);
549 550

    if (_writeY && _writeC)
551
    roundYCA (_width, _roundY, _roundC, _tmpBuf, _tmpBuf);
552 553 554 555 556 557

    _outputFile.writePixels (1);
}


RgbaOutputFile::RgbaOutputFile (const char name[],
558 559
                const Header &header,
                RgbaChannels rgbaChannels,
560 561 562 563 564 565 566 567 568
                                int numThreads):
    _outputFile (0),
    _toYca (0)
{
    Header hd (header);
    insertChannels (hd, rgbaChannels);
    _outputFile = new OutputFile (name, hd, numThreads);

    if (rgbaChannels & (WRITE_Y | WRITE_C))
569
    _toYca = new ToYca (*_outputFile, rgbaChannels);
570 571 572 573
}


RgbaOutputFile::RgbaOutputFile (OStream &os,
574 575
                const Header &header,
                RgbaChannels rgbaChannels,
576 577 578 579 580 581 582 583 584
                                int numThreads):
    _outputFile (0),
    _toYca (0)
{
    Header hd (header);
    insertChannels (hd, rgbaChannels);
    _outputFile = new OutputFile (os, hd, numThreads);

    if (rgbaChannels & (WRITE_Y | WRITE_C))
585
    _toYca = new ToYca (*_outputFile, rgbaChannels);
586 587 588 589
}


RgbaOutputFile::RgbaOutputFile (const char name[],
590 591 592 593 594 595 596 597
                const Imath::Box2i &displayWindow,
                const Imath::Box2i &dataWindow,
                RgbaChannels rgbaChannels,
                float pixelAspectRatio,
                const Imath::V2f screenWindowCenter,
                float screenWindowWidth,
                LineOrder lineOrder,
                Compression compression,
598 599 600 601 602
                                int numThreads):
    _outputFile (0),
    _toYca (0)
{
    Header hd (displayWindow,
603 604 605 606 607 608
           dataWindow.isEmpty()? displayWindow: dataWindow,
           pixelAspectRatio,
           screenWindowCenter,
           screenWindowWidth,
           lineOrder,
           compression);
609 610 611 612 613

    insertChannels (hd, rgbaChannels);
    _outputFile = new OutputFile (name, hd, numThreads);

    if (rgbaChannels & (WRITE_Y | WRITE_C))
614
    _toYca = new ToYca (*_outputFile, rgbaChannels);
615 616 617 618
}


RgbaOutputFile::RgbaOutputFile (const char name[],
619 620 621 622 623 624 625 626
                int width,
                int height,
                RgbaChannels rgbaChannels,
                float pixelAspectRatio,
                const Imath::V2f screenWindowCenter,
                float screenWindowWidth,
                LineOrder lineOrder,
                Compression compression,
627 628 629 630 631
                                int numThreads):
    _outputFile (0),
    _toYca (0)
{
    Header hd (width,
632 633 634 635 636 637
           height,
           pixelAspectRatio,
           screenWindowCenter,
           screenWindowWidth,
           lineOrder,
           compression);
638 639 640 641 642

    insertChannels (hd, rgbaChannels);
    _outputFile = new OutputFile (name, hd, numThreads);

    if (rgbaChannels & (WRITE_Y | WRITE_C))
643
    _toYca = new ToYca (*_outputFile, rgbaChannels);
644 645 646 647 648 649 650 651 652 653 654 655
}


RgbaOutputFile::~RgbaOutputFile ()
{
    delete _toYca;
    delete _outputFile;
}


void
RgbaOutputFile::setFrameBuffer (const Rgba *base,
656 657
                size_t xStride,
                size_t yStride)
658 659 660
{
    if (_toYca)
    {
661 662
    Lock lock (*_toYca);
    _toYca->setFrameBuffer (base, xStride, yStride);
663 664 665
    }
    else
    {
666 667
    size_t xs = xStride * sizeof (Rgba);
    size_t ys = yStride * sizeof (Rgba);
668

669
    FrameBuffer fb;
670

671 672 673 674
    fb.insert ("R", Slice (HALF, (char *) &base[0].r, xs, ys));
    fb.insert ("G", Slice (HALF, (char *) &base[0].g, xs, ys));
    fb.insert ("B", Slice (HALF, (char *) &base[0].b, xs, ys));
    fb.insert ("A", Slice (HALF, (char *) &base[0].a, xs, ys));
675

676
    _outputFile->setFrameBuffer (fb);
677 678 679 680
    }
}


681
void
682 683 684 685
RgbaOutputFile::writePixels (int numScanLines)
{
    if (_toYca)
    {
686 687
    Lock lock (*_toYca);
    _toYca->writePixels (numScanLines);
688 689 690
    }
    else
    {
691
    _outputFile->writePixels (numScanLines);
692 693 694 695
    }
}


696
int
697 698 699 700
RgbaOutputFile::currentScanLine () const
{
    if (_toYca)
    {
701 702
    Lock lock (*_toYca);
    return _toYca->currentScanLine();
703 704 705
    }
    else
    {
706
    return _outputFile->currentScanLine();
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
    }
}


const Header &
RgbaOutputFile::header () const
{
    return _outputFile->header();
}


const FrameBuffer &
RgbaOutputFile::frameBuffer () const
{
    return _outputFile->frameBuffer();
}


const Imath::Box2i &
RgbaOutputFile::displayWindow () const
{
    return _outputFile->header().displayWindow();
}


const Imath::Box2i &
RgbaOutputFile::dataWindow () const
{
    return _outputFile->header().dataWindow();
}


739
float
740 741 742 743 744 745 746 747 748 749 750 751 752
RgbaOutputFile::pixelAspectRatio () const
{
    return _outputFile->header().pixelAspectRatio();
}


const Imath::V2f
RgbaOutputFile::screenWindowCenter () const
{
    return _outputFile->header().screenWindowCenter();
}


753
float
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
RgbaOutputFile::screenWindowWidth () const
{
    return _outputFile->header().screenWindowWidth();
}


LineOrder
RgbaOutputFile::lineOrder () const
{
    return _outputFile->header().lineOrder();
}


Compression
RgbaOutputFile::compression () const
{
    return _outputFile->header().compression();
}


RgbaChannels
RgbaOutputFile::channels () const
{
    return rgbaChannels (_outputFile->header().channels());
}


781
void
782 783 784 785 786 787
RgbaOutputFile::updatePreviewImage (const PreviewRgba newPixels[])
{
    _outputFile->updatePreviewImage (newPixels);
}


788
void
789 790 791 792
RgbaOutputFile::setYCRounding (unsigned int roundY, unsigned int roundC)
{
    if (_toYca)
    {
793 794
    Lock lock (*_toYca);
    _toYca->setYCRounding (roundY, roundC);
795 796 797 798
    }
}


799
void
800 801 802 803 804 805 806 807 808 809 810 811 812 813
RgbaOutputFile::breakScanLine  (int y, int offset, int length, char c)
{
    _outputFile->breakScanLine (y, offset, length, c);
}


class RgbaInputFile::FromYca: public Mutex
{
  public:

     FromYca (InputFile &inputFile, RgbaChannels rgbaChannels);
    ~FromYca ();

    void		setFrameBuffer (Rgba *base,
814 815 816
                    size_t xStride,
                    size_t yStride,
                    const string &channelNamePrefix);
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

    void		readPixels (int scanLine1, int scanLine2);

  private:

    void		readPixels (int scanLine);
    void		rotateBuf1 (int d);
    void		rotateBuf2 (int d);
    void		readYCAScanLine (int y, Rgba buf[]);
    void		padTmpBuf ();

    InputFile &		_inputFile;
    bool		_readC;
    int			_xMin;
    int			_yMin;
    int 		_yMax;
    int			_width;
    int			_height;
    int			_currentScanLine;
    LineOrder		_lineOrder;
    V3f			_yw;
    Rgba *		_bufBase;
    Rgba *		_buf1[N + 2];
    Rgba *		_buf2[3];
    Rgba *		_tmpBuf;
    Rgba *		_fbBase;
    size_t		_fbXStride;
    size_t		_fbYStride;
};


RgbaInputFile::FromYca::FromYca (InputFile &inputFile,
849
                 RgbaChannels rgbaChannels)
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
:
    _inputFile (inputFile)
{
    _readC = (rgbaChannels & WRITE_C)? true: false;

    const Box2i dw = _inputFile.header().dataWindow();

    _xMin = dw.min.x;
    _yMin = dw.min.y;
    _yMax = dw.max.y;
    _width  = dw.max.x - dw.min.x + 1;
    _height = dw.max.y - dw.min.y + 1;
    _currentScanLine = dw.min.y - N - 2;
    _lineOrder = _inputFile.header().lineOrder();
    _yw = ywFromHeader (_inputFile.header());

    ptrdiff_t pad = cachePadding (_width * sizeof (Rgba)) / sizeof (Rgba);

    _bufBase = new Rgba[(_width + pad) * (N + 2 + 3)];

    for (int i = 0; i < N + 2; ++i)
871 872
    _buf1[i] = _bufBase + (i * (_width + pad));

873
    for (int i = 0; i < 3; ++i)
874
    _buf2[i] = _bufBase + ((i + N + 2) * (_width + pad));
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

    _tmpBuf = new Rgba[_width + N - 1];

    _fbBase = 0;
    _fbXStride = 0;
    _fbYStride = 0;
}


RgbaInputFile::FromYca::~FromYca ()
{
    delete [] _bufBase;
    delete [] _tmpBuf;
}


void
RgbaInputFile::FromYca::setFrameBuffer (Rgba *base,
893 894 895
                    size_t xStride,
                    size_t yStride,
                    const string &channelNamePrefix)
896 897 898
{
    if (_fbBase == 0)
    {
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
    FrameBuffer fb;

    fb.insert (channelNamePrefix + "Y",
           Slice (HALF,					// type
              (char *) &_tmpBuf[N2 - _xMin].g,	// base
              sizeof (Rgba),			// xStride
              0,					// yStride
              1,					// xSampling
              1,					// ySampling
              0.5));				// fillValue

    if (_readC)
    {
        fb.insert (channelNamePrefix + "RY",
               Slice (HALF,				// type
                  (char *) &_tmpBuf[N2 - _xMin].r,	// base
                  sizeof (Rgba) * 2,		// xStride
                  0,				// yStride
                  2,				// xSampling
                  2,				// ySampling
                  0.0));				// fillValue

        fb.insert (channelNamePrefix + "BY",
               Slice (HALF,				// type
                  (char *) &_tmpBuf[N2 - _xMin].b,	// base
                  sizeof (Rgba) * 2,		// xStride
                  0,				// yStride
                  2,				// xSampling
                  2,				// ySampling
                  0.0));				// fillValue
    }

    fb.insert (channelNamePrefix + "A",
           Slice (HALF,					// type
              (char *) &_tmpBuf[N2 - _xMin].a,	// base
              sizeof (Rgba),			// xStride
              0,					// yStride
              1,					// xSampling
              1,					// ySampling
              1.0));				// fillValue

    _inputFile.setFrameBuffer (fb);
941 942 943 944 945 946 947 948
    }

    _fbBase = base;
    _fbXStride = xStride;
    _fbYStride = yStride;
}


949
void
950 951 952 953 954 955 956
RgbaInputFile::FromYca::readPixels (int scanLine1, int scanLine2)
{
    int minY = min (scanLine1, scanLine2);
    int maxY = max (scanLine1, scanLine2);

    if (_lineOrder == INCREASING_Y)
    {
957 958
    for (int y = minY; y <= maxY; ++y)
        readPixels (y);
959 960 961
    }
    else
    {
962 963
    for (int y = maxY; y >= minY; --y)
        readPixels (y);
964 965 966 967
    }
}


968
void
969 970 971 972
RgbaInputFile::FromYca::readPixels (int scanLine)
{
    if (_fbBase == 0)
    {
973 974 975
    THROW (Iex::ArgExc, "No frame buffer was specified as the "
                "pixel data destination for image file "
                "\"" << _inputFile.fileName() << "\".");
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
    }

    //
    // In order to convert one scan line to RGB format, we need that
    // scan line plus N2+1 extra scan lines above and N2+1 scan lines
    // below in luminance/chroma format.
    //
    // We allow random access to scan lines, but we buffer partially
    // processed luminance/chroma data in order to make reading pixels
    // in increasing y or decreasing y order reasonably efficient:
    //
    //	_currentScanLine	holds the y coordinate of the scan line
    //				that was most recently read.
    //
    //	_buf1			contains scan lines _currentScanLine-N2-1
    //				through _currentScanLine+N2+1 in
    //				luminance/chroma format.  Odd-numbered
    //				lines contain no chroma data.  Even-numbered
    //				lines have valid chroma data for all pixels.
    //
    //  _buf2			contains scan lines _currentScanLine-1
    //  			through _currentScanLine+1, in RGB format.
    //				Super-saturated pixels (see ImfRgbaYca.h)
    //				have not yet been eliminated.
    //
    // If the scan line we are trying to read now is close enough to
    // _currentScanLine, we don't have to recompute the contents of _buf1
    // and _buf2 from scratch.  We can rotate _buf1 and _buf2, and fill
    // in the missing data.
    //

    int dy = scanLine - _currentScanLine;

    if (abs (dy) < N + 2)
1010
    rotateBuf1 (dy);
1011 1012

    if (abs (dy) < 3)
1013
    rotateBuf2 (dy);
1014 1015 1016

    if (dy < 0)
    {
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    {
        int n = min (-dy, N + 2);
        int yMin = scanLine - N2 - 1;

        for (int i = n - 1; i >= 0; --i)
        readYCAScanLine (yMin + i, _buf1[i]);
    }

    {
        int n = min (-dy, 3);

        for (int i = 0; i < n; ++i)
        {
        if ((scanLine + i) & 1)
        {
            YCAtoRGBA (_yw, _width, _buf1[N2 + i], _buf2[i]);
        }
        else
        {
            reconstructChromaVert (_width, _buf1 + i, _buf2[i]);
            YCAtoRGBA (_yw, _width, _buf2[i], _buf2[i]);
        }
        }
    }
1041 1042 1043
    }
    else
    {
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    {
        int n = min (dy, N + 2);
        int yMax = scanLine + N2 + 1;

        for (int i = n - 1; i >= 0; --i)
        readYCAScanLine (yMax - i, _buf1[N + 1 - i]);
    }

    {
        int n = min (dy, 3);

        for (int i = 2; i > 2 - n; --i)
        {
        if ((scanLine + i) & 1)
        {
            YCAtoRGBA (_yw, _width, _buf1[N2 + i], _buf2[i]);
        }
        else
        {
            reconstructChromaVert (_width, _buf1 + i, _buf2[i]);
            YCAtoRGBA (_yw, _width, _buf2[i], _buf2[i]);
        }
        }
    }
1068 1069 1070 1071 1072
    }

    fixSaturation (_yw, _width, _buf2, _tmpBuf);

    for (int i = 0; i < _width; ++i)
1073
    _fbBase[_fbYStride * scanLine + _fbXStride * (i + _xMin)] = _tmpBuf[i];
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

    _currentScanLine = scanLine;
}


void
RgbaInputFile::FromYca::rotateBuf1 (int d)
{
    d = modp (d, N + 2);

    Rgba *tmp[N + 2];

    for (int i = 0; i < N + 2; ++i)
1087
    tmp[i] = _buf1[i];
1088 1089

    for (int i = 0; i < N + 2; ++i)
1090
    _buf1[i] = tmp[(i + d) % (N + 2)];
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
}


void
RgbaInputFile::FromYca::rotateBuf2 (int d)
{
    d = modp (d, 3);

    Rgba *tmp[3];

    for (int i = 0; i < 3; ++i)
1102
    tmp[i] = _buf2[i];
1103 1104

    for (int i = 0; i < 3; ++i)
1105
    _buf2[i] = tmp[(i + d) % 3];
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
}


void
RgbaInputFile::FromYca::readYCAScanLine (int y, Rgba *buf)
{
    //
    // Clamp y.
    //

    if (y < _yMin)
1117
    y = _yMin;
1118
    else if (y > _yMax)
1119
    y = _yMax - 1;
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

    //
    // Read scan line y into _tmpBuf.
    //

    _inputFile.readPixels (y);

    //
    // Reconstruct missing chroma samples and copy
    // the scan line into buf.
    //

    if (!_readC)
    {
1134 1135 1136 1137 1138
    for (int i = 0; i < _width; ++i)
    {
        _tmpBuf[i + N2].r = 0;
        _tmpBuf[i + N2].b = 0;
    }
1139 1140 1141 1142
    }

    if (y & 1)
    {
1143
    memcpy (buf, _tmpBuf + N2, _width * sizeof (Rgba));
1144 1145 1146
    }
    else
    {
1147 1148
    padTmpBuf();
    reconstructChromaHoriz (_width, _tmpBuf, buf);
1149 1150 1151 1152 1153 1154 1155 1156 1157
    }
}


void
RgbaInputFile::FromYca::padTmpBuf ()
{
    for (int i = 0; i < N2; ++i)
    {
1158 1159
    _tmpBuf[i] = _tmpBuf[N2];
    _tmpBuf[_width + N2 + i] = _tmpBuf[_width + N2 - 2];
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    }
}


RgbaInputFile::RgbaInputFile (const char name[], int numThreads):
    _inputFile (new InputFile (name, numThreads)),
    _fromYca (0),
    _channelNamePrefix ("")
{
    RgbaChannels rgbaChannels = channels();

    if (rgbaChannels & (WRITE_Y | WRITE_C))
1172
    _fromYca = new FromYca (*_inputFile, rgbaChannels);
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
}


RgbaInputFile::RgbaInputFile (IStream &is, int numThreads):
    _inputFile (new InputFile (is, numThreads)),
    _fromYca (0),
    _channelNamePrefix ("")
{
    RgbaChannels rgbaChannels = channels();

    if (rgbaChannels & (WRITE_Y | WRITE_C))
1184
    _fromYca = new FromYca (*_inputFile, rgbaChannels);
1185 1186 1187 1188
}


RgbaInputFile::RgbaInputFile (const char name[],
1189 1190
                  const string &layerName,
                  int numThreads)
1191 1192 1193 1194 1195 1196 1197 1198
:
    _inputFile (new InputFile (name, numThreads)),
    _fromYca (0),
    _channelNamePrefix (prefixFromLayerName (layerName, _inputFile->header()))
{
    RgbaChannels rgbaChannels = channels();

    if (rgbaChannels & (WRITE_Y | WRITE_C))
1199
    _fromYca = new FromYca (*_inputFile, rgbaChannels);
1200 1201 1202 1203
}


RgbaInputFile::RgbaInputFile (IStream &is,
1204 1205
                  const string &layerName,
                  int numThreads)
1206 1207 1208 1209 1210 1211 1212 1213
:
    _inputFile (new InputFile (is, numThreads)),
    _fromYca (0),
    _channelNamePrefix (prefixFromLayerName (layerName, _inputFile->header()))
{
    RgbaChannels rgbaChannels = channels();

    if (rgbaChannels & (WRITE_Y | WRITE_C))
1214
    _fromYca = new FromYca (*_inputFile, rgbaChannels);
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
}


RgbaInputFile::~RgbaInputFile ()
{
    delete _inputFile;
    delete _fromYca;
}


1225
void
1226 1227 1228 1229
RgbaInputFile::setFrameBuffer (Rgba *base, size_t xStride, size_t yStride)
{
    if (_fromYca)
    {
1230 1231
    Lock lock (*_fromYca);
    _fromYca->setFrameBuffer (base, xStride, yStride, _channelNamePrefix);
1232 1233 1234
    }
    else
    {
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
    size_t xs = xStride * sizeof (Rgba);
    size_t ys = yStride * sizeof (Rgba);

    FrameBuffer fb;

    fb.insert (_channelNamePrefix + "R",
           Slice (HALF,
              (char *) &base[0].r,
              xs, ys,
              1, 1,		// xSampling, ySampling
              0.0));	// fillValue

    fb.insert (_channelNamePrefix + "G",
           Slice (HALF,
              (char *) &base[0].g,
              xs, ys,
              1, 1,		// xSampling, ySampling
              0.0));	// fillValue

    fb.insert (_channelNamePrefix + "B",
           Slice (HALF,
              (char *) &base[0].b,
              xs, ys,
              1, 1,		// xSampling, ySampling
              0.0));	// fillValue

    fb.insert (_channelNamePrefix + "A",
           Slice (HALF,
              (char *) &base[0].a,
              xs, ys,
              1, 1,		// xSampling, ySampling
              1.0));	// fillValue

    _inputFile->setFrameBuffer (fb);
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
    }
}


void
RgbaInputFile::setLayerName (const string &layerName)
{
    delete _fromYca;
    _fromYca = 0;

    _channelNamePrefix = prefixFromLayerName (layerName, _inputFile->header());

    RgbaChannels rgbaChannels = channels();

    if (rgbaChannels & (WRITE_Y | WRITE_C))
1284
    _fromYca = new FromYca (*_inputFile, rgbaChannels);
1285 1286 1287 1288 1289 1290

    FrameBuffer fb;
    _inputFile->setFrameBuffer (fb);
}


1291
void
1292 1293 1294 1295
RgbaInputFile::readPixels (int scanLine1, int scanLine2)
{
    if (_fromYca)
    {
1296 1297
    Lock lock (*_fromYca);
    _fromYca->readPixels (scanLine1, scanLine2);
1298 1299 1300
    }
    else
    {
1301
    _inputFile->readPixels (scanLine1, scanLine2);
1302 1303 1304 1305
    }
}


1306
void
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
RgbaInputFile::readPixels (int scanLine)
{
    readPixels (scanLine, scanLine);
}


bool
RgbaInputFile::isComplete () const
{
    return _inputFile->isComplete();
}


const Header &
RgbaInputFile::header () const
{
    return _inputFile->header();
}


const char *
RgbaInputFile::fileName () const
{
    return _inputFile->fileName();
}


1334
const FrameBuffer &
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
RgbaInputFile::frameBuffer () const
{
    return _inputFile->frameBuffer();
}


const Imath::Box2i &
RgbaInputFile::displayWindow () const
{
    return _inputFile->header().displayWindow();
}


const Imath::Box2i &
RgbaInputFile::dataWindow () const
{
    return _inputFile->header().dataWindow();
}


1355
float
1356 1357 1358 1359 1360 1361
RgbaInputFile::pixelAspectRatio () const
{
    return _inputFile->header().pixelAspectRatio();
}


1362
const Imath::V2f
1363 1364 1365 1366 1367 1368
RgbaInputFile::screenWindowCenter () const
{
    return _inputFile->header().screenWindowCenter();
}


1369
float
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
RgbaInputFile::screenWindowWidth () const
{
    return _inputFile->header().screenWindowWidth();
}


LineOrder
RgbaInputFile::lineOrder () const
{
    return _inputFile->header().lineOrder();
}


Compression
RgbaInputFile::compression () const
{
    return _inputFile->header().compression();
}


1390
RgbaChannels
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
RgbaInputFile::channels () const
{
    return rgbaChannels (_inputFile->header().channels(), _channelNamePrefix);
}


int
RgbaInputFile::version () const
{
    return _inputFile->version();
}


} // namespace Imf