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 
OutSliceInfo(PixelType t,const char * b,size_t xs,size_t ys,int xsm,int ysm,bool z)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     type (t),
122     base (b),
123     xStride (xs),
124     yStride (ys),
125     xSampling (xsm),
126     ySampling (ysm),
127     zero (z)
128 {
129     // empty
130 }
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 
wait__anon067f0eed0111::LineBuffer151     void		wait () {_sem.wait();}
post__anon067f0eed0111::LineBuffer152     void		post () {_sem.post();}
153 
154   private:
155 
156     Semaphore		_sem;
157 };
158 
159 
LineBuffer(Compressor * comp)160 LineBuffer::LineBuffer (Compressor *comp) :
161     dataPtr (0),
162     dataSize (0),
163     compressor (comp),
164     partiallyFull (false),
165     hasException (false),
166     exception (),
167     _sem (1)
168 {
169     // empty
170 }
171 
172 
~LineBuffer()173 LineBuffer::~LineBuffer ()
174 {
175     delete compressor;
176 }
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 
Data(int numThreads)223 OutputFile::Data::Data (int numThreads):
224     lineOffsetsPosition (0),
225     partNumber (-1),
226     _streamData(0),
227     _deleteStream(false)
228 {
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     lineBuffers.resize (max (1, 2 * numThreads));
235 }
236 
237 
~Data()238 OutputFile::Data::~Data ()
239 {
240     for (size_t i = 0; i < lineBuffers.size(); i++)
241         delete lineBuffers[i];
242 }
243 
244 
245 LineBuffer*
getLineBuffer(int number)246 OutputFile::Data::getLineBuffer (int number)
247 {
248     return lineBuffers[number % lineBuffers.size()];
249 }
250 
251 namespace {
252 
253 Int64
writeLineOffsets(OPENEXR_IMF_INTERNAL_NAMESPACE::OStream & os,const vector<Int64> & lineOffsets)254 writeLineOffsets (OPENEXR_IMF_INTERNAL_NAMESPACE::OStream &os, const vector<Int64> &lineOffsets)
255 {
256     Int64 pos = os.tellp();
257 
258     if (pos == -1)
259 	IEX_NAMESPACE::throwErrnoExc ("Cannot determine current file position (%T).");
260 
261     for (unsigned int i = 0; i < lineOffsets.size(); i++)
262 	Xdr::write<StreamIO> (os, lineOffsets[i]);
263 
264     return pos;
265 }
266 
267 
268 void
writePixelData(OutputStreamMutex * filedata,OutputFile::Data * partdata,int lineBufferMinY,const char pixelData[],int pixelDataSize)269 writePixelData (OutputStreamMutex *filedata,
270                 OutputFile::Data *partdata,
271                 int lineBufferMinY,
272                 const char pixelData[],
273                 int pixelDataSize)
274 {
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     Int64 currentPosition = filedata->currentPosition;
282     filedata->currentPosition = 0;
283 
284     if (currentPosition == 0)
285         currentPosition = filedata->os->tellp();
286 
287     partdata->lineOffsets[(partdata->currentScanLine - partdata->minY) / partdata->linesInBuffer] =
288         currentPosition;
289 
290     #ifdef DEBUG
291 
292         assert (filedata->os->tellp() == currentPosition);
293 
294     #endif
295 
296 
297 
298     if (partdata->multiPart)
299     {
300         OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::write <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*filedata->os, partdata->partNumber);
301     }
302 
303     OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::write <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*filedata->os, lineBufferMinY);
304     OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::write <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*filedata->os, pixelDataSize);
305     filedata->os->write (pixelData, pixelDataSize);
306 
307     filedata->currentPosition = currentPosition +
308                            Xdr::size<int>() +
309                            Xdr::size<int>() +
310                            pixelDataSize;
311 
312     if (partdata->multiPart)
313     {
314         filedata->currentPosition += Xdr::size<int>();
315     }
316 }
317 
318 
319 inline void
writePixelData(OutputStreamMutex * filedata,OutputFile::Data * partdata,const LineBuffer * lineBuffer)320 writePixelData (OutputStreamMutex* filedata,
321                 OutputFile::Data *partdata,
322                 const LineBuffer *lineBuffer)
323 {
324     writePixelData (filedata, partdata,
325                     lineBuffer->minY,
326                     lineBuffer->dataPtr,
327                     lineBuffer->dataSize);
328 }
329 
330 
331 void
convertToXdr(OutputFile::Data * ofd,Array<char> & lineBuffer,int lineBufferMinY,int lineBufferMaxY,int inSize)332 convertToXdr (OutputFile::Data *ofd,
333               Array<char> &lineBuffer,
334               int lineBufferMinY,
335               int lineBufferMaxY,
336               int inSize)
337 {
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     char *writePtr = &lineBuffer[0];
357     for (int y = lineBufferMinY; y <= lineBufferMaxY; y++)
358     {
359 	//
360         // Set these to point to the start of line y.
361         // We will write to writePtr from readPtr.
362 	//
363 
364         const char *readPtr = writePtr;
365 
366 	//
367         // Iterate over all slices in the file.
368 	//
369 
370         for (unsigned int i = 0; i < ofd->slices.size(); ++i)
371         {
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             const OutSliceInfo &slice = ofd->slices[i];
379 
380             if (modp (y, slice.ySampling) != 0)
381                 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             int dMinX = divp (ofd->minX, slice.xSampling);
390             int dMaxX = divp (ofd->maxX, slice.xSampling);
391 
392 	    //
393             // Convert the samples in place.
394 	    //
395 
396             convertInPlace (writePtr, readPtr, slice.type, dMaxX - dMinX + 1);
397         }
398     }
399 }
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 
LineBufferTask(TaskGroup * group,OutputFile::Data * ofd,int number,int scanLineMin,int scanLineMax)429 LineBufferTask::LineBufferTask
430     (TaskGroup *group,
431      OutputFile::Data *ofd,
432      int number,
433      int scanLineMin,
434      int scanLineMax)
435 :
436     Task (group),
437     _ofd (ofd),
438     _lineBuffer (_ofd->getLineBuffer(number))
439 {
440     //
441     // Wait for the lineBuffer to become available
442     //
443 
444     _lineBuffer->wait ();
445 
446     //
447     // Initialize the lineBuffer data if necessary
448     //
449 
450     if (!_lineBuffer->partiallyFull)
451     {
452         _lineBuffer->endOfLineBufferData = _lineBuffer->buffer;
453 
454         _lineBuffer->minY = _ofd->minY + number * _ofd->linesInBuffer;
455 
456         _lineBuffer->maxY = min (_lineBuffer->minY + _ofd->linesInBuffer - 1,
457 				 _ofd->maxY);
458 
459         _lineBuffer->partiallyFull = true;
460     }
461 
462     _lineBuffer->scanLineMin = max (_lineBuffer->minY, scanLineMin);
463     _lineBuffer->scanLineMax = min (_lineBuffer->maxY, scanLineMax);
464 }
465 
466 
~LineBufferTask()467 LineBufferTask::~LineBufferTask ()
468 {
469     //
470     // Signal that the line buffer is now free
471     //
472 
473     _lineBuffer->post ();
474 }
475 
476 
477 void
execute()478 LineBufferTask::execute ()
479 {
480     try
481     {
482         //
483         // First copy the pixel data from the
484 	// frame buffer into the line buffer
485         //
486 
487         int yStart, yStop, dy;
488 
489         if (_ofd->lineOrder == INCREASING_Y)
490         {
491             yStart = _lineBuffer->scanLineMin;
492             yStop = _lineBuffer->scanLineMax + 1;
493             dy = 1;
494         }
495         else
496         {
497             yStart = _lineBuffer->scanLineMax;
498             yStop = _lineBuffer->scanLineMin - 1;
499             dy = -1;
500         }
501 
502 	int y;
503 
504         for (y = yStart; y != yStop; y += dy)
505         {
506             //
507             // Gather one scan line's worth of pixel data and store
508             // them in _ofd->lineBuffer.
509             //
510 
511             char *writePtr = _lineBuffer->buffer +
512                              _ofd->offsetInLineBuffer[y - _ofd->minY];
513             //
514             // Iterate over all image channels.
515             //
516 
517             for (unsigned int i = 0; i < _ofd->slices.size(); ++i)
518             {
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                 const OutSliceInfo &slice = _ofd->slices[i];
525 
526                 if (modp (y, slice.ySampling) != 0)
527                     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                 int dMinX = divp (_ofd->minX, slice.xSampling);
536                 int dMaxX = divp (_ofd->maxX, slice.xSampling);
537 
538                 //
539 		// Fill the line buffer with with pixel data.
540                 //
541 
542                 if (slice.zero)
543                 {
544                     //
545                     // The frame buffer contains no data for this channel.
546                     // Store zeroes in _lineBuffer->buffer.
547                     //
548 
549                     fillChannelWithZeroes (writePtr, _ofd->format, slice.type,
550                                            dMaxX - dMinX + 1);
551                 }
552                 else
553                 {
554                     //
555                     // If necessary, convert the pixel data to Xdr format.
556 		    // Then store the pixel data in _ofd->lineBuffer.
557                     //
558 
559                     const char *linePtr = slice.base +
560                                           divp (y, slice.ySampling) *
561                                           slice.yStride;
562 
563                     const char *readPtr = linePtr + dMinX * slice.xStride;
564                     const char *endPtr  = linePtr + dMaxX * slice.xStride;
565 
566                     copyFromFrameBuffer (writePtr, readPtr, endPtr,
567                                          slice.xStride, _ofd->format,
568                                          slice.type);
569                 }
570             }
571 
572             if (_lineBuffer->endOfLineBufferData < writePtr)
573                 _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         }
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         if (y >= _lineBuffer->minY && y <= _lineBuffer->maxY)
591             return;
592 
593         _lineBuffer->dataPtr = _lineBuffer->buffer;
594 
595         _lineBuffer->dataSize = _lineBuffer->endOfLineBufferData -
596                                 _lineBuffer->buffer;
597 
598 	//
599         // Compress the data
600 	//
601 
602         Compressor *compressor = _lineBuffer->compressor;
603 
604         if (compressor)
605         {
606             const char *compPtr;
607 
608             int compSize = compressor->compress (_lineBuffer->dataPtr,
609                                                  _lineBuffer->dataSize,
610                                                  _lineBuffer->minY, compPtr);
611 
612             if (compSize < _lineBuffer->dataSize)
613             {
614                 _lineBuffer->dataSize = compSize;
615                 _lineBuffer->dataPtr = compPtr;
616             }
617             else if (_ofd->format == Compressor::NATIVE)
618             {
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                 convertToXdr (_ofd, _lineBuffer->buffer, _lineBuffer->minY,
627                               _lineBuffer->maxY, _lineBuffer->dataSize);
628             }
629         }
630 
631         _lineBuffer->partiallyFull = false;
632     }
633     catch (std::exception &e)
634     {
635         if (!_lineBuffer->hasException)
636         {
637             _lineBuffer->exception = e.what ();
638             _lineBuffer->hasException = true;
639         }
640     }
641     catch (...)
642     {
643         if (!_lineBuffer->hasException)
644         {
645             _lineBuffer->exception = "unrecognized exception";
646             _lineBuffer->hasException = true;
647         }
648     }
649 }
650 
651 } // namespace
652 
653 
OutputFile(const char fileName[],const Header & header,int numThreads)654 OutputFile::OutputFile
655     (const char fileName[],
656      const Header &header,
657      int numThreads)
658 :
659     _data (new Data (numThreads))
660 
661 {
662     _data->_streamData=new OutputStreamMutex ();
663     _data->_deleteStream=true;
664     try
665     {
666 	header.sanityCheck();
667 	_data->_streamData->os = new StdOFStream (fileName);
668         _data->multiPart=false; // only one header, not multipart
669 	initialize (header);
670 	_data->_streamData->currentPosition = _data->_streamData->os->tellp();
671 
672 	// Write header and empty offset table to the file.
673 	writeMagicNumberAndVersionField(*_data->_streamData->os, _data->header);
674 	_data->previewPosition =
675 	        _data->header.writeTo (*_data->_streamData->os);
676         _data->lineOffsetsPosition =
677                 writeLineOffsets (*_data->_streamData->os,_data->lineOffsets);
678     }
679     catch (IEX_NAMESPACE::BaseExc &e)
680     {
681         if (_data && _data->_streamData) delete _data->_streamData;
682 	if (_data)       delete _data;
683 
684 	REPLACE_EXC (e, "Cannot open image file "
685 			"\"" << fileName << "\". " << e);
686 	throw;
687     }
688     catch (...)
689     {
690         if (_data && _data->_streamData) delete _data->_streamData;
691         if (_data)       delete _data;
692 
693         throw;
694     }
695 }
696 
697 
OutputFile(OPENEXR_IMF_INTERNAL_NAMESPACE::OStream & os,const Header & header,int numThreads)698 OutputFile::OutputFile
699     (OPENEXR_IMF_INTERNAL_NAMESPACE::OStream &os,
700      const Header &header,
701      int numThreads)
702 :
703     _data (new Data (numThreads))
704 {
705 
706     _data->_streamData=new OutputStreamMutex ();
707     _data->_deleteStream=false;
708     try
709     {
710 	header.sanityCheck();
711 	_data->_streamData->os = &os;
712         _data->multiPart=false;
713 	initialize (header);
714 	_data->_streamData->currentPosition = _data->_streamData->os->tellp();
715 
716 	// Write header and empty offset table to the file.
717 	writeMagicNumberAndVersionField(*_data->_streamData->os, _data->header);
718 	_data->previewPosition =
719 	        _data->header.writeTo (*_data->_streamData->os);
720         _data->lineOffsetsPosition =
721                 writeLineOffsets (*_data->_streamData->os, _data->lineOffsets);
722     }
723     catch (IEX_NAMESPACE::BaseExc &e)
724     {
725         if (_data && _data->_streamData) delete _data->_streamData;
726 	if (_data)       delete _data;
727 
728 	REPLACE_EXC (e, "Cannot open image file "
729 			"\"" << os.fileName() << "\". " << e);
730 	throw;
731     }
732     catch (...)
733     {
734         if (_data && _data->_streamData) delete _data->_streamData;
735         if (_data)       delete _data;
736 
737         throw;
738     }
739 }
740 
OutputFile(const OutputPartData * part)741 OutputFile::OutputFile(const OutputPartData* part) : _data(NULL)
742 {
743     try
744     {
745         if (part->header.type() != SCANLINEIMAGE)
746             throw IEX_NAMESPACE::ArgExc("Can't build a OutputFile from a type-mismatched part.");
747 
748         _data = new Data (part->numThreads);
749         _data->_streamData = part->mutex;
750         _data->_deleteStream=false;
751         _data->multiPart=part->multipart;
752 
753         initialize (part->header);
754         _data->partNumber = part->partNumber;
755         _data->lineOffsetsPosition = part->chunkOffsetTablePosition;
756         _data->previewPosition = part->previewPosition;
757     }
758     catch (IEX_NAMESPACE::BaseExc &e)
759     {
760         if (_data) delete _data;
761 
762         REPLACE_EXC (e, "Cannot initialize output part "
763                         "\"" << part->partNumber << "\". " << e);
764         throw;
765     }
766     catch (...)
767     {
768         if (_data) delete _data;
769 
770         throw;
771     }
772 }
773 
774 void
initialize(const Header & header)775 OutputFile::initialize (const Header &header)
776 {
777     _data->header = header;
778 
779     // "fix" the type if it happens to be set incorrectly
780     // (attribute is optional, but ensure it is correct if it exists)
781     if(_data->header.hasType())
782     {
783         _data->header.setType(SCANLINEIMAGE);
784     }
785 
786     const Box2i &dataWindow = header.dataWindow();
787 
788     _data->currentScanLine = (header.lineOrder() == INCREASING_Y)?
789 				 dataWindow.min.y: dataWindow.max.y;
790 
791     _data->missingScanLines = dataWindow.max.y - dataWindow.min.y + 1;
792     _data->lineOrder = header.lineOrder();
793     _data->minX = dataWindow.min.x;
794     _data->maxX = dataWindow.max.x;
795     _data->minY = dataWindow.min.y;
796     _data->maxY = dataWindow.max.y;
797 
798     size_t maxBytesPerLine = bytesPerLineTable (_data->header,
799 						_data->bytesPerLine);
800 
801     for (size_t i = 0; i < _data->lineBuffers.size(); ++i)
802     {
803         _data->lineBuffers[i] =
804 	    new LineBuffer (newCompressor (_data->header.compression(),
805 					   maxBytesPerLine,
806 					   _data->header));
807     }
808 
809     LineBuffer *lineBuffer = _data->lineBuffers[0];
810     _data->format = defaultFormat (lineBuffer->compressor);
811     _data->linesInBuffer = numLinesInBuffer (lineBuffer->compressor);
812     _data->lineBufferSize = maxBytesPerLine * _data->linesInBuffer;
813 
814     for (size_t i = 0; i < _data->lineBuffers.size(); i++)
815         _data->lineBuffers[i]->buffer.resizeErase(_data->lineBufferSize);
816 
817     int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +
818 			  _data->linesInBuffer) / _data->linesInBuffer;
819 
820     _data->lineOffsets.resize (lineOffsetSize);
821 
822 
823     offsetInLineBufferTable (_data->bytesPerLine,
824 			     _data->linesInBuffer,
825 			     _data->offsetInLineBuffer);
826 }
827 
828 
~OutputFile()829 OutputFile::~OutputFile ()
830 {
831     if (_data)
832     {
833         {
834             Lock lock(*_data->_streamData);
835             Int64 originalPosition = _data->_streamData->os->tellp();
836 
837             if (_data->lineOffsetsPosition > 0)
838             {
839                 try
840                 {
841                     _data->_streamData->os->seekp (_data->lineOffsetsPosition);
842                     writeLineOffsets (*_data->_streamData->os, _data->lineOffsets);
843 
844                     //
845                     // Restore the original position.
846                     //
847                     _data->_streamData->os->seekp (originalPosition);
848                 }
849                 catch (...)
850                 {
851                     //
852                     // We cannot safely throw any exceptions from here.
853                     // This destructor may have been called because the
854                     // stack is currently being unwound for another
855                     // exception.
856                     //
857                 }
858             }
859         }
860 
861         if (_data->_deleteStream && _data->_streamData)
862             delete _data->_streamData->os;
863 
864         if (_data->partNumber == -1 && _data->_streamData)
865             delete _data->_streamData;
866 
867 	delete _data;
868     }
869 
870 }
871 
872 
873 const char *
fileName() const874 OutputFile::fileName () const
875 {
876     return _data->_streamData->os->fileName();
877 }
878 
879 
880 const Header &
header() const881 OutputFile::header () const
882 {
883     return _data->header;
884 }
885 
886 
887 void
setFrameBuffer(const FrameBuffer & frameBuffer)888 OutputFile::setFrameBuffer (const FrameBuffer &frameBuffer)
889 {
890     Lock lock (*_data->_streamData);
891 
892     //
893     // Check if the new frame buffer descriptor
894     // is compatible with the image file header.
895     //
896 
897     const ChannelList &channels = _data->header.channels();
898 
899     for (ChannelList::ConstIterator i = channels.begin();
900 	 i != channels.end();
901 	 ++i)
902     {
903 	FrameBuffer::ConstIterator j = frameBuffer.find (i.name());
904 
905 	if (j == frameBuffer.end())
906 	    continue;
907 
908 	if (i.channel().type != j.slice().type)
909 	{
910 	    THROW (IEX_NAMESPACE::ArgExc, "Pixel type of \"" << i.name() << "\" channel "
911 			        "of output file \"" << fileName() << "\" is "
912 			        "not compatible with the frame buffer's "
913 			        "pixel type.");
914 	}
915 
916 	if (i.channel().xSampling != j.slice().xSampling ||
917 	    i.channel().ySampling != j.slice().ySampling)
918 	{
919 	    THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors "
920 				"of \"" << i.name() << "\" channel "
921 				"of output file \"" << fileName() << "\" are "
922 				"not compatible with the frame buffer's "
923 				"subsampling factors.");
924 	}
925     }
926 
927     //
928     // Initialize slice table for writePixels().
929     //
930 
931     vector<OutSliceInfo> slices;
932 
933     for (ChannelList::ConstIterator i = channels.begin();
934 	 i != channels.end();
935 	 ++i)
936     {
937 	FrameBuffer::ConstIterator j = frameBuffer.find (i.name());
938 
939 	if (j == frameBuffer.end())
940 	{
941 	    //
942 	    // Channel i is not present in the frame buffer.
943 	    // In the file, channel i will contain only zeroes.
944 	    //
945 
946 	    slices.push_back (OutSliceInfo (i.channel().type,
947 					    0, // base
948 					    0, // xStride,
949 					    0, // yStride,
950 					    i.channel().xSampling,
951 					    i.channel().ySampling,
952 					    true)); // zero
953 	}
954 	else
955 	{
956 	    //
957 	    // Channel i is present in the frame buffer.
958 	    //
959 
960 	    slices.push_back (OutSliceInfo (j.slice().type,
961 					    j.slice().base,
962 					    j.slice().xStride,
963 					    j.slice().yStride,
964 					    j.slice().xSampling,
965 					    j.slice().ySampling,
966 					    false)); // zero
967 	}
968     }
969 
970     //
971     // Store the new frame buffer.
972     //
973 
974     _data->frameBuffer = frameBuffer;
975     _data->slices = slices;
976 }
977 
978 
979 const FrameBuffer &
frameBuffer() const980 OutputFile::frameBuffer () const
981 {
982     Lock lock (*_data->_streamData);
983     return _data->frameBuffer;
984 }
985 
986 
987 void
writePixels(int numScanLines)988 OutputFile::writePixels (int numScanLines)
989 {
990     try
991     {
992         Lock lock (*_data->_streamData);
993 
994 	if (_data->slices.size() == 0)
995 	    throw IEX_NAMESPACE::ArgExc ("No frame buffer specified "
996 			       "as pixel data source.");
997 
998         //
999         // Maintain two iterators:
1000         //     nextWriteBuffer: next linebuffer to be written to the file
1001         //     nextCompressBuffer: next linebuffer to compress
1002         //
1003 
1004         int first = (_data->currentScanLine - _data->minY) /
1005                          _data->linesInBuffer;
1006 
1007         int nextWriteBuffer = first;
1008         int nextCompressBuffer;
1009         int stop;
1010         int step;
1011         int scanLineMin;
1012         int scanLineMax;
1013 
1014         {
1015             //
1016             // Create a task group for all line buffer tasks. When the
1017             // taskgroup goes out of scope, the destructor waits until
1018 	    // all tasks are complete.
1019             //
1020 
1021             TaskGroup taskGroup;
1022 
1023             //
1024             // Determine the range of lineBuffers that intersect the scan
1025 	    // line range.  Then add the initial compression tasks to the
1026 	    // thread pool.  We always add in at least one task but the
1027 	    // individual task might not do anything if numScanLines == 0.
1028             //
1029 
1030             if (_data->lineOrder == INCREASING_Y)
1031             {
1032                 int last = (_data->currentScanLine + (numScanLines - 1) -
1033                             _data->minY) / _data->linesInBuffer;
1034 
1035                 scanLineMin = _data->currentScanLine;
1036                 scanLineMax = _data->currentScanLine + numScanLines - 1;
1037 
1038                 int numTasks = max (min ((int)_data->lineBuffers.size(),
1039                                          last - first + 1),
1040 				    1);
1041 
1042                 for (int i = 0; i < numTasks; i++)
1043 		{
1044                     ThreadPool::addGlobalTask
1045                         (new LineBufferTask (&taskGroup, _data, first + i,
1046                                              scanLineMin, scanLineMax));
1047 		}
1048 
1049                 nextCompressBuffer = first + numTasks;
1050                 stop = last + 1;
1051                 step = 1;
1052             }
1053             else
1054             {
1055                 int last = (_data->currentScanLine - (numScanLines - 1) -
1056                             _data->minY) / _data->linesInBuffer;
1057 
1058                 scanLineMax = _data->currentScanLine;
1059                 scanLineMin = _data->currentScanLine - numScanLines + 1;
1060 
1061                 int numTasks = max (min ((int)_data->lineBuffers.size(),
1062                                          first - last + 1),
1063 				    1);
1064 
1065                 for (int i = 0; i < numTasks; i++)
1066 		{
1067                     ThreadPool::addGlobalTask
1068                         (new LineBufferTask (&taskGroup, _data, first - i,
1069                                              scanLineMin, scanLineMax));
1070 		}
1071 
1072                 nextCompressBuffer = first - numTasks;
1073                 stop = last - 1;
1074                 step = -1;
1075             }
1076 
1077             while (true)
1078             {
1079                 if (_data->missingScanLines <= 0)
1080                 {
1081                     throw IEX_NAMESPACE::ArgExc ("Tried to write more scan lines "
1082                                        "than specified by the data window.");
1083                 }
1084 
1085 		//
1086                 // Wait until the next line buffer is ready to be written
1087 		//
1088 
1089                 LineBuffer *writeBuffer =
1090 		    _data->getLineBuffer (nextWriteBuffer);
1091 
1092                 writeBuffer->wait();
1093 
1094                 int numLines = writeBuffer->scanLineMax -
1095                                writeBuffer->scanLineMin + 1;
1096 
1097                 _data->missingScanLines -= numLines;
1098 
1099 		//
1100                 // If the line buffer is only partially full, then it is
1101 		// not complete and we cannot write it to disk yet.
1102 		//
1103 
1104                 if (writeBuffer->partiallyFull)
1105                 {
1106                     _data->currentScanLine = _data->currentScanLine +
1107                                              step * numLines;
1108                     writeBuffer->post();
1109 
1110                     return;
1111                 }
1112 
1113 		//
1114                 // Write the line buffer
1115 		//
1116 
1117                 writePixelData (_data->_streamData, _data, writeBuffer);
1118                 nextWriteBuffer += step;
1119 
1120                 _data->currentScanLine = _data->currentScanLine +
1121                                          step * numLines;
1122 
1123                 #ifdef DEBUG
1124 
1125                     assert (_data->currentScanLine ==
1126                             ((_data->lineOrder == INCREASING_Y) ?
1127                              writeBuffer->scanLineMax + 1:
1128                              writeBuffer->scanLineMin - 1));
1129 
1130                 #endif
1131 
1132 		//
1133                 // Release the lock on the line buffer
1134 		//
1135 
1136                 writeBuffer->post();
1137 
1138 		//
1139                 // If this was the last line buffer in the scanline range
1140 		//
1141 
1142                 if (nextWriteBuffer == stop)
1143                     break;
1144 
1145 		//
1146                 // If there are no more line buffers to compress,
1147                 // then only continue to write out remaining lineBuffers
1148 		//
1149 
1150                 if (nextCompressBuffer == stop)
1151                     continue;
1152 
1153 		//
1154                 // Add nextCompressBuffer as a compression task
1155 		//
1156 
1157                 ThreadPool::addGlobalTask
1158                     (new LineBufferTask (&taskGroup, _data, nextCompressBuffer,
1159                                          scanLineMin, scanLineMax));
1160 
1161 		//
1162                 // Update the next line buffer we need to compress
1163 		//
1164 
1165                 nextCompressBuffer += step;
1166             }
1167 
1168 	    //
1169             // Finish all tasks
1170 	    //
1171         }
1172 
1173 	//
1174 	// Exeption handling:
1175 	//
1176 	// LineBufferTask::execute() may have encountered exceptions, but
1177 	// those exceptions occurred in another thread, not in the thread
1178 	// that is executing this call to OutputFile::writePixels().
1179 	// LineBufferTask::execute() has caught all exceptions and stored
1180 	// the exceptions' what() strings in the line buffers.
1181 	// Now we check if any line buffer contains a stored exception; if
1182 	// this is the case then we re-throw the exception in this thread.
1183 	// (It is possible that multiple line buffers contain stored
1184 	// exceptions.  We re-throw the first exception we find and
1185 	// ignore all others.)
1186 	//
1187 
1188 	const string *exception = 0;
1189 
1190         for (size_t i = 0; i < _data->lineBuffers.size(); ++i)
1191 	{
1192             LineBuffer *lineBuffer = _data->lineBuffers[i];
1193 
1194 	    if (lineBuffer->hasException && !exception)
1195 		exception = &lineBuffer->exception;
1196 
1197 	    lineBuffer->hasException = false;
1198 	}
1199 
1200 	if (exception)
1201 	    throw IEX_NAMESPACE::IoExc (*exception);
1202     }
1203     catch (IEX_NAMESPACE::BaseExc &e)
1204     {
1205 	REPLACE_EXC (e, "Failed to write pixel data to image "
1206 		        "file \"" << fileName() << "\". " << e);
1207 	throw;
1208     }
1209 }
1210 
1211 
1212 int
currentScanLine() const1213 OutputFile::currentScanLine () const
1214 {
1215     Lock lock (*_data->_streamData);
1216     return _data->currentScanLine;
1217 }
1218 
1219 
1220 void
copyPixels(InputFile & in)1221 OutputFile::copyPixels (InputFile &in)
1222 {
1223     Lock lock (*_data->_streamData);
1224 
1225     //
1226     // Check if this file's and and the InputFile's
1227     // headers are compatible.
1228     //
1229 
1230     const Header &hdr = _data->header;
1231     const Header &inHdr = in.header();
1232 
1233     if (inHdr.find("tiles") != inHdr.end())
1234 	THROW (IEX_NAMESPACE::ArgExc, "Cannot copy pixels from image "
1235 			    "file \"" << in.fileName() << "\" to image "
1236 			    "file \"" << fileName() << "\". "
1237                             "The input file is tiled, but the output file is "
1238                             "not. Try using TiledOutputFile::copyPixels "
1239                             "instead.");
1240 
1241     if (!(hdr.dataWindow() == inHdr.dataWindow()))
1242 	THROW (IEX_NAMESPACE::ArgExc, "Cannot copy pixels from image "
1243 			    "file \"" << in.fileName() << "\" to image "
1244 			    "file \"" << fileName() << "\". "
1245                             "The files have different data windows.");
1246 
1247     if (!(hdr.lineOrder() == inHdr.lineOrder()))
1248 	THROW (IEX_NAMESPACE::ArgExc, "Quick pixel copy from image "
1249 			    "file \"" << in.fileName() << "\" to image "
1250 			    "file \"" << fileName() << "\" failed. "
1251 			    "The files have different line orders.");
1252 
1253     if (!(hdr.compression() == inHdr.compression()))
1254 	THROW (IEX_NAMESPACE::ArgExc, "Quick pixel copy from image "
1255 			    "file \"" << in.fileName() << "\" to image "
1256 			    "file \"" << fileName() << "\" failed. "
1257 			    "The files use different compression methods.");
1258 
1259     if (!(hdr.channels() == inHdr.channels()))
1260 	THROW (IEX_NAMESPACE::ArgExc, "Quick pixel copy from image "
1261 			    "file \"" << in.fileName() << "\" to image "
1262 			    "file \"" << fileName() << "\" failed.  "
1263 			    "The files have different channel lists.");
1264 
1265     //
1266     // Verify that no pixel data have been written to this file yet.
1267     //
1268 
1269     const Box2i &dataWindow = hdr.dataWindow();
1270 
1271     if (_data->missingScanLines != dataWindow.max.y - dataWindow.min.y + 1)
1272 	THROW (IEX_NAMESPACE::LogicExc, "Quick pixel copy from image "
1273 			      "file \"" << in.fileName() << "\" to image "
1274 			      "file \"" << fileName() << "\" failed. "
1275 			      "\"" << fileName() << "\" already contains "
1276 			      "pixel data.");
1277 
1278     //
1279     // Copy the pixel data.
1280     //
1281 
1282     while (_data->missingScanLines > 0)
1283     {
1284 	const char *pixelData;
1285 	int pixelDataSize;
1286 
1287 	in.rawPixelData (_data->currentScanLine, pixelData, pixelDataSize);
1288 
1289         writePixelData (_data->_streamData, _data, lineBufferMinY (_data->currentScanLine,
1290                                                _data->minY,
1291                                                _data->linesInBuffer),
1292                         pixelData, pixelDataSize);
1293 
1294 	_data->currentScanLine += (_data->lineOrder == INCREASING_Y)?
1295 				   _data->linesInBuffer: -_data->linesInBuffer;
1296 
1297 	_data->missingScanLines -= _data->linesInBuffer;
1298     }
1299 }
1300 
1301 
1302 void
copyPixels(InputPart & in)1303 OutputFile::copyPixels( InputPart & in)
1304 {
1305     copyPixels(*in.file);
1306 }
1307 
1308 
1309 
1310 void
updatePreviewImage(const PreviewRgba newPixels[])1311 OutputFile::updatePreviewImage (const PreviewRgba newPixels[])
1312 {
1313     Lock lock (*_data->_streamData);
1314 
1315     if (_data->previewPosition <= 0)
1316 	THROW (IEX_NAMESPACE::LogicExc, "Cannot update preview image pixels. "
1317 			      "File \"" << fileName() << "\" does not "
1318 			      "contain a preview image.");
1319 
1320     //
1321     // Store the new pixels in the header's preview image attribute.
1322     //
1323 
1324     PreviewImageAttribute &pia =
1325 	_data->header.typedAttribute <PreviewImageAttribute> ("preview");
1326 
1327     PreviewImage &pi = pia.value();
1328     PreviewRgba *pixels = pi.pixels();
1329     int numPixels = pi.width() * pi.height();
1330 
1331     for (int i = 0; i < numPixels; ++i)
1332 	pixels[i] = newPixels[i];
1333 
1334     //
1335     // Save the current file position, jump to the position in
1336     // the file where the preview image starts, store the new
1337     // preview image, and jump back to the saved file position.
1338     //
1339 
1340     Int64 savedPosition = _data->_streamData->os->tellp();
1341 
1342     try
1343     {
1344         _data->_streamData->os->seekp (_data->previewPosition);
1345 	pia.writeValueTo (*_data->_streamData->os, _data->version);
1346 	_data->_streamData->os->seekp (savedPosition);
1347     }
1348     catch (IEX_NAMESPACE::BaseExc &e)
1349     {
1350 	REPLACE_EXC (e, "Cannot update preview image pixels for "
1351 			"file \"" << fileName() << "\". " << e);
1352 	throw;
1353     }
1354 }
1355 
1356 
1357 void
breakScanLine(int y,int offset,int length,char c)1358 OutputFile::breakScanLine  (int y, int offset, int length, char c)
1359 {
1360     Lock lock (*_data->_streamData);
1361 
1362     Int64 position =
1363 	_data->lineOffsets[(y - _data->minY) / _data->linesInBuffer];
1364 
1365     if (!position)
1366 	THROW (IEX_NAMESPACE::ArgExc, "Cannot overwrite scan line " << y << ". "
1367 			    "The scan line has not yet been stored in "
1368 			    "file \"" << fileName() << "\".");
1369 
1370     _data->_streamData->currentPosition = 0;
1371     _data->_streamData->os->seekp (position + offset);
1372 
1373     for (int i = 0; i < length; ++i)
1374         _data->_streamData->os->write (&c, 1);
1375 }
1376 
1377 
1378 OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
1379