replace ImBuf.depth with ImBuf.planes to match ImageFormatData.planes & to avoid...
[blender.git] / source / blender / imbuf / intern / openexr / openexr_api.cpp
1 /** \file blender/imbuf/intern/openexr/openexr_api.cpp
2  *  \ingroup openexr
3  */
4 /*
5 *
6  * ***** BEGIN GPLLICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version. 
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * Copyright by Gernot Ziegler <gz@lysator.liu.se>.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): Austin Benesh, Ton Roosendaal (float, half, speedup, cleanup...).
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <stddef.h>
35 #include <string>
36
37
38 #include <openexr_api.h>
39
40 extern "C"
41 {
42
43 // The following prevents a linking error in debug mode for MSVC using the libs in CVS
44 #if defined(WITH_OPENEXR) && defined(_WIN32) && defined(_DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
45 _CRTIMP void __cdecl _invalid_parameter_noinfo(void)
46 {
47 }
48 #endif
49
50 #include "MEM_guardedalloc.h"
51
52 #include "BLI_blenlib.h"
53 #include "BLI_math_color.h"
54
55 #include "IMB_imbuf_types.h"
56 #include "IMB_imbuf.h"
57 #include "IMB_allocimbuf.h"
58 #include "IMB_metadata.h"
59
60 #include "openexr_multi.h"
61 }
62
63 #include <iostream>
64
65 #if defined (_WIN32) && !defined(FREE_WINDOWS)
66 #include <half.h>
67 #include <IlmImf/ImfVersion.h>
68 #include <IlmImf/ImfArray.h>
69 #include <IlmImf/ImfIO.h>
70 #include <IlmImf/ImfChannelList.h>
71 #include <IlmImf/ImfPixelType.h>
72 #include <IlmImf/ImfInputFile.h>
73 #include <IlmImf/ImfOutputFile.h>
74 #include <IlmImf/ImfCompression.h>
75 #include <IlmImf/ImfCompressionAttribute.h>
76 #include <IlmImf/ImfStringAttribute.h>
77 #include <Imath/ImathBox.h>
78 #else
79 #include <half.h>
80 #include <ImfVersion.h>
81 #include <ImathBox.h>
82 #include <ImfArray.h>
83 #include <ImfIO.h>
84 #include <ImfChannelList.h>
85 #include <ImfPixelType.h>
86 #include <ImfInputFile.h>
87 #include <ImfOutputFile.h>
88 #include <ImfCompression.h>
89 #include <ImfCompressionAttribute.h>
90 #include <ImfStringAttribute.h>
91 #endif
92
93 using namespace Imf;
94 using namespace Imath;
95
96 class Mem_IStream: public IStream
97 {
98 public:
99         
100         Mem_IStream (unsigned char *exrbuf, size_t exrsize):
101             IStream("dummy"), _exrpos (0), _exrsize(exrsize)  { _exrbuf = exrbuf; }
102         
103         virtual bool    read (char c[], int n);
104         virtual Int64   tellg ();
105         virtual void    seekg (Int64 pos);
106         virtual void    clear ();
107         //virtual ~Mem_IStream() {}; // unused
108         
109 private:
110
111         Int64 _exrpos;
112         Int64 _exrsize;
113         unsigned char *_exrbuf;
114 };
115
116 bool Mem_IStream::read (char c[], int n)
117 {
118         if (n + _exrpos <= _exrsize)
119         {
120                 memcpy(c, (void *)(&_exrbuf[_exrpos]), n);
121                 _exrpos += n;
122                 return true;
123         }
124         else
125                 return false;
126 }
127
128 Int64 Mem_IStream::tellg ()
129 {
130         return _exrpos;
131 }
132
133 void Mem_IStream::seekg (Int64 pos)
134 {
135         _exrpos = pos;
136 }
137
138 void Mem_IStream::clear () 
139
140 }
141
142 struct _RGBAZ
143 {
144         half r;
145         half g;
146         half b;
147         half a;
148         half z;
149 };
150
151 typedef struct _RGBAZ RGBAZ;
152
153 extern "C"
154 {
155         
156 int imb_is_a_openexr(unsigned char *mem)
157 {
158         return Imf::isImfMagic ((const char *)mem);
159 }
160
161 static void openexr_header_compression(Header *header, int compression)
162 {
163         switch(compression)
164         {
165                 case 0:
166                         header->compression() = NO_COMPRESSION;
167                         break;
168                 case 1:
169                         header->compression() = PXR24_COMPRESSION;
170                         break;
171                 case 2:
172                         header->compression() = ZIP_COMPRESSION;
173                         break;
174                 case 3:
175                         header->compression() = PIZ_COMPRESSION;
176                         break;
177                 case 4:
178                         header->compression() = RLE_COMPRESSION;
179                         break;
180                 default:
181                         header->compression() = ZIP_COMPRESSION;
182                         break; 
183         }
184 }
185
186 static void openexr_header_metadata(Header *header, struct ImBuf *ibuf)
187 {
188         ImMetaData* info;
189
190         for(info= ibuf->metadata; info; info= info->next)
191                 header->insert(info->key, StringAttribute(info->value));
192 }
193
194 static int imb_save_openexr_half(struct ImBuf *ibuf, const char *name, int flags)
195 {
196         int channels = ibuf->channels;
197         int width = ibuf->x;
198         int height = ibuf->y;
199         int write_zbuf = (flags & IB_zbuffloat) && ibuf->zbuf_float != NULL;   // summarize
200         
201         try
202         {
203                 Header header (width, height);
204                 
205                 openexr_header_compression(&header, ibuf->ftype & OPENEXR_COMPRESS);
206                 openexr_header_metadata(&header, ibuf);
207                 
208                 header.channels().insert ("R", Channel (HALF));
209                 header.channels().insert ("G", Channel (HALF));
210                 header.channels().insert ("B", Channel (HALF));
211                 if (ibuf->planes==32 && channels >= 4)
212                         header.channels().insert ("A", Channel (HALF));
213                 if (write_zbuf)         // z we do as float always
214                         header.channels().insert ("Z", Channel (FLOAT));
215                 
216                 FrameBuffer frameBuffer;                        
217                 OutputFile *file = new OutputFile(name, header);                        
218                 
219                 /* we store first everything in half array */
220                 RGBAZ *pixels = new RGBAZ[height * width];
221                 RGBAZ *to = pixels;
222                 int xstride= sizeof (RGBAZ);
223                 int ystride= xstride*width;
224
225                 /* indicate used buffers */
226                 frameBuffer.insert ("R", Slice (HALF,  (char *) &pixels[0].r, xstride, ystride));       
227                 frameBuffer.insert ("G", Slice (HALF,  (char *) &pixels[0].g, xstride, ystride));
228                 frameBuffer.insert ("B", Slice (HALF,  (char *) &pixels[0].b, xstride, ystride));
229                 if (ibuf->planes==32 && channels >= 4)
230                         frameBuffer.insert ("A", Slice (HALF, (char *) &pixels[0].a, xstride, ystride));
231                 if (write_zbuf)
232                         frameBuffer.insert ("Z", Slice (FLOAT, (char *)(ibuf->zbuf_float + (height-1)*width),
233                                                                                         sizeof(float), sizeof(float) * -width));
234                 if(ibuf->rect_float) {
235                         float *from;
236
237                         if(ibuf->profile == IB_PROFILE_LINEAR_RGB) {
238                                 for (int i = ibuf->y-1; i >= 0; i--)
239                                 {
240                                         from= ibuf->rect_float + channels*i*width;
241
242                                         for (int j = ibuf->x; j > 0; j--)
243                                         {
244                                                 to->r = from[0];
245                                                 to->g = from[1];
246                                                 to->b = from[2];
247                                                 to->a = (channels >= 4)? from[3]: 1.0f;
248                                                 to++; from += 4;
249                                         }
250                                 }
251                         }
252                         else {
253                                 for (int i = ibuf->y-1; i >= 0; i--)
254                                 {
255                                         from= ibuf->rect_float + channels*i*width;
256
257                                         for (int j = ibuf->x; j > 0; j--)
258                                         {
259                                                 to->r = srgb_to_linearrgb(from[0]);
260                                                 to->g = srgb_to_linearrgb(from[1]);
261                                                 to->b = srgb_to_linearrgb(from[2]);
262                                                 to->a = (channels >= 4)? from[3]: 1.0f;
263                                                 to++; from += 4;
264                                         }
265                                 }
266                         }
267                 }
268                 else {
269                         unsigned char *from;
270
271                         if(ibuf->profile == IB_PROFILE_LINEAR_RGB) {
272                                 for (int i = ibuf->y-1; i >= 0; i--)
273                                 {
274                                         from= (unsigned char *)ibuf->rect + channels*i*width;
275
276                                         for (int j = ibuf->x; j > 0; j--)
277                                         {
278                                                 to->r = (float)(from[0])/255.0;
279                                                 to->g = (float)(from[1])/255.0;
280                                                 to->b = (float)(from[2])/255.0;
281                                                 to->a = (float)(channels >= 4) ? from[3]/255.0 : 1.0f;
282                                                 to++; from += 4;
283                                         }
284                                 }
285                         }
286                         else {
287                                 for (int i = ibuf->y-1; i >= 0; i--)
288                                 {
289                                         from= (unsigned char *)ibuf->rect + channels*i*width;
290
291                                         for (int j = ibuf->x; j > 0; j--)
292                                         {
293                                                 to->r = srgb_to_linearrgb((float)from[0] / 255.0);
294                                                 to->g = srgb_to_linearrgb((float)from[1] / 255.0);
295                                                 to->b = srgb_to_linearrgb((float)from[2] / 255.0);
296                                                 to->a = channels >= 4 ? (float)from[3]/255.0 : 1.0f;
297                                                 to++; from += 4;
298                                         }
299                                 }
300                         }
301                 }
302                 
303 //              printf("OpenEXR-save: Writing OpenEXR file of height %d.\n", height);
304                 
305                 file->setFrameBuffer (frameBuffer);                               
306                 file->writePixels (height);                                       
307                 delete file;
308                 delete [] pixels;
309         }
310         catch (const std::exception &exc)
311         {
312                 printf("OpenEXR-save: ERROR: %s\n", exc.what());
313                 if (ibuf) IMB_freeImBuf(ibuf);
314                 
315                 return (0);
316         }
317         
318         return (1);
319 }
320
321 static int imb_save_openexr_float(struct ImBuf *ibuf, const char *name, int flags)
322 {
323         int channels = ibuf->channels;
324         int width = ibuf->x;
325         int height = ibuf->y;
326         int write_zbuf = (flags & IB_zbuffloat) && ibuf->zbuf_float != NULL;   // summarize
327
328         try
329         {
330                 Header header (width, height);
331                 
332                 openexr_header_compression(&header, ibuf->ftype & OPENEXR_COMPRESS);
333                 openexr_header_metadata(&header, ibuf);
334                 
335                 header.channels().insert ("R", Channel (FLOAT));
336                 header.channels().insert ("G", Channel (FLOAT));
337                 header.channels().insert ("B", Channel (FLOAT));
338                 if (ibuf->planes==32 && channels >= 4)
339                         header.channels().insert ("A", Channel (FLOAT));
340                 if (write_zbuf)
341                         header.channels().insert ("Z", Channel (FLOAT));
342                 
343                 FrameBuffer frameBuffer;                        
344                 OutputFile *file = new OutputFile(name, header);                        
345                 int xstride = sizeof(float) * channels;
346                 int ystride = - xstride*width;
347                 float *rect[4] = {NULL, NULL, NULL, NULL};
348
349                 /* last scanline, stride negative */
350                 rect[0]= ibuf->rect_float + channels*(height-1)*width;
351                 rect[1]= rect[0]+1;
352                 rect[2]= rect[0]+2;
353                 rect[3]= (channels >= 4)? rect[0]+3:rect[0]; /* red as alpha, is this needed since alpha isnt written? */
354
355                 frameBuffer.insert ("R", Slice (FLOAT,  (char *)rect[0], xstride, ystride));
356                 frameBuffer.insert ("G", Slice (FLOAT,  (char *)rect[1], xstride, ystride));
357                 frameBuffer.insert ("B", Slice (FLOAT,  (char *)rect[2], xstride, ystride));
358                 if (ibuf->planes==32 && channels >= 4)
359                         frameBuffer.insert ("A", Slice (FLOAT,  (char *)rect[3], xstride, ystride));
360                 if (write_zbuf)
361                         frameBuffer.insert ("Z", Slice (FLOAT, (char *) (ibuf->zbuf_float + (height-1)*width),
362                                                                                         sizeof(float), sizeof(float) * -width));
363                 file->setFrameBuffer (frameBuffer);                               
364                 file->writePixels (height);                                       
365                 delete file;
366         }
367         catch (const std::exception &exc)
368         {
369                 printf("OpenEXR-save: ERROR: %s\n", exc.what());
370                 if (ibuf) IMB_freeImBuf(ibuf);
371                 
372                 return (0);
373         }
374         
375         return (1);
376         //      printf("OpenEXR-save: Done.\n");
377 }
378
379
380 int imb_save_openexr(struct ImBuf *ibuf, const char *name, int flags)
381 {
382         if (flags & IB_mem) 
383         {
384                 printf("OpenEXR-save: Create EXR in memory CURRENTLY NOT SUPPORTED !\n");
385                 imb_addencodedbufferImBuf(ibuf);
386                 ibuf->encodedsize = 0;    
387                 return(0);
388         } 
389         
390         if (ibuf->ftype & OPENEXR_HALF) 
391                 return imb_save_openexr_half(ibuf, name, flags);
392         else {
393                 /* when no float rect, we save as half (16 bits is sufficient) */
394                 if (ibuf->rect_float==NULL)
395                         return imb_save_openexr_half(ibuf, name, flags);
396                 else
397                         return imb_save_openexr_float(ibuf, name, flags);
398         }
399 }
400
401 /* ********************* Nicer API, MultiLayer and with Tile file support ************************************ */
402
403 /* naming rules:
404    - parse name from right to left
405    - last character is channel ID, 1 char like 'A' 'R' 'G' 'B' 'X' 'Y' 'Z' 'W' 'U' 'V'
406    - separated with a dot; the Pass name (like "Depth", "Color", "Diffuse" or "Combined")
407    - separated with a dot: the Layer name (like "Lamp1" or "Walls" or "Characters")
408 */
409
410 static ListBase exrhandles= {NULL, NULL};
411
412 typedef struct ExrHandle {
413         struct ExrHandle *next, *prev;
414         
415         InputFile *ifile;
416         TiledOutputFile *tofile;
417         OutputFile *ofile;
418         int tilex, tiley;
419         int width, height;
420         int mipmap;
421         
422         ListBase channels;      /* flattened out, ExrChannel */
423         ListBase layers;        /* hierarchical, pointing in end to ExrChannel */
424 } ExrHandle;
425
426 /* flattened out channel */
427 typedef struct ExrChannel {
428         struct ExrChannel *next, *prev;
429         
430         char name[EXR_TOT_MAXNAME+1];   /* full name of layer+pass */
431         int xstride, ystride;           /* step to next pixel, to next scanline */
432         float *rect;                            /* first pointer to write in */
433         char chan_id;                           /* quick lookup of channel char */
434 } ExrChannel;
435
436
437 /* hierarchical; layers -> passes -> channels[] */
438 typedef struct ExrPass {
439         struct ExrPass *next, *prev;
440         char name[EXR_PASS_MAXNAME];
441         int totchan;
442         float *rect;
443         struct ExrChannel *chan[EXR_PASS_MAXCHAN];
444         char chan_id[EXR_PASS_MAXCHAN];
445 } ExrPass;
446
447 typedef struct ExrLayer {
448         struct ExrLayer *next, *prev;
449         char name[EXR_LAY_MAXNAME+1];
450         ListBase passes;
451 } ExrLayer;
452
453 /* ********************** */
454
455 void *IMB_exr_get_handle(void)
456 {
457         ExrHandle *data= (ExrHandle *)MEM_callocN(sizeof(ExrHandle), "exr handle");
458         BLI_addtail(&exrhandles, data);
459         return data;
460 }
461
462 /* adds flattened ExrChannels */
463 /* xstride, ystride and rect can be done in set_channel too, for tile writing */
464 void IMB_exr_add_channel(void *handle, const char *layname, const char *passname, int xstride, int ystride, float *rect)
465 {
466         ExrHandle *data= (ExrHandle *)handle;
467         ExrChannel *echan;
468         
469         echan= (ExrChannel *)MEM_callocN(sizeof(ExrChannel), "exr tile channel");
470         
471         if(layname) {
472                 char lay[EXR_LAY_MAXNAME+1], pass[EXR_PASS_MAXNAME+1];
473                 BLI_strncpy(lay, layname, EXR_LAY_MAXNAME);
474                 BLI_strncpy(pass, passname, EXR_PASS_MAXNAME);
475
476                 sprintf(echan->name, "%s.%s", lay, pass);
477         }
478         else
479                 BLI_strncpy(echan->name, passname, EXR_TOT_MAXNAME-1);
480         
481         echan->xstride= xstride;
482         echan->ystride= ystride;
483         echan->rect= rect;
484         
485         // printf("added channel %s\n", echan->name);
486         BLI_addtail(&data->channels, echan);
487 }
488
489 /* only used for writing temp. render results (not image files) */
490 int IMB_exr_begin_write(void *handle, const char *filename, int width, int height, int compress)
491 {
492         ExrHandle *data= (ExrHandle *)handle;
493         Header header (width, height);
494         ExrChannel *echan;
495         
496         data->width= width;
497         data->height= height;
498         
499         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next)
500                 header.channels().insert (echan->name, Channel (FLOAT));
501         
502         openexr_header_compression(&header, compress);
503         // openexr_header_metadata(&header, ibuf); // no imbuf. cant write
504         /* header.lineOrder() = DECREASING_Y; this crashes in windows for file read! */
505         
506         header.insert ("BlenderMultiChannel", StringAttribute ("Blender V2.55.1 and newer"));
507
508         /* avoid crash/abort when we dont have permission to write here */
509         try {
510                 data->ofile = new OutputFile(filename, header);
511         }
512         catch (const std::exception &exc) {
513                 std::cerr << "IMB_exr_begin_write: ERROR: " << exc.what() << std::endl;
514                 data->ofile = NULL;
515         }
516
517         return (data->ofile != NULL);
518 }
519
520 void IMB_exrtile_begin_write(void *handle, const char *filename, int mipmap, int width, int height, int tilex, int tiley)
521 {
522         ExrHandle *data= (ExrHandle *)handle;
523         Header header (width, height);
524         ExrChannel *echan;
525         
526         data->tilex= tilex;
527         data->tiley= tiley;
528         data->width= width;
529         data->height= height;
530         data->mipmap= mipmap;
531         
532         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next)
533                 header.channels().insert (echan->name, Channel (FLOAT));
534         
535         header.setTileDescription (TileDescription (tilex, tiley, (mipmap)? MIPMAP_LEVELS: ONE_LEVEL));
536         header.lineOrder() = RANDOM_Y;
537         header.compression() = RLE_COMPRESSION;
538         
539         header.insert ("BlenderMultiChannel", StringAttribute ("Blender V2.43"));
540         
541         data->tofile = new TiledOutputFile(filename, header);
542 }
543
544 /* read from file */
545 int IMB_exr_begin_read(void *handle, const char *filename, int *width, int *height)
546 {
547         ExrHandle *data= (ExrHandle *)handle;
548         
549         if(BLI_exists(filename) && BLI_file_size(filename)>32) {        /* 32 is arbitrary, but zero length files crashes exr */
550                 data->ifile = new InputFile(filename);
551                 if(data->ifile) {
552                         Box2i dw = data->ifile->header().dataWindow();
553                         data->width= *width  = dw.max.x - dw.min.x + 1;
554                         data->height= *height = dw.max.y - dw.min.y + 1;
555                         
556                         const ChannelList &channels = data->ifile->header().channels();
557                         
558                         for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
559                                 IMB_exr_add_channel(data, NULL, i.name(), 0, 0, NULL);
560                         
561                         return 1;
562                 }
563         }
564         return 0;
565 }
566
567 /* still clumsy name handling, layers/channels can be ordered as list in list later */
568 void IMB_exr_set_channel(void *handle, const char *layname, const char *passname, int xstride, int ystride, float *rect)
569 {
570         ExrHandle *data= (ExrHandle *)handle;
571         ExrChannel *echan;
572         char name[EXR_TOT_MAXNAME + 1];
573         
574         if(layname) {
575                 char lay[EXR_LAY_MAXNAME+1], pass[EXR_PASS_MAXNAME+1];
576                 BLI_strncpy(lay, layname, EXR_LAY_MAXNAME);
577                 BLI_strncpy(pass, passname, EXR_PASS_MAXNAME);
578                 
579                 sprintf(name, "%s.%s", lay, pass);
580         }
581         else
582                 BLI_strncpy(name, passname, EXR_TOT_MAXNAME-1);
583
584         echan= (ExrChannel *)BLI_findstring(&data->channels, name, offsetof(ExrChannel, name));
585
586         if(echan) {
587                 echan->xstride= xstride;
588                 echan->ystride= ystride;
589                 echan->rect= rect;
590         }
591         else
592                 printf("IMB_exrtile_set_channel error %s\n", name);
593 }
594
595 void IMB_exrtile_clear_channels(void *handle)
596 {
597         ExrHandle *data= (ExrHandle *)handle;
598         BLI_freelistN(&data->channels);
599 }
600
601 void IMB_exrtile_write_channels(void *handle, int partx, int party, int level)
602 {
603         ExrHandle *data= (ExrHandle *)handle;
604         FrameBuffer frameBuffer;
605         ExrChannel *echan;
606         
607         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next) {
608                 float *rect= echan->rect - echan->xstride*partx - echan->ystride*party;
609
610                 frameBuffer.insert (echan->name, Slice (FLOAT,  (char *)rect, 
611                                                         echan->xstride*sizeof(float), echan->ystride*sizeof(float)));
612         }
613         
614         data->tofile->setFrameBuffer (frameBuffer);
615
616         try {
617                 // printf("write tile %d %d\n", partx/data->tilex, party/data->tiley);
618                 data->tofile->writeTile (partx/data->tilex, party/data->tiley, level);
619         }
620         catch (const std::exception &exc) {
621                 std::cerr << "OpenEXR-writeTile: ERROR: " << exc.what() << std::endl;
622         }
623 }
624
625 void IMB_exr_write_channels(void *handle)
626 {
627         ExrHandle *data= (ExrHandle *)handle;
628         FrameBuffer frameBuffer;
629         ExrChannel *echan;
630         
631         if(data->channels.first) {
632                 for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next) {
633                         /* last scanline, stride negative */
634                         float *rect = echan->rect + echan->xstride*(data->height-1)*data->width;
635                         
636                         frameBuffer.insert (echan->name, Slice (FLOAT,  (char *)rect, 
637                                                                                                         echan->xstride*sizeof(float), -echan->ystride*sizeof(float)));
638                 }
639                 
640                 data->ofile->setFrameBuffer (frameBuffer);
641                 try {
642                         data->ofile->writePixels (data->height);        
643                 }
644                 catch (const std::exception &exc) {
645                         std::cerr << "OpenEXR-writePixels: ERROR: " << exc.what() << std::endl;
646                 }
647         }
648         else {
649                 printf("Error: attempt to save MultiLayer without layers.\n");
650         }
651 }
652
653 void IMB_exr_read_channels(void *handle)
654 {
655         ExrHandle *data= (ExrHandle *)handle;
656         FrameBuffer frameBuffer;
657         ExrChannel *echan;
658         
659         /* check if exr was saved with previous versions of blender which flipped images */
660         const StringAttribute *ta = data->ifile->header().findTypedAttribute <StringAttribute> ("BlenderMultiChannel");
661         short flip = (ta && strncmp(ta->value().c_str(), "Blender V2.43", 13)==0); /* 'previous multilayer attribute, flipped */
662         
663         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next) {
664                 
665                 if(echan->rect) {
666                         if(flip)
667                                 frameBuffer.insert (echan->name, Slice (FLOAT,  (char *)echan->rect, 
668                                                                                         echan->xstride*sizeof(float), echan->ystride*sizeof(float)));
669                         else
670                                 frameBuffer.insert (echan->name, Slice (FLOAT,  (char *)(echan->rect + echan->xstride*(data->height-1)*data->width), 
671                                                                                         echan->xstride*sizeof(float), -echan->ystride*sizeof(float)));
672                 }
673                 else 
674                         printf("warning, channel with no rect set %s\n", echan->name);
675         }
676         
677         data->ifile->setFrameBuffer (frameBuffer);
678
679         try {
680                 data->ifile->readPixels (0, data->height-1);    
681         }
682         catch (const std::exception &exc) {
683                 std::cerr << "OpenEXR-readPixels: ERROR: " << exc.what() << std::endl;
684         }
685 }
686
687 void IMB_exr_multilayer_convert(void *handle, void *base,  
688                                                                 void * (*addlayer)(void *base, char *str), 
689                                                                 void (*addpass)(void *base, void *lay, char *str, 
690                                                                                                 float *rect, int totchan, char *chan_id))
691 {
692         ExrHandle *data= (ExrHandle *)handle;
693         ExrLayer *lay;
694         ExrPass *pass;
695
696         if(data->layers.first==NULL) {
697                 printf("cannot convert multilayer, no layers in handle\n");
698                 return;
699         }
700
701         for(lay= (ExrLayer *)data->layers.first; lay; lay= lay->next) {
702                 void *laybase= addlayer(base, lay->name);
703                 if(laybase) {
704                         for(pass= (ExrPass *)lay->passes.first; pass; pass= pass->next) {
705                                 addpass(base, laybase, pass->name, pass->rect, pass->totchan, pass->chan_id);
706                                 pass->rect= NULL;
707                         }
708                 }
709         }
710 }
711
712
713 void IMB_exr_close(void *handle)
714 {
715         ExrHandle *data= (ExrHandle *)handle;
716         ExrLayer *lay;
717         ExrPass *pass;
718         
719         if(data->ifile)
720                 delete data->ifile;
721         else if(data->ofile)
722                 delete data->ofile;
723         else if(data->tofile)
724                 delete data->tofile;
725         
726         data->ifile= NULL;
727         data->ofile= NULL;
728         data->tofile= NULL;
729         
730         BLI_freelistN(&data->channels);
731         
732         for(lay= (ExrLayer *)data->layers.first; lay; lay= lay->next) {
733                 for(pass= (ExrPass *)lay->passes.first; pass; pass= pass->next)
734                         if(pass->rect)
735                                 MEM_freeN(pass->rect);
736                 BLI_freelistN(&lay->passes);
737         }
738         BLI_freelistN(&data->layers);
739         
740         BLI_remlink(&exrhandles, data);
741         MEM_freeN(data);
742 }
743
744 /* ********* */
745
746 static int imb_exr_split_channel_name(ExrChannel *echan, char *layname, char *passname)
747 {
748         int plen, len= strlen(echan->name);
749         
750         if(len < 4) {
751                 printf("multilayer read: name too short: %s\n", echan->name);
752                 return 0;
753         }
754         if(echan->name[len-2]!='.') {
755                 printf("multilayer read: name has no Channel: %s\n", echan->name);
756                 return 0;
757         }
758         echan->chan_id= echan->name[len-1];
759         
760         len-= 3;
761         while(len>=0) {
762                 if(echan->name[len]=='.')
763                         break;
764                 len--;
765         }
766         BLI_strncpy(passname, echan->name+len+1, EXR_PASS_MAXNAME);
767         plen= strlen(passname);
768         if(plen < 3) {
769                 printf("multilayer read: should not happen: %s\n", echan->name);
770                 return 0;
771         }
772         passname[plen-2]= 0;
773         
774         if(len<1)
775                 layname[0]= 0;
776         else {
777                 BLI_strncpy(layname, echan->name, EXR_LAY_MAXNAME);
778                 layname[len]= 0;
779         }
780         // printf("found lay %s pass %s chan %c\n", layname, passname, echan->chan_id);
781         return 1;
782 }
783
784 static ExrLayer *imb_exr_get_layer(ListBase *lb, char *layname)
785 {
786         ExrLayer *lay= (ExrLayer *)BLI_findstring(lb, layname, offsetof(ExrLayer, name));
787
788         if(lay==NULL) {
789                 lay= (ExrLayer *)MEM_callocN(sizeof(ExrLayer), "exr layer");
790                 BLI_addtail(lb, lay);
791                 BLI_strncpy(lay->name, layname, EXR_LAY_MAXNAME);
792         }
793
794         return lay;
795 }
796
797 static ExrPass *imb_exr_get_pass(ListBase *lb, char *passname)
798 {
799         ExrPass *pass= (ExrPass *)BLI_findstring(lb, passname, offsetof(ExrPass, name));
800         
801         if(pass==NULL) {
802                 pass= (ExrPass *)MEM_callocN(sizeof(ExrPass), "exr pass");
803
804                 if(strcmp(passname, "Combined")==0)
805                         BLI_addhead(lb, pass);
806                 else
807                         BLI_addtail(lb, pass);
808         }
809
810         BLI_strncpy(pass->name, passname, EXR_LAY_MAXNAME);
811         
812         return pass;
813 }
814
815 /* creates channels, makes a hierarchy and assigns memory to channels */
816 static ExrHandle *imb_exr_begin_read_mem(InputFile *file, int width, int height)
817 {
818         ExrLayer *lay;
819         ExrPass *pass;
820         ExrChannel *echan;
821         ExrHandle *data= (ExrHandle *)IMB_exr_get_handle();
822         int a;
823         char layname[EXR_TOT_MAXNAME], passname[EXR_TOT_MAXNAME];
824         
825         data->ifile= file;
826         data->width= width;
827         data->height= height;
828         
829         const ChannelList &channels = data->ifile->header().channels();
830
831         for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
832                 IMB_exr_add_channel(data, NULL, i.name(), 0, 0, NULL);
833         
834         /* now try to sort out how to assign memory to the channels */
835         /* first build hierarchical layer list */
836         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next) {
837                 if( imb_exr_split_channel_name(echan, layname, passname) ) {
838                         ExrLayer *lay= imb_exr_get_layer(&data->layers, layname);
839                         ExrPass *pass= imb_exr_get_pass(&lay->passes, passname);
840                         
841                         pass->chan[pass->totchan]= echan;
842                         pass->totchan++;
843                         if(pass->totchan>=EXR_PASS_MAXCHAN)
844                                 break;
845                 }
846         }
847         if(echan) {
848                 printf("error, too many channels in one pass: %s\n", echan->name);
849                 IMB_exr_close(data);
850                 return NULL;
851         }
852         
853         /* with some heuristics, try to merge the channels in buffers */
854         for(lay= (ExrLayer *)data->layers.first; lay; lay= lay->next) {
855                 for(pass= (ExrPass *)lay->passes.first; pass; pass= pass->next) {
856                         if(pass->totchan) {
857                                 pass->rect= (float *)MEM_mapallocN(width*height*pass->totchan*sizeof(float), "pass rect");
858                                 if(pass->totchan==1) {
859                                         echan= pass->chan[0];
860                                         echan->rect= pass->rect;
861                                         echan->xstride= 1;
862                                         echan->ystride= width;
863                                         pass->chan_id[0]= echan->chan_id;
864                                 }
865                                 else {
866                                         char lookup[256];
867                                         
868                                         memset(lookup, 0, sizeof(lookup));
869                                                    
870                                         /* we can have RGB(A), XYZ(W), UVA */
871                                         if(pass->totchan==3 || pass->totchan==4) {
872                                                 if(pass->chan[0]->chan_id=='B' || pass->chan[1]->chan_id=='B' ||  pass->chan[2]->chan_id=='B') {
873                                                         lookup[(unsigned int)'R']= 0;
874                                                         lookup[(unsigned int)'G']= 1;
875                                                         lookup[(unsigned int)'B']= 2;
876                                                         lookup[(unsigned int)'A']= 3;
877                                                 }
878                                                 else if(pass->chan[0]->chan_id=='Y' || pass->chan[1]->chan_id=='Y' ||  pass->chan[2]->chan_id=='Y') {
879                                                         lookup[(unsigned int)'X']= 0;
880                                                         lookup[(unsigned int)'Y']= 1;
881                                                         lookup[(unsigned int)'Z']= 2;
882                                                         lookup[(unsigned int)'W']= 3;
883                                                 }
884                                                 else {
885                                                         lookup[(unsigned int)'U']= 0;
886                                                         lookup[(unsigned int)'V']= 1;
887                                                         lookup[(unsigned int)'A']= 2;
888                                                 }
889                                                 for(a=0; a<pass->totchan; a++) {
890                                                         echan= pass->chan[a];
891                                                         echan->rect= pass->rect + lookup[(unsigned int)echan->chan_id];
892                                                         echan->xstride= pass->totchan;
893                                                         echan->ystride= width*pass->totchan;
894                                                         pass->chan_id[ (unsigned int)lookup[(unsigned int)echan->chan_id] ]= echan->chan_id;
895                                                 }
896                                         }
897                                         else { /* unknown */
898                                                 for(a=0; a<pass->totchan; a++) {
899                                                         echan= pass->chan[a];
900                                                         echan->rect= pass->rect + a;
901                                                         echan->xstride= pass->totchan;
902                                                         echan->ystride= width*pass->totchan;
903                                                         pass->chan_id[a]= echan->chan_id;
904                                                 }
905                                         }
906                                 }
907                         }
908                 }
909         }
910         
911         return data;
912 }
913
914
915 /* ********************************************************* */
916
917 typedef struct RGBA
918 {
919         float r;
920         float g;
921         float b;
922         float a;
923 } RGBA;
924
925
926 /* debug only */
927 static void exr_print_filecontents(InputFile *file)
928 {
929         const ChannelList &channels = file->header().channels();
930         
931         for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
932         {
933                 const Channel &channel = i.channel();
934                 printf("OpenEXR-load: Found channel %s of type %d\n", i.name(), channel.type);
935         }
936 }
937
938 /* for non-multilayer, map  R G B A channel names to something that's in this file */
939 static const char *exr_rgba_channelname(InputFile *file, const char *chan)
940 {
941         const ChannelList &channels = file->header().channels();
942         
943         for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
944         {
945                 /* const Channel &channel = i.channel(); */ /* Not used yet */
946                 const char *str= i.name();
947                 int len= strlen(str);
948                 if(len) {
949                         if(BLI_strcasecmp(chan, str+len-1)==0) {
950                                 return str;
951                         }
952                 }
953         }
954         return chan;
955 }
956
957
958
959 static int exr_has_zbuffer(InputFile *file)
960 {
961         return !(file->header().channels().findChannel("Z") == NULL);
962 }
963
964 static int exr_is_renderresult(InputFile *file)
965 {
966         const StringAttribute *comments= file->header().findTypedAttribute<StringAttribute>("BlenderMultiChannel");
967         if(comments)
968 //              if(comments->value() == "Blender MultiChannel")
969                         return 1;
970         return 0;
971 }
972
973 struct ImBuf *imb_load_openexr(unsigned char *mem, size_t size, int flags)
974 {
975         struct ImBuf *ibuf = NULL;
976         InputFile *file = NULL;
977         
978         if (imb_is_a_openexr(mem) == 0) return(NULL);
979         
980         try
981         {
982                 Mem_IStream *membuf = new Mem_IStream(mem, size); 
983                 int is_multi;
984                 file = new InputFile(*membuf);
985                 
986                 Box2i dw = file->header().dataWindow();
987                 int width  = dw.max.x - dw.min.x + 1;
988                 int height = dw.max.y - dw.min.y + 1;
989                 
990                 //printf("OpenEXR-load: image data window %d %d %d %d\n", 
991                 //         dw.min.x, dw.min.y, dw.max.x, dw.max.y);
992
993                 if(0) // debug
994                         exr_print_filecontents(file);
995                 
996                 is_multi= exr_is_renderresult(file);
997                 
998                 /* do not make an ibuf when */
999                 if(is_multi && !(flags & IB_test) && !(flags & IB_multilayer)) 
1000                 {
1001                         printf("Error: can't process EXR multilayer file\n");
1002                 }
1003                 else {
1004                 
1005                         ibuf = IMB_allocImBuf(width, height, 32, 0);
1006                         ibuf->ftype = OPENEXR;
1007
1008                         /* openEXR is linear as per EXR spec */
1009                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1010                         
1011                         if (!(flags & IB_test))
1012                         {
1013                                 if(is_multi) /* only enters with IB_multilayer flag set */
1014                                 {
1015                                         /* constructs channels for reading, allocates memory in channels */
1016                                         ExrHandle *handle= imb_exr_begin_read_mem(file, width, height);
1017                                         if(handle) {
1018                                                 IMB_exr_read_channels(handle);
1019                                                 ibuf->userdata= handle;                 /* potential danger, the caller has to check for this! */
1020                                                 return ibuf;
1021                                         }
1022                                 }
1023                                 else {
1024                                         FrameBuffer frameBuffer;
1025                                         float *first;
1026                                         int xstride = sizeof(float) * 4;
1027                                         int ystride = - xstride*width;
1028                                         
1029                                         imb_addrectfloatImBuf(ibuf);
1030                                         
1031                                         /* inverse correct first pixel for datawindow coordinates (- dw.min.y because of y flip) */
1032                                         first= ibuf->rect_float - 4*(dw.min.x - dw.min.y*width);
1033                                         /* but, since we read y-flipped (negative y stride) we move to last scanline */
1034                                         first+= 4*(height-1)*width;
1035                                         
1036                                         frameBuffer.insert ( exr_rgba_channelname(file, "R"), 
1037                                                                                 Slice (FLOAT,  (char *) first, xstride, ystride));
1038                                         frameBuffer.insert ( exr_rgba_channelname(file, "G"), 
1039                                                                                 Slice (FLOAT,  (char *) (first+1), xstride, ystride));
1040                                         frameBuffer.insert ( exr_rgba_channelname(file, "B"), 
1041                                                                                 Slice (FLOAT,  (char *) (first+2), xstride, ystride));
1042                                                                                                                                                         
1043                                         frameBuffer.insert ( exr_rgba_channelname(file, "A"), 
1044                                                                                 Slice (FLOAT,  (char *) (first+3), xstride, ystride, 1, 1, 1.0f)); /* 1.0 is fill value */
1045
1046                                         if(exr_has_zbuffer(file)) 
1047                                         {
1048                                                 float *firstz;
1049                                                 
1050                                                 addzbuffloatImBuf(ibuf);
1051                                                 firstz= ibuf->zbuf_float - (dw.min.x - dw.min.y*width);
1052                                                 firstz+= (height-1)*width;
1053                                                 frameBuffer.insert ("Z", Slice (FLOAT,  (char *)firstz , sizeof(float), -width*sizeof(float)));
1054                                         }
1055                                         
1056                                         file->setFrameBuffer (frameBuffer);
1057                                         file->readPixels (dw.min.y, dw.max.y);
1058
1059                                         // XXX, ImBuf has no nice way to deal with this.
1060                                         // ideally IM_rect would be used when the caller wants a rect BUT
1061                                         // at the moment all functions use IM_rect.
1062                                         // Disabling this is ok because all functions should check if a rect exists and create one on demand.
1063                                         //
1064                                         // Disabling this because the sequencer frees immediate.
1065                                         //
1066                                         // if(flag & IM_rect)
1067                                         //     IMB_rect_from_float(ibuf);
1068                                 }
1069                         }
1070                         
1071                 }
1072                 delete file;
1073                 return(ibuf);
1074         }
1075         catch (const std::exception &exc)
1076         {
1077                 std::cerr << exc.what() << std::endl;
1078                 if (ibuf) IMB_freeImBuf(ibuf);
1079                 delete file;
1080                 
1081                 return (0);
1082         }
1083         
1084 }
1085
1086
1087 } // export "C"