Coverage Report

Created: 2026-08-14 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opencv/3rdparty/openexr/IlmImf/ImfOutputFile.cpp
Line
Count
Source
1
//
2
///\todo: version needs fixing!
3
//
4
5
///////////////////////////////////////////////////////////////////////////
6
//
7
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
8
// Digital Ltd. LLC
9
// 
10
// All rights reserved.
11
// 
12
// Redistribution and use in source and binary forms, with or without
13
// modification, are permitted provided that the following conditions are
14
// met:
15
// *       Redistributions of source code must retain the above copyright
16
// notice, this list of conditions and the following disclaimer.
17
// *       Redistributions in binary form must reproduce the above
18
// copyright notice, this list of conditions and the following disclaimer
19
// in the documentation and/or other materials provided with the
20
// distribution.
21
// *       Neither the name of Industrial Light & Magic nor the names of
22
// its contributors may be used to endorse or promote products derived
23
// from this software without specific prior written permission. 
24
// 
25
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
//
37
///////////////////////////////////////////////////////////////////////////
38
39
40
//-----------------------------------------------------------------------------
41
//
42
//  class OutputFile
43
//
44
//-----------------------------------------------------------------------------
45
46
#include <ImfOutputFile.h>
47
#include <ImfInputFile.h>
48
#include <ImfChannelList.h>
49
#include <ImfMisc.h>
50
#include <ImfStdIO.h>
51
#include <ImfCompressor.h>
52
#include "ImathBox.h"
53
#include "ImathFun.h"
54
#include <ImfArray.h>
55
#include "ImfXdr.h"
56
#include <ImfPreviewImageAttribute.h>
57
#include <ImfPartType.h>
58
#include "IlmThreadPool.h"
59
#include "ImfOutputStreamMutex.h"
60
#include "IlmThreadSemaphore.h"
61
#include "IlmThreadMutex.h"
62
#include "Iex.h"
63
#include "ImfInputPart.h"
64
#include "ImfNamespace.h"
65
#include "ImfOutputPartData.h"
66
67
#include <string>
68
#include <vector>
69
#include <fstream>
70
#include <assert.h>
71
#include <algorithm>
72
73
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
74
75
using IMATH_NAMESPACE::Box2i;
76
using IMATH_NAMESPACE::divp;
77
using IMATH_NAMESPACE::modp;
78
using std::string;
79
using std::vector;
80
using std::ofstream;
81
using std::min;
82
using std::max;
83
using ILMTHREAD_NAMESPACE::Mutex;
84
using ILMTHREAD_NAMESPACE::Lock;
85
using ILMTHREAD_NAMESPACE::Semaphore;
86
using ILMTHREAD_NAMESPACE::Task;
87
using ILMTHREAD_NAMESPACE::TaskGroup;
88
using ILMTHREAD_NAMESPACE::ThreadPool;
89
90
91
namespace {
92
93
94
struct OutSliceInfo
95
{
96
    PixelType   type;
97
    const char *  base;
98
    size_t    xStride;
99
    size_t    yStride;
100
    int     xSampling;
101
    int     ySampling;
102
    bool    zero;
103
104
    OutSliceInfo (PixelType type = HALF,
105
            const char *base = 0,
106
            size_t xStride = 0,
107
            size_t yStride = 0,
108
            int xSampling = 1,
109
            int ySampling = 1,
110
            bool zero = false);
111
                  
112
};
113
114
115
OutSliceInfo::OutSliceInfo (PixelType t,
116
                const char *b,
117
                size_t xs, size_t ys,
118
                int xsm, int ysm,
119
                bool z)
120
:
121
0
    type (t),
122
0
    base (b),
123
0
    xStride (xs),
124
0
    yStride (ys),
125
0
    xSampling (xsm),
126
0
    ySampling (ysm),
127
0
    zero (z)
128
0
{
129
    // empty
130
0
}
131
132
133
struct LineBuffer
134
{
135
    Array<char>   buffer;
136
    const char *  dataPtr;
137
    int     dataSize;
138
    char *    endOfLineBufferData;
139
    int     minY;
140
    int     maxY;
141
    int     scanLineMin;
142
    int     scanLineMax;
143
    Compressor *  compressor;
144
    bool    partiallyFull;        // has incomplete data
145
    bool    hasException;
146
    string    exception;
147
148
    LineBuffer (Compressor *comp);
149
    ~LineBuffer ();
150
151
0
    void    wait () {_sem.wait();}
152
0
    void    post () {_sem.post();}
153
154
  private:
155
156
    Semaphore   _sem;
157
};
158
159
160
LineBuffer::LineBuffer (Compressor *comp) :
161
0
    dataPtr (0),
162
0
    dataSize (0),
163
0
    compressor (comp),
164
0
    partiallyFull (false),
165
0
    hasException (false),
166
0
    exception (),
167
0
    _sem (1)
168
0
{
169
    // empty
170
0
}
171
172
173
LineBuffer::~LineBuffer ()
174
0
{
175
0
    delete compressor;
176
0
}
177
178
} // namespace
179
180
struct OutputFile::Data
181
{
182
    Header     header;    // the image header
183
    bool                 multiPart;   // is the file multipart?
184
    int      version;               // version attribute \todo NOT BEING WRITTEN PROPERLY
185
    Int64    previewPosition;       // file position for preview
186
    FrameBuffer    frameBuffer;           // framebuffer to write into
187
    int      currentScanLine;       // next scanline to be written
188
    int      missingScanLines;      // number of lines to write
189
    LineOrder    lineOrder;   // the file's lineorder
190
    int      minX;      // data window's min x coord
191
    int      maxX;      // data window's max x coord
192
    int      minY;      // data window's min y coord
193
    int      maxY;      // data window's max x coord
194
    vector<Int64>  lineOffsets;   // stores offsets in file for
195
            // each scanline
196
    vector<size_t>   bytesPerLine;          // combined size of a line over
197
                                                // all channels
198
    vector<size_t>   offsetInLineBuffer;    // offset for each scanline in
199
                                                // its linebuffer
200
    Compressor::Format   format;                // compressor's data format
201
    vector<OutSliceInfo> slices;    // info about channels in file
202
    Int64    lineOffsetsPosition;   // file position for line
203
                                                // offset table
204
205
    vector<LineBuffer*>  lineBuffers;           // each holds one line buffer
206
    int      linesInBuffer;         // number of scanlines each
207
                                                // buffer holds
208
    size_t     lineBufferSize;        // size of the line buffer
209
210
    int                  partNumber;            // the output part number
211
    OutputStreamMutex *  _streamData;         
212
    bool                 _deleteStream;
213
     Data (int numThreads);
214
    ~Data ();
215
216
217
    inline LineBuffer * getLineBuffer (int number); // hash function from line
218
                    // buffer indices into our
219
                // vector of line buffers
220
};
221
222
223
OutputFile::Data::Data (int numThreads):
224
0
    lineOffsetsPosition (0),
