ImfDeepScanLineOutputFile.cpp 49 KB

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