225
0
    partNumber (-1),
226
0
    _streamData(0),
227
0
    _deleteStream(false)
228
0
{
229
    //
230
    // We need at least one lineBuffer, but if threading is used,
231
    // to keep n threads busy we need 2*n lineBuffers.
232
    //
233
234
0
    lineBuffers.resize (max (1, 2 * numThreads));
235
0
}
236
237
238
OutputFile::Data::~Data ()
239
0
{
240
0
    for (size_t i = 0; i < lineBuffers.size(); i++)
241
0
        delete lineBuffers[i];
242
0
}
243
244
245
LineBuffer*
246
OutputFile::Data::getLineBuffer (int number)
247
0
{
248
0
    return lineBuffers[number % lineBuffers.size()];
249
0
}
250
251
namespace {
252
253
Int64
254
writeLineOffsets (OPENEXR_IMF_INTERNAL_NAMESPACE::OStream &os, const vector<Int64> &lineOffsets)
255
0
{
256
0
    Int64 pos = os.tellp();
257
258
0
    if (pos == -1)
259
0
  IEX_NAMESPACE::throwErrnoExc ("Cannot determine current file position (%T).");
260
    
261
0
    for (unsigned int i = 0; i < lineOffsets.size(); i++)
262
0
  Xdr::write<StreamIO> (os, lineOffsets[i]);
263
264
0
    return pos;
265
0
}
266
267
268
void
269
writePixelData (OutputStreamMutex *filedata,
270
                OutputFile::Data *partdata,
271
                int lineBufferMinY,
272
                const char pixelData[],
273
                int pixelDataSize)
274
0
{
275
    //
276
    // Store a block of pixel data in the output file, and try
277
    // to keep track of the current writing position the file
278
    // without calling tellp() (tellp() can be fairly expensive).
279
    //
280
281
0
    Int64 currentPosition = filedata->currentPosition;
282
0
    filedata->currentPosition = 0;
283
284
0
    if (currentPosition == 0)
285
0
        currentPosition = filedata->os->tellp();
286
287
0
    partdata->lineOffsets[(partdata->currentScanLine - partdata->minY) / partdata->linesInBuffer] =
288
0
        currentPosition;
289
290
    #ifdef DEBUG
291
292
        assert (filedata->os->tellp() == currentPosition);
293
294
    #endif
295
    
296
  
297
  
298
0
    if (partdata->multiPart)
299
0
    {
300
0
        OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::write <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*filedata->os, partdata->partNumber);
301
0
    }
302
    
303
0
    OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::write <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*filedata->os, lineBufferMinY);
304
0
    OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::write <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*filedata->os, pixelDataSize);
305
0
    filedata->os->write (pixelData, pixelDataSize);
306
307
0
    filedata->currentPosition = currentPosition +
308
0
                           Xdr::size<int>() +
309
0
                           Xdr::size<int>() +
310
0
                           pixelDataSize;
311
312
0
    if (partdata->multiPart)
313
0
    {
314
0
        filedata->currentPosition += Xdr::size<int>();
315
0
    }
316
0
}
317
318
319
inline void
320
writePixelData (OutputStreamMutex* filedata,
321
                OutputFile::Data *partdata,
322
                const LineBuffer *lineBuffer)
323
0
{
324
0
    writePixelData (filedata, partdata,
325
0
                    lineBuffer->minY,
326
0
                    lineBuffer->dataPtr,
327
0
                    lineBuffer->dataSize);
328
0
}
329
330
331
void
332
convertToXdr (OutputFile::Data *ofd,
333
              Array<char> &lineBuffer,
334
              int lineBufferMinY,
335
              int lineBufferMaxY,
336
              int inSize)
337
0
{
338
    //
339
    // Convert the contents of a lineBuffer from the machine's native
340
    // representation to Xdr format.  This function is called by
341
    // CompressLineBuffer::execute(), below, if the compressor wanted
342
    // its input pixel data in the machine's native format, but then
343
    // failed to compress the data (most compressors will expand rather
344
    // than compress random input data).
345
    //
346
    // Note that this routine assumes that the machine's native
347
    // representation of the pixel data has the same size as the
348
    // Xdr representation.  This makes it possible to convert the
349
    // pixel data in place, without an intermediate temporary buffer.
350
    //
351
   
352
    //
353
    // Iterate over all scanlines in the lineBuffer to convert.
354
    //
355
356
0
    char *writePtr = &lineBuffer[0];
357
0
    for (int y = lineBufferMinY; y <= lineBufferMaxY; y++)
358
0
    {
359
  //
360
        // Set these to point to the start of line y.
361
        // We will write to writePtr from readPtr.
362
  //
363
364
0
        const char *readPtr = writePtr;
365
        
366
  //
367
        // Iterate over all slices in the file.
368
  //
369
  
370
0
        for (unsigned int i = 0; i < ofd->slices.size(); ++i)
371
0
        {
372
            //
373
            // Test if scan line y of this channel is
374
            // contains any data (the scan line contains
375
            // data only if y % ySampling == 0).
376
            //
377
378
0
            const OutSliceInfo &slice = ofd->slices[i];
379
380
0
            if (modp (y, slice.ySampling) != 0)
381
0
                continue;
382
383
            //
384
            // Find the number of sampled pixels, dMaxX-dMinX+1, for
385
      // slice i in scan line y (i.e. pixels within the data window
386
            // for which x % xSampling == 0).
387
            //
388
389
0
            int dMinX = divp (ofd->minX, slice.xSampling);
390
0
            int dMaxX = divp (ofd->maxX, slice.xSampling);
391
            
392
      //
393
            // Convert the samples in place.
394
      //
395
            
396
0
            convertInPlace (writePtr, readPtr, slice.type, dMaxX - dMinX + 1);
397
0
        }
398
0
    }
399
0
}
400
401
402
//
403
// A LineBufferTask encapsulates the task of copying a set of scanlines
404
// from the user's frame buffer into a LineBuffer object, compressing
405
// the data if necessary.
406
//
407
408
class LineBufferTask: public Task
409
{
410
  public:
411
412
    LineBufferTask (TaskGroup *group,
413
                    OutputFile::Data *ofd,
414
        int number,
415
                    int scanLineMin,
416
        int scanLineMax);
417
418
    virtual ~LineBufferTask (); 
419
420
    virtual void  execute ();
421
422
  private:
423
424
    OutputFile::Data *  _ofd;
425
    LineBuffer *  _lineBuffer;
426
};
427
428
429
LineBufferTask::LineBufferTask
430
    (TaskGroup *group,
431
     OutputFile::Data *ofd,
432
     int number,
433
     int scanLineMin,
434
     int scanLineMax)
435
:
436
0
    Task (group),
437
0
    _ofd (ofd),
438
0
    _lineBuffer (_ofd->getLineBuffer(number))
439
0
{
440
    //
441
    // Wait for the lineBuffer to become available
442
    //
443
444
0
    _lineBuffer->wait ();
445
    
446
    //
447
    // Initialize the lineBuffer data if necessary
448
    //
449
450
0
    if (!_lineBuffer->partiallyFull)
451
0
    {
452
0
        _lineBuffer->endOfLineBufferData = _lineBuffer->buffer;
453
454
0
        _lineBuffer->minY = _ofd->minY + number * _ofd->linesInBuffer;
455
456
0
        _lineBuffer->maxY = min (_lineBuffer->minY + _ofd->linesInBuffer - 1,
457
0
         _ofd->maxY);
458
459
0
        _lineBuffer->partiallyFull = true;
460
0
    }
461
    
462
0
    _lineBuffer->scanLineMin = max (_lineBuffer->minY, scanLineMin);
463
0
    _lineBuffer->scanLineMax = min (_lineBuffer->maxY, scanLineMax);
464
0
}
465
466
467
LineBufferTask::~LineBufferTask ()
468
0
{
469
    //
470
    // Signal that the line buffer is now free
471
    //
472
473
0
    _lineBuffer->post ();
474
0
}
475
476
477
void
478
LineBufferTask::execute ()
479
0
{
480
0
    try
481
0
    {
482
        //
483
        // First copy the pixel data from the
484
  // frame buffer into the line buffer
485
        //
486
        
487
0
        int yStart, yStop, dy;
488
489
0
        if (_ofd->lineOrder == INCREASING_Y)
490
0
        {
491
0
            yStart = _lineBuffer->scanLineMin;
492
0
            yStop = _lineBuffer->scanLineMax + 1;
493
0
            dy = 1;
494
0
        }
495
0
        else
496
0
        {
497
0
            yStart = _lineBuffer->scanLineMax;
498
0
            yStop = _lineBuffer->scanLineMin - 1;
499
0
            dy = -1;
500
0
        }
501
    
502
0
  int y;
503
504
0
        for (y = yStart; y != yStop; y += dy)
505
0
        {
506
            //
507
            // Gather one scan line's worth of pixel data and store
508
            // them in _ofd->lineBuffer.
509
            //
510
        
511
0
            char *writePtr = _lineBuffer->buffer +
512
0
                             _ofd->offsetInLineBuffer[y - _ofd->minY];
513
            //
514
            // Iterate over all image channels.
515
            //
516
517
0
            for (unsigned int i = 0; i < _ofd->slices.size(); ++i)
518
0
            {
519
                //
520
                // Test if scan line y of this channel contains any data
521
    // (the scan line contains data only if y % ySampling == 0).
522
                //
523
        
524
0
                const OutSliceInfo &slice = _ofd->slices[i];
525
        
526
0
                if (modp (y, slice.ySampling) != 0)
527
0
                    continue;
528
        
529
                //
530
                // Find the x coordinates of the leftmost and rightmost
531
                // sampled pixels (i.e. pixels within the data window
532
                // for which x % xSampling == 0).
533
                //
534
        
535
0
                int dMinX = divp (_ofd->minX, slice.xSampling);
536
0
                int dMaxX = divp (_ofd->maxX, slice.xSampling);
537
        
538
                //
539
    // Fill the line buffer with with pixel data.
540
                //
541
        
542
0
                if (slice.zero)
543
0
                {
544
                    //
545
                    // The frame buffer contains no data for this channel.
546
                    // Store zeroes in _lineBuffer->buffer.
547
                    //
548
                    
549
0
                    fillChannelWithZeroes (writePtr, _ofd->format, slice.type,
550
0
                                           dMaxX - dMinX + 1);
551
0
                }
552
0
                else
553
0
                {
554
                    //
555
                    // If necessary, convert the pixel data to Xdr format.
556
        // Then store the pixel data in _ofd->lineBuffer.
557
                    //
558
        
559
0
                    const char *linePtr = slice.base +
560
0
                                          divp (y, slice.ySampling) *
561
0
                                          slice.yStride;
562
        
563
0
                    const char *readPtr = linePtr + dMinX * slice.xStride;
564
0
                    const char *endPtr  = linePtr + dMaxX * slice.xStride;
565
    
566
0
                    copyFromFrameBuffer (writePtr, readPtr, endPtr,
567
0
                                         slice.xStride, _ofd->format,
568
0
                                         slice.type);
569
0
                }
570
0
            }
571
        
572
0
            if (_lineBuffer->endOfLineBufferData < writePtr)
573
0
                _lineBuffer->endOfLineBufferData = writePtr;
574
        
575
            #ifdef DEBUG
576
        
577
                assert (writePtr - (_lineBuffer->buffer +
578
                        _ofd->offsetInLineBuffer[y - _ofd->minY]) ==
579
                        (int) _ofd->bytesPerLine[y - _ofd->minY]);
580
        
581
            #endif
582
        
583
0
        }
584
    
585
        //
586
        // If the next scanline isn't past the bounds of the lineBuffer
587
        // then we are done, otherwise compress the linebuffer
588
        //
589
    
590
0
        if (y >= _lineBuffer->minY && y <= _lineBuffer->maxY)
591
0
            return;
592
    
593
0
        _lineBuffer->dataPtr = _lineBuffer->buffer;
594
595
0
        _lineBuffer->dataSize = _lineBuffer->endOfLineBufferData -
596
0
                                _lineBuffer->buffer;
597
    
598
  //
599
        // Compress the data
600
  //
601
602
0
        Compressor *compressor = _lineBuffer->compressor;
603
604
0
        if (compressor)
605
0
        {
606
0
            const char *compPtr;
607
608
0
            int compSize = compressor->compress (_lineBuffer->dataPtr,
609
0
                                                 _lineBuffer->dataSize,
610
0
                                                 _lineBuffer->minY, compPtr);
611
    
612
0
            if (compSize < _lineBuffer->dataSize)
613
0
            {
614
0
                _lineBuffer->dataSize = compSize;
615
0
                _lineBuffer->dataPtr = compPtr;
616
0
            }
617
0
            else if (_ofd->format == Compressor::NATIVE)
618
0
            {
619
                //
620
                // The data did not shrink during compression, but
621
                // we cannot write to the file using the machine's
622
                // native format, so we need to convert the lineBuffer
623
                // to Xdr.
624
                //
625
    
626
0
                convertToXdr (_ofd, _lineBuffer->buffer, _lineBuffer->minY,
627
0
                              _lineBuffer->maxY, _lineBuffer->dataSize);
628
0
            }
629
0
        }
630
631
0
        _lineBuffer->partiallyFull = false;
632
0
    }
633
0
    catch (std::exception &e)
634
0
    {
635
0
        if (!_lineBuffer->hasException)
636
0
        {
637
0
            _lineBuffer->exception = e.what ();
638
0
            _lineBuffer->hasException = true;
639
0
        }
640
0
    }
641
0
    catch (...)
642
0
    {
643
0
        if (!_lineBuffer->hasException)
644
0
        {
645
0
            _lineBuffer->exception = "unrecognized exception";
646
0
            _lineBuffer->hasException = true;
647
0
        }
648
0
    }
649
0
}
650
651
} // namespace
652
653
654
OutputFile::OutputFile
655
    (const char fileName[],
656
     const Header &header,
657
     int numThreads)
658
:
659
0
    _data (new Data (numThreads))
660
0
{
661
0
    _data->_streamData=new OutputStreamMutex ();
662
0
    _data->_deleteStream=true;
663
0
    try
664
0
    {
665
0
        header.sanityCheck();
666
0
        _data->_streamData->os = new StdOFStream (fileName);
667
0
        _data->multiPart=false; // only one header, not multipart
668
0
        initialize (header);
669
0
        _data->_streamData->currentPosition = _data->_streamData->os->tellp();
670
        
671
        // Write header and empty offset table to the file.
672
0
        writeMagicNumberAndVersionField(*_data->_streamData->os, _data->header);
673
0
        _data->previewPosition =
674
0
            _data->header.writeTo (*_data->_streamData->os);
675
0
        _data->lineOffsetsPosition =
676
0
            writeLineOffsets (*_data->_streamData->os,_data->lineOffsets);
677
0
    }
678
0
    catch (IEX_NAMESPACE::BaseExc &e)
679
0
    {
680
        // ~OutputFile will not run, so free memory here
681
0
        if (_data)
682
0
        {
683
0
            if (_data->_streamData)
684
0
            {
685
0
                delete _data->_streamData->os;
686
0
                delete _data->_streamData;
687
0
            }
688
689
0
            delete _data;
690
0
        }
691
692
0
  REPLACE_EXC (e, "Cannot open image file "
693
0
      "\"" << fileName << "\". " << e.what());
694
0
  throw;
695
0
    }
696
0
    catch (...)
697
0
    {
698
        // ~OutputFile will not run, so free memory here
699
0
        if (_data)
700
0
        {
701
0
            if (_data->_streamData)
702
0
            {
703
0
                delete _data->_streamData->os;
704
0
                delete _data->_streamData;
705
0
            }
706
0
            delete _data;
707
0
        }
708
709
0
        throw;
710
0
    }
711
0
}
712
713
714
OutputFile::OutputFile
715
    (OPENEXR_IMF_INTERNAL_NAMESPACE::OStream &os,
716
     const Header &header,
717
     int numThreads)
718
:
719
0
    _data (new Data (numThreads))
720
0
{
721
0
    _data->_streamData=new OutputStreamMutex ();
722
0
    _data->_deleteStream=false;
723
0
    try
724
0
    {
725
0
        header.sanityCheck();
726
0
        _data->_streamData->os = &os;
727
0
        _data->multiPart=false;
728
0
        initialize (header);
729
0
        _data->_streamData->currentPosition = _data->_streamData->os->tellp();
730
731
        // Write header and empty offset table to the file.
732
0
        writeMagicNumberAndVersionField(*_data->_streamData->os, _data->header);
733
0
        _data->previewPosition =
734
0
            _data->header.writeTo (*_data->_streamData->os);
735
0
        _data->lineOffsetsPosition =
736
0
            writeLineOffsets (*_data->_streamData->os, _data->lineOffsets);
737
0
    }
738
0
    catch (IEX_NAMESPACE::BaseExc &e)
739
0
    {
740
        // ~OutputFile will not run, so free memory here
741
0
        if (_data)
742
0
        {
743
0
            if (_data->_streamData)
744
0
                delete _data->_streamData;
745
0
            delete _data;
746
0
        }
747
748
0
        REPLACE_EXC (e, "Cannot open image file "
749
0
                     "\"" << os.fileName() << "\". " << e.what());
750
0
        throw;
751
0
    }
752
0
    catch (...)
753
0
    {
754
        // ~OutputFile will not run, so free memory here
755
0
        if (_data)
756
0
        {
757
0
            if (_data->_streamData)
758
0
                delete _data->_streamData;
759
0
            delete _data;
760
0
        }
761
762
0
        throw;
763
0
    }
764
0
}
765
766
0
OutputFile::OutputFile(const OutputPartData* part) : _data(NULL)
767
0
{
768
0
    try
769
0
    {
770
0
        if (part->header.type() != SCANLINEIMAGE)
771
0
            throw IEX_NAMESPACE::ArgExc("Can't build a OutputFile from a type-mismatched part.");
772
773
0
        _data = new Data (part->numThreads);
774
0
        _data->_streamData = part->mutex;
775
0
        _data->_deleteStream=false;
776
0
        _data->multiPart=part->multipart;
777
778
0
        initialize (part->header);
779
0
        _data->partNumber = part->partNumber;
780
0
        _data->lineOffsetsPosition = part->chunkOffsetTablePosition;
781
0
        _data->previewPosition = part->previewPosition;
782
0
    }
783
0
    catch (IEX_NAMESPACE::BaseExc &e)
784
0
    {
785
0
        if (_data) delete _data;
786
787
0
        REPLACE_EXC (e, "Cannot initialize output part "
788
0
                     "\"" << part->partNumber << "\". " << e.what());
789
0
        throw;
790
0
    }
791
0
    catch (...)
792
0
    {
793
0
        if (_data) delete _data;
794
795
0
        throw;
796
0
    }
797
0
}
798
799
void
800
OutputFile::initialize (const Header &header)
801
0
{
802
0
    _data->header = header;
803
804
    // "fix" the type if it happens to be set incorrectly
805
    // (attribute is optional, but ensure it is correct if it exists)
806
0
    if(_data->header.hasType())
807
0
    {
808
0
        _data->header.setType(SCANLINEIMAGE);
809
0
    }
810
    
811
0
    const Box2i &dataWindow = header.dataWindow();
812
813
0
    _data->currentScanLine = (header.lineOrder() == INCREASING_Y)?
814
0
         dataWindow.min.y: dataWindow.max.y;
815
816
0
    _data->missingScanLines = dataWindow.max.y - dataWindow.min.y + 1;
817
0
    _data->lineOrder = header.lineOrder();
818
0
    _data->minX = dataWindow.min.x;
819
0
    _data->maxX = dataWindow.max.x;
820
0
    _data->minY = dataWindow.min.y;
821
0
    _data->maxY = dataWindow.max.y;
822
823
0
    size_t maxBytesPerLine = bytesPerLineTable (_data->header,
824
0
            _data->bytesPerLine);
825
826
0
    for (size_t i = 0; i < _data->lineBuffers.size(); ++i)
827
0
    {
828
0
        _data->lineBuffers[i] =
829
0
      new LineBuffer (newCompressor (_data->header.compression(),
830
0
             maxBytesPerLine,
831
0
             _data->header));
832
0
    }
833
834
0
    LineBuffer *lineBuffer = _data->lineBuffers[0];
835
0
    _data->format = defaultFormat (lineBuffer->compressor);
836
0
    _data->linesInBuffer = numLinesInBuffer (lineBuffer->compressor);
837
0
    _data->lineBufferSize = maxBytesPerLine * _data->linesInBuffer;
838
839
0
    for (size_t i = 0; i < _data->lineBuffers.size(); i++)
840
0
        _data->lineBuffers[i]->buffer.resizeErase(_data->lineBufferSize);
841
842
0
    int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +
843
0
        _data->linesInBuffer) / _data->linesInBuffer;
844
845
0
    _data->lineOffsets.resize (lineOffsetSize);
846
    
847
    
848
0
    offsetInLineBufferTable (_data->bytesPerLine,
849
0
           _data->linesInBuffer,
850
0
           _data->offsetInLineBuffer);
851
0
}
852
853
854
OutputFile::~OutputFile ()
855
0
{
856
0
    if (_data)
857
0
    {
858
0
        {
859
0
            Lock lock(*_data->_streamData);
860
0
            Int64 originalPosition = _data->_streamData->os->tellp();
861
862
0
            if (_data->lineOffsetsPosition > 0)
863
0
            {
864
0
                try
865
0
                {
866
0
                    _data->_streamData->os->seekp (_data->lineOffsetsPosition);
867
0
                    writeLineOffsets (*_data->_streamData->os, _data->lineOffsets);
868
869
                    //
870
                    // Restore the original position.
871
                    //
872
0
                    _data->_streamData->os->seekp (originalPosition);
873
0
                }
874
0
                catch (...)
875
0
                {
876
                    //
877
                    // We cannot safely throw any exceptions from here.
878
                    // This destructor may have been called because the
879
                    // stack is currently being unwound for another
880
                    // exception.
881
                    //
882
0
                }
883
0
            }
884
0
        }
885
886
0
        if (_data->_deleteStream && _data->_streamData)
887
0
            delete _data->_streamData->os;
888
889
0
        if (_data->partNumber == -1 && _data->_streamData)
890
0
            delete _data->_streamData;
891
892
0
  delete _data;
893
0
    }
894
895
0
}
896
897
898
const char *
899
OutputFile::fileName () const
900
0
{
901
0
    return _data->_streamData->os->fileName();
902
0
}
903
904
905
const Header &
906
OutputFile::header () const
907
0
{
908
0
    return _data->header;
909
0
}
910
911
912
void  
913
OutputFile::setFrameBuffer (const FrameBuffer &frameBuffer)
914
0
{
915
0
    Lock lock (*_data->_streamData);
916
    
917
    //
918
    // Check if the new frame buffer descriptor
919
    // is compatible with the image file header.
920
    //
921
922
0
    const ChannelList &channels = _data->header.channels();
923
924
0
    for (ChannelList::ConstIterator i = channels.begin();
925
0
   i != channels.end();
926
0
   ++i)
927
0
    {
928
0
  FrameBuffer::ConstIterator j = frameBuffer.find (i.name());
929
930
0
  if (j == frameBuffer.end())
931
0
      continue;
932
933
0
  if (i.channel().type != j.slice().type)
934
0
  {
935
0
      THROW (IEX_NAMESPACE::ArgExc, "Pixel type of \"" << i.name() << "\" channel "
936
0
              "of output file \"" << fileName() << "\" is "
937
0
              "not compatible with the frame buffer's "
938
0
              "pixel type.");
939
0
  }
940
941
0
  if (i.channel().xSampling != j.slice().xSampling ||
942
0
      i.channel().ySampling != j.slice().ySampling)
943
0
  {
944
0
      THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors "
945
0
        "of \"" << i.name() << "\" channel "
946
0
        "of output file \"" << fileName() << "\" are "
947
0
        "not compatible with the frame buffer's "
948
0
        "subsampling factors.");
949
0
  }
950
0
    }
951
    
952
    //
953
    // Initialize slice table for writePixels().
954
    //
955
956
0
    vector<OutSliceInfo> slices;
957
958
0
    for (ChannelList::ConstIterator i = channels.begin();
959
0
   i != channels.end();
960
0
   ++i)
961
0
    {
962
0
  FrameBuffer::ConstIterator j = frameBuffer.find (i.name());
963
964
0
  if (j == frameBuffer.end())
965
0
  {
966
      //
967
      // Channel i is not present in the frame buffer.
968
      // In the file, channel i will contain only zeroes.
969
      //
970
971
0
      slices.push_back (OutSliceInfo (i.channel().type,
972
0
              0, // base
973
0
              0, // xStride,
974
0
              0, // yStride,
975
0
              i.channel().xSampling,
976
0
              i.channel().ySampling,
977
0
              true)); // zero
978
0
  }
979
0
  else
980
0
  {
981
      //
982
      // Channel i is present in the frame buffer.
983
      //
984
985
0
      slices.push_back (OutSliceInfo (j.slice().type,
986
0
              j.slice().base,
987
0
              j.slice().xStride,
988
0
              j.slice().yStride,
989
0
              j.slice().xSampling,
990
0
              j.slice().ySampling,
991
0
              false)); // zero
992
0
  }
993
0
    }
994
995
    //
996
    // Store the new frame buffer.
997
    //
998
999
0
    _data->frameBuffer = frameBuffer;
1000
0
    _data->slices = slices;
1001
0
}
1002
1003
1004
const FrameBuffer &
1005
OutputFile::frameBuffer () const
1006
0
{
1007
0
    Lock lock (*_data->_streamData);
1008
0
    return _data->frameBuffer;
1009
0
}
1010
1011
1012
void  
1013
OutputFile::writePixels (int numScanLines)
1014
0
{
1015
0
    try
1016
0
    {
1017
0
        Lock lock (*_data->_streamData);
1018
1019
0
  if (_data->slices.size() == 0)
1020
0
      throw IEX_NAMESPACE::ArgExc ("No frame buffer specified "
1021
0
             "as pixel data source.");
1022
1023
        //
1024
        // Maintain two iterators:
1025
        //     nextWriteBuffer: next linebuffer to be written to the file
1026
        //     nextCompressBuffer: next linebuffer to compress
1027
        //
1028
1029
0
        int first = (_data->currentScanLine - _data->minY) /
1030
0
                         _data->linesInBuffer;
1031
1032
0
        int nextWriteBuffer = first;
1033
0
        int nextCompressBuffer;
1034
0
        int stop;
1035
0
        int step;
1036
0
        int scanLineMin;
1037
0
        int scanLineMax;
1038
1039
0
        {
1040
            //
1041
            // Create a task group for all line buffer tasks. When the
1042
            // taskgroup goes out of scope, the destructor waits until
1043
      // all tasks are complete.
1044
            //
1045
            
1046
0
            TaskGroup taskGroup;
1047
            
1048
            //
1049
            // Determine the range of lineBuffers that intersect the scan
1050
      // line range.  Then add the initial compression tasks to the
1051
      // thread pool.  We always add in at least one task but the
1052
      // individual task might not do anything if numScanLines == 0.
1053
            //
1054
    
1055
0
            if (_data->lineOrder == INCREASING_Y)
1056
0
            {
1057
0
                int last = (_data->currentScanLine + (numScanLines - 1) -
1058
0
                            _data->minY) / _data->linesInBuffer;
1059
    
1060
0
                scanLineMin = _data->currentScanLine;
1061
0
                scanLineMax = _data->currentScanLine + numScanLines - 1;
1062
    
1063
0
                int numTasks = max (min ((int)_data->lineBuffers.size(),
1064
0
                                         last - first + 1),
1065
0
            1);
1066
1067
0
                for (int i = 0; i < numTasks; i++)
1068
0
    {
1069
0
                    ThreadPool::addGlobalTask
1070
0
                        (new LineBufferTask (&taskGroup, _data, first + i,
1071
0
                                             scanLineMin, scanLineMax));
1072
0
    }
1073
    
1074
0
                nextCompressBuffer = first + numTasks;
1075
0
                stop = last + 1;
1076
0
                step = 1;
1077
0
            }
1078
0
            else
1079
0
            {
1080
0
                int last = (_data->currentScanLine - (numScanLines - 1) -
1081
0
                            _data->minY) / _data->linesInBuffer;
1082
    
1083
0
                scanLineMax = _data->currentScanLine;
1084
0
                scanLineMin = _data->currentScanLine - numScanLines + 1;
1085
    
1086
0
                int numTasks = max (min ((int)_data->lineBuffers.size(),
1087
0
                                         first - last + 1),
1088
0
            1);
1089
1090
0
                for (int i = 0; i < numTasks; i++)
1091
0
    {
1092
0
                    ThreadPool::addGlobalTask
1093
0
                        (new LineBufferTask (&taskGroup, _data, first - i,
1094
0
                                             scanLineMin, scanLineMax));
1095
0
    }
1096
    
1097
0
                nextCompressBuffer = first - numTasks;
1098
0
                stop = last - 1;
1099
0
                step = -1;
1100
0
            }
1101
            
1102
0
            while (true)
1103
0
            {
1104
0
                if (_data->missingScanLines <= 0)
1105
0
                {
1106
0
                    throw IEX_NAMESPACE::ArgExc ("Tried to write more scan lines "
1107
0
                                       "than specified by the data window.");
1108
0
                }
1109
    
1110
    //
1111
                // Wait until the next line buffer is ready to be written
1112
    //
1113
1114
0
                LineBuffer *writeBuffer =
1115
0
        _data->getLineBuffer (nextWriteBuffer);
1116
1117
0
                writeBuffer->wait();
1118
                
1119
0
                int numLines = writeBuffer->scanLineMax - 
1120
0
                               writeBuffer->scanLineMin + 1;
1121
1122
0
                _data->missingScanLines -= numLines;
1123
    
1124
    //
1125
                // If the line buffer is only partially full, then it is
1126
    // not complete and we cannot write it to disk yet.
1127
    //
1128
1129
0
                if (writeBuffer->partiallyFull)
1130
0
                {
1131
0
                    _data->currentScanLine = _data->currentScanLine +
1132
0
                                             step * numLines;
1133
0
                    writeBuffer->post();
1134
    
1135
0
                    return;
1136
0
                }
1137
    
1138
    //
1139
                // Write the line buffer
1140
    //
1141
1142
0
                writePixelData (_data->_streamData, _data, writeBuffer);
1143
0
                nextWriteBuffer += step;
1144
1145
0
                _data->currentScanLine = _data->currentScanLine +
1146
0
                                         step * numLines;
1147
    
1148
                #ifdef DEBUG
1149
    
1150
                    assert (_data->currentScanLine ==
1151
                            ((_data->lineOrder == INCREASING_Y) ?
1152
                             writeBuffer->scanLineMax + 1:
1153
                             writeBuffer->scanLineMin - 1));
1154
    
1155
                #endif
1156
                
1157
    //
1158
                // Release the lock on the line buffer
1159
    //
1160
1161
0
                writeBuffer->post();
1162
                
1163
    //
1164
                // If this was the last line buffer in the scanline range
1165
    //
1166
1167
0
                if (nextWriteBuffer == stop)
1168
0
                    break;
1169
    
1170
    //
1171
                // If there are no more line buffers to compress,
1172
                // then only continue to write out remaining lineBuffers
1173
    //
1174
1175
0
                if (nextCompressBuffer == stop)
1176
0
                    continue;
1177
    
1178
    //
1179
                // Add nextCompressBuffer as a compression task
1180
    //
1181
1182
0
                ThreadPool::addGlobalTask
1183
0
                    (new LineBufferTask (&taskGroup, _data, nextCompressBuffer,
1184
0
                                         scanLineMin, scanLineMax));
1185
                
1186
    //
1187
                // Update the next line buffer we need to compress
1188
    //
1189
1190
0
                nextCompressBuffer += step;
1191
0
            }
1192
        
1193
      //
1194
            // Finish all tasks
1195
      //
1196
0
        }
1197
        
1198
  //
1199
  // Exeption handling:
1200
  //
1201
  // LineBufferTask::execute() may have encountered exceptions, but
1202
  // those exceptions occurred in another thread, not in the thread
1203
  // that is executing this call to OutputFile::writePixels().
1204
  // LineBufferTask::execute() has caught all exceptions and stored
1205
  // the exceptions' what() strings in the line buffers.
1206
  // Now we check if any line buffer contains a stored exception; if
1207
  // this is the case then we re-throw the exception in this thread.
1208
  // (It is possible that multiple line buffers contain stored
1209
  // exceptions.  We re-throw the first exception we find and
1210
  // ignore all others.)
1211
  //
1212
1213
0
  const string *exception = 0;
1214
1215
0
        for (size_t i = 0; i < _data->lineBuffers.size(); ++i)
1216
0
  {
1217
0
            LineBuffer *lineBuffer = _data->lineBuffers[i];
1218
1219
0
      if (lineBuffer->hasException && !exception)
1220
0
    exception = &lineBuffer->exception;
1221
1222
0
      lineBuffer->hasException = false;
1223
0
  }
1224
1225
0
  if (exception)
1226
0
      throw IEX_NAMESPACE::IoExc (*exception);
1227
0
    }
1228
0
    catch (IEX_NAMESPACE::BaseExc &e)
1229
0
    {
1230
0
  REPLACE_EXC (e, "Failed to write pixel data to image "
1231
0
                 "file \"" << fileName() << "\". " << e.what());
1232
0
  throw;
1233
0
    }
1234
0
}
1235
1236
1237
int 
1238
OutputFile::currentScanLine () const
1239
0
{
1240
0
    Lock lock (*_data->_streamData);
1241
0
    return _data->currentScanLine;
1242
0
}
1243
1244
1245
void  
1246
OutputFile::copyPixels (InputFile &in)
1247
0
{
1248
0
    Lock lock (*_data->_streamData);
1249
1250
    //
1251
    // Check if this file's and and the InputFile's
1252
    // headers are compatible.
1253
    //
1254
1255
0
    const Header &hdr = _data->header;
1256
0
    const Header &inHdr = in.header();
1257
1258
0
    if (inHdr.find("tiles") != inHdr.end())
1259
0
  THROW (IEX_NAMESPACE::ArgExc, "Cannot copy pixels from image "
1260
0
          "file \"" << in.fileName() << "\" to image "
1261
0
          "file \"" << fileName() << "\". "
1262
0
                            "The input file is tiled, but the output file is "
1263
0
                            "not. Try using TiledOutputFile::copyPixels "
1264
0
                            "instead.");
1265
1266
0
    if (!(hdr.dataWindow() == inHdr.dataWindow()))
1267
0
  THROW (IEX_NAMESPACE::ArgExc, "Cannot copy pixels from image "
1268
0
          "file \"" << in.fileName() << "\" to image "
1269
0
          "file \"" << fileName() << "\". "
1270
0
                            "The files have different data windows.");
1271
1272
0
    if (!(hdr.lineOrder() == inHdr.lineOrder()))
1273
0
  THROW (IEX_NAMESPACE::ArgExc, "Quick pixel copy from image "
1274
0
          "file \"" << in.fileName() << "\" to image "
1275
0
          "file \"" << fileName() << "\" failed. "
1276
0
          "The files have different line orders.");
1277
1278
0
    if (!(hdr.compression() == inHdr.compression()))
1279
0
  THROW (IEX_NAMESPACE::ArgExc, "Quick pixel copy from image "
1280
0
          "file \"" << in.fileName() << "\" to image "
1281
0
          "file \"" << fileName() << "\" failed. "
1282
0
          "The files use different compression methods.");
1283
1284
0
    if (!(hdr.channels() == inHdr.channels()))
1285
0
  THROW (IEX_NAMESPACE::ArgExc, "Quick pixel copy from image "
1286
0
          "file \"" << in.fileName() << "\" to image "
1287
0
          "file \"" << fileName() << "\" failed.  "
1288
0
          "The files have different channel lists.");
1289
1290
    //
1291
    // Verify that no pixel data have been written to this file yet.
1292
    //
1293
1294
0
    const Box2i &dataWindow = hdr.dataWindow();
1295
1296
0
    if (_data->missingScanLines != dataWindow.max.y - dataWindow.min.y + 1)
1297
0
  THROW (IEX_NAMESPACE::LogicExc, "Quick pixel copy from image "
1298
0
            "file \"" << in.fileName() << "\" to image "
1299
0
            "file \"" << fileName() << "\" failed. "
1300
0
            "\"" << fileName() << "\" already contains "
1301
0
            "pixel data.");
1302
1303
    //
1304
    // Copy the pixel data.
1305
    //
1306
1307
0
    while (_data->missingScanLines > 0)
1308
0
    {
1309
0
  const char *pixelData;
1310
0
  int pixelDataSize;
1311
1312
0
  in.rawPixelData (_data->currentScanLine, pixelData, pixelDataSize);
1313
1314
0
        writePixelData (_data->_streamData, _data, lineBufferMinY (_data->currentScanLine,
1315
0
                                               _data->minY,
1316
0
                                               _data->linesInBuffer),
1317
0
                        pixelData, pixelDataSize);
1318
1319
0
  _data->currentScanLine += (_data->lineOrder == INCREASING_Y)?
1320
0
           _data->linesInBuffer: -_data->linesInBuffer;
1321
1322
0
  _data->missingScanLines -= _data->linesInBuffer;
1323
0
    }
1324
0
}
1325
1326
1327
void
1328
OutputFile::copyPixels( InputPart & in)
1329
0
{
1330
0
    copyPixels(*in.file);
1331
0
}
1332
1333
1334
1335
void
1336
OutputFile::updatePreviewImage (const PreviewRgba newPixels[])
1337
0
{
1338
0
    Lock lock (*_data->_streamData);
1339
1340
0
    if (_data->previewPosition <= 0)
1341
0
  THROW (IEX_NAMESPACE::LogicExc, "Cannot update preview image pixels. "
1342
0
            "File \"" << fileName() << "\" does not "
1343
0
            "contain a preview image.");
1344
1345
    //
1346
    // Store the new pixels in the header's preview image attribute.
1347
    //
1348
1349
0
    PreviewImageAttribute &pia =
1350
0
  _data->header.typedAttribute <PreviewImageAttribute> ("preview");
1351
1352
0
    PreviewImage &pi = pia.value();
1353
0
    PreviewRgba *pixels = pi.pixels();
1354
0
    int numPixels = pi.width() * pi.height();
1355
1356
0
    for (int i = 0; i < numPixels; ++i)
1357
0
  pixels[i] = newPixels[i];
1358
1359
    //
1360
    // Save the current file position, jump to the position in
1361
    // the file where the preview image starts, store the new
1362
    // preview image, and jump back to the saved file position.
1363
    //
1364
1365
0
    Int64 savedPosition = _data->_streamData->os->tellp();
1366
1367
0
    try
1368
0
    {
1369
0
        _data->_streamData->os->seekp (_data->previewPosition);
1370
0
  pia.writeValueTo (*_data->_streamData->os, _data->version);
1371
0
  _data->_streamData->os->seekp (savedPosition);
1372
0
    }
1373
0
    catch (IEX_NAMESPACE::BaseExc &e)
1374
0
    {
1375
0
  REPLACE_EXC (e, "Cannot update preview image pixels for "
1376
0
                 "file \"" << fileName() << "\". " << e.what());
1377
0
  throw;
1378
0
    }
1379
0
}
1380
1381
1382
void  
1383
OutputFile::breakScanLine  (int y, int offset, int length, char c)
1384
0
{
1385
0
    Lock lock (*_data->_streamData);
1386
1387
0
    Int64 position = 
1388
0
  _data->lineOffsets[(y - _data->minY) / _data->linesInBuffer];
1389
1390
0
    if (!position)
1391
0
  THROW (IEX_NAMESPACE::ArgExc, "Cannot overwrite scan line " << y << ". "
1392
0
          "The scan line has not yet been stored in "
1393
0
          "file \"" << fileName() << "\".");
1394
1395
0
    _data->_streamData->currentPosition = 0;
1396
0
    _data->_streamData->os->seekp (position + offset);
1397
1398
0
    for (int i = 0; i < length; ++i)
1399
0
        _data->_streamData->os->write (&c, 1);
1400
0
}
1401
1402
1403
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT