7b528ed962452c176260399755e603e620211957
[blender-staging.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->depth==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->depth==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->depth==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->depth==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 void 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         data->ofile = new OutputFile(filename, header);
509 }
510
511 void IMB_exrtile_begin_write(void *handle, const char *filename, int mipmap, int width, int height, int tilex, int tiley)
512 {
513         ExrHandle *data= (ExrHandle *)handle;
514         Header header (width, height);
515         ExrChannel *echan;
516         
517         data->tilex= tilex;
518         data->tiley= tiley;
519         data->width= width;
520         data->height= height;
521         data->mipmap= mipmap;
522         
523         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next)
524                 header.channels().insert (echan->name, Channel (FLOAT));
525         
526         header.setTileDescription (TileDescription (tilex, tiley, (mipmap)? MIPMAP_LEVELS: ONE_LEVEL));
527         header.lineOrder() = RANDOM_Y;
528         header.compression() = RLE_COMPRESSION;
529         
530         header.insert ("BlenderMultiChannel", StringAttribute ("Blender V2.43"));
531         
532         data->tofile = new TiledOutputFile(filename, header);
533 }
534
535 /* read from file */
536 int IMB_exr_begin_read(void *handle, const char *filename, int *width, int *height)
537 {
538         ExrHandle *data= (ExrHandle *)handle;
539         
540         if(BLI_exists(filename) && BLI_filepathsize(filename)>32) {     /* 32 is arbitrary, but zero length files crashes exr */
541                 data->ifile = new InputFile(filename);
542                 if(data->ifile) {
543                         Box2i dw = data->ifile->header().dataWindow();
544                         data->width= *width  = dw.max.x - dw.min.x + 1;
545                         data->height= *height = dw.max.y - dw.min.y + 1;
546                         
547                         const ChannelList &channels = data->ifile->header().channels();
548                         
549                         for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
550                                 IMB_exr_add_channel(data, NULL, i.name(), 0, 0, NULL);
551                         
552                         return 1;
553                 }
554         }
555         return 0;
556 }
557
558 /* still clumsy name handling, layers/channels can be ordered as list in list later */
559 void IMB_exr_set_channel(void *handle, const char *layname, const char *passname, int xstride, int ystride, float *rect)
560 {
561         ExrHandle *data= (ExrHandle *)handle;
562         ExrChannel *echan;
563         char name[EXR_TOT_MAXNAME + 1];
564         
565         if(layname) {
566                 char lay[EXR_LAY_MAXNAME+1], pass[EXR_PASS_MAXNAME+1];
567                 BLI_strncpy(lay, layname, EXR_LAY_MAXNAME);
568                 BLI_strncpy(pass, passname, EXR_PASS_MAXNAME);
569                 
570                 sprintf(name, "%s.%s", lay, pass);
571         }
572         else
573                 BLI_strncpy(name, passname, EXR_TOT_MAXNAME-1);
574
575         echan= (ExrChannel *)BLI_findstring(&data->channels, name, offsetof(ExrChannel, name));
576
577         if(echan) {
578                 echan->xstride= xstride;
579                 echan->ystride= ystride;
580                 echan->rect= rect;
581         }
582         else
583                 printf("IMB_exrtile_set_channel error %s\n", name);
584 }
585
586 void IMB_exrtile_clear_channels(void *handle)
587 {
588         ExrHandle *data= (ExrHandle *)handle;
589         BLI_freelistN(&data->channels);
590 }
591
592 void IMB_exrtile_write_channels(void *handle, int partx, int party, int level)
593 {
594         ExrHandle *data= (ExrHandle *)handle;
595         FrameBuffer frameBuffer;
596         ExrChannel *echan;
597         
598         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next) {
599                 float *rect= echan->rect - echan->xstride*partx - echan->ystride*party;
600
601                 frameBuffer.insert (echan->name, Slice (FLOAT,  (char *)rect, 
602                                                         echan->xstride*sizeof(float), echan->ystride*sizeof(float)));
603         }
604         
605         data->tofile->setFrameBuffer (frameBuffer);
606
607         try {
608                 // printf("write tile %d %d\n", partx/data->tilex, party/data->tiley);
609                 data->tofile->writeTile (partx/data->tilex, party/data->tiley, level);
610         }
611         catch (const std::exception &exc) {
612                 std::cerr << "OpenEXR-writeTile: ERROR: " << exc.what() << std::endl;
613         }
614 }
615
616 void IMB_exr_write_channels(void *handle)
617 {
618         ExrHandle *data= (ExrHandle *)handle;
619         FrameBuffer frameBuffer;
620         ExrChannel *echan;
621         
622         if(data->channels.first) {
623                 for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next) {
624                         /* last scanline, stride negative */
625                         float *rect = echan->rect + echan->xstride*(data->height-1)*data->width;
626                         
627                         frameBuffer.insert (echan->name, Slice (FLOAT,  (char *)rect, 
628                                                                                                         echan->xstride*sizeof(float), -echan->ystride*sizeof(float)));
629                 }
630                 
631                 data->ofile->setFrameBuffer (frameBuffer);
632                 try {
633                         data->ofile->writePixels (data->height);        
634                 }
635                 catch (const std::exception &exc) {
636                         std::cerr << "OpenEXR-writePixels: ERROR: " << exc.what() << std::endl;
637                 }
638         }
639         else {
640                 printf("Error: attempt to save MultiLayer without layers.\n");
641         }
642 }
643
644 void IMB_exr_read_channels(void *handle)
645 {
646         ExrHandle *data= (ExrHandle *)handle;
647         FrameBuffer frameBuffer;
648         ExrChannel *echan;
649         
650         /* check if exr was saved with previous versions of blender which flipped images */
651         const StringAttribute *ta = data->ifile->header().findTypedAttribute <StringAttribute> ("BlenderMultiChannel");
652         short flip = (ta && strncmp(ta->value().c_str(), "Blender V2.43", 13)==0); /* 'previous multilayer attribute, flipped */
653         
654         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next) {
655                 
656                 if(echan->rect) {
657                         if(flip)
658                                 frameBuffer.insert (echan->name, Slice (FLOAT,  (char *)echan->rect, 
659                                                                                         echan->xstride*sizeof(float), echan->ystride*sizeof(float)));
660                         else
661                                 frameBuffer.insert (echan->name, Slice (FLOAT,  (char *)(echan->rect + echan->xstride*(data->height-1)*data->width), 
662                                                                                         echan->xstride*sizeof(float), -echan->ystride*sizeof(float)));
663                 }
664                 else 
665                         printf("warning, channel with no rect set %s\n", echan->name);
666         }
667         
668         data->ifile->setFrameBuffer (frameBuffer);
669
670         try {
671                 data->ifile->readPixels (0, data->height-1);    
672         }
673         catch (const std::exception &exc) {
674                 std::cerr << "OpenEXR-readPixels: ERROR: " << exc.what() << std::endl;
675         }
676 }
677
678 void IMB_exr_multilayer_convert(void *handle, void *base,  
679                                                                 void * (*addlayer)(void *base, char *str), 
680                                                                 void (*addpass)(void *base, void *lay, char *str, 
681                                                                                                 float *rect, int totchan, char *chan_id))
682 {
683         ExrHandle *data= (ExrHandle *)handle;
684         ExrLayer *lay;
685         ExrPass *pass;
686
687         if(data->layers.first==NULL) {
688                 printf("cannot convert multilayer, no layers in handle\n");
689                 return;
690         }
691
692         for(lay= (ExrLayer *)data->layers.first; lay; lay= lay->next) {
693                 void *laybase= addlayer(base, lay->name);
694                 if(laybase) {
695                         for(pass= (ExrPass *)lay->passes.first; pass; pass= pass->next) {
696                                 addpass(base, laybase, pass->name, pass->rect, pass->totchan, pass->chan_id);
697                                 pass->rect= NULL;
698                         }
699                 }
700         }
701 }
702
703
704 void IMB_exr_close(void *handle)
705 {
706         ExrHandle *data= (ExrHandle *)handle;
707         ExrLayer *lay;
708         ExrPass *pass;
709         
710         if(data->ifile)
711                 delete data->ifile;
712         else if(data->ofile)
713                 delete data->ofile;
714         else if(data->tofile)
715                 delete data->tofile;
716         
717         data->ifile= NULL;
718         data->ofile= NULL;
719         data->tofile= NULL;
720         
721         BLI_freelistN(&data->channels);
722         
723         for(lay= (ExrLayer *)data->layers.first; lay; lay= lay->next) {
724                 for(pass= (ExrPass *)lay->passes.first; pass; pass= pass->next)
725                         if(pass->rect)
726                                 MEM_freeN(pass->rect);
727                 BLI_freelistN(&lay->passes);
728         }
729         BLI_freelistN(&data->layers);
730         
731         BLI_remlink(&exrhandles, data);
732         MEM_freeN(data);
733 }
734
735 /* ********* */
736
737 static int imb_exr_split_channel_name(ExrChannel *echan, char *layname, char *passname)
738 {
739         int plen, len= strlen(echan->name);
740         
741         if(len < 4) {
742                 printf("multilayer read: name too short: %s\n", echan->name);
743                 return 0;
744         }
745         if(echan->name[len-2]!='.') {
746                 printf("multilayer read: name has no Channel: %s\n", echan->name);
747                 return 0;
748         }
749         echan->chan_id= echan->name[len-1];
750         
751         len-= 3;
752         while(len>=0) {
753                 if(echan->name[len]=='.')
754                         break;
755                 len--;
756         }
757         BLI_strncpy(passname, echan->name+len+1, EXR_PASS_MAXNAME);
758         plen= strlen(passname);
759         if(plen < 3) {
760                 printf("multilayer read: should not happen: %s\n", echan->name);
761                 return 0;
762         }
763         passname[plen-2]= 0;
764         
765         if(len<1)
766                 layname[0]= 0;
767         else {
768                 BLI_strncpy(layname, echan->name, EXR_LAY_MAXNAME);
769                 layname[len]= 0;
770         }
771         // printf("found lay %s pass %s chan %c\n", layname, passname, echan->chan_id);
772         return 1;
773 }
774
775 static ExrLayer *imb_exr_get_layer(ListBase *lb, char *layname)
776 {
777         ExrLayer *lay= (ExrLayer *)BLI_findstring(lb, layname, offsetof(ExrLayer, name));
778
779         if(lay==NULL) {
780                 lay= (ExrLayer *)MEM_callocN(sizeof(ExrLayer), "exr layer");
781                 BLI_addtail(lb, lay);
782                 BLI_strncpy(lay->name, layname, EXR_LAY_MAXNAME);
783         }
784
785         return lay;
786 }
787
788 static ExrPass *imb_exr_get_pass(ListBase *lb, char *passname)
789 {
790         ExrPass *pass= (ExrPass *)BLI_findstring(lb, passname, offsetof(ExrPass, name));
791         
792         if(pass==NULL) {
793                 pass= (ExrPass *)MEM_callocN(sizeof(ExrPass), "exr pass");
794
795                 if(strcmp(passname, "Combined")==0)
796                         BLI_addhead(lb, pass);
797                 else
798                         BLI_addtail(lb, pass);
799         }
800
801         BLI_strncpy(pass->name, passname, EXR_LAY_MAXNAME);
802         
803         return pass;
804 }
805
806 /* creates channels, makes a hierarchy and assigns memory to channels */
807 static ExrHandle *imb_exr_begin_read_mem(InputFile *file, int width, int height)
808 {
809         ExrLayer *lay;
810         ExrPass *pass;
811         ExrChannel *echan;
812         ExrHandle *data= (ExrHandle *)IMB_exr_get_handle();
813         int a;
814         char layname[EXR_TOT_MAXNAME], passname[EXR_TOT_MAXNAME];
815         
816         data->ifile= file;
817         data->width= width;
818         data->height= height;
819         
820         const ChannelList &channels = data->ifile->header().channels();
821
822         for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
823                 IMB_exr_add_channel(data, NULL, i.name(), 0, 0, NULL);
824         
825         /* now try to sort out how to assign memory to the channels */
826         /* first build hierarchical layer list */
827         for(echan= (ExrChannel *)data->channels.first; echan; echan= echan->next) {
828                 if( imb_exr_split_channel_name(echan, layname, passname) ) {
829                         ExrLayer *lay= imb_exr_get_layer(&data->layers, layname);
830                         ExrPass *pass= imb_exr_get_pass(&lay->passes, passname);
831                         
832                         pass->chan[pass->totchan]= echan;
833                         pass->totchan++;
834                         if(pass->totchan>=EXR_PASS_MAXCHAN)
835                                 break;
836                 }
837         }
838         if(echan) {
839                 printf("error, too many channels in one pass: %s\n", echan->name);
840                 IMB_exr_close(data);
841                 return NULL;
842         }
843         
844         /* with some heuristics, try to merge the channels in buffers */
845         for(lay= (ExrLayer *)data->layers.first; lay; lay= lay->next) {
846                 for(pass= (ExrPass *)lay->passes.first; pass; pass= pass->next) {
847                         if(pass->totchan) {
848                                 pass->rect= (float *)MEM_mapallocN(width*height*pass->totchan*sizeof(float), "pass rect");
849                                 if(pass->totchan==1) {
850                                         echan= pass->chan[0];
851                                         echan->rect= pass->rect;
852                                         echan->xstride= 1;
853                                         echan->ystride= width;
854                                         pass->chan_id[0]= echan->chan_id;
855                                 }
856                                 else {
857                                         char lookup[256];
858                                         
859                                         memset(lookup, 0, sizeof(lookup));
860                                                    
861                                         /* we can have RGB(A), XYZ(W), UVA */
862                                         if(pass->totchan==3 || pass->totchan==4) {
863                                                 if(pass->chan[0]->chan_id=='B' || pass->chan[1]->chan_id=='B' ||  pass->chan[2]->chan_id=='B') {
864                                                         lookup[(unsigned int)'R']= 0;
865                                                         lookup[(unsigned int)'G']= 1;
866                                                         lookup[(unsigned int)'B']= 2;
867                                                         lookup[(unsigned int)'A']= 3;
868                                                 }
869                                                 else if(pass->chan[0]->chan_id=='Y' || pass->chan[1]->chan_id=='Y' ||  pass->chan[2]->chan_id=='Y') {
870                                                         lookup[(unsigned int)'X']= 0;
871                                                         lookup[(unsigned int)'Y']= 1;
872                                                         lookup[(unsigned int)'Z']= 2;
873                                                         lookup[(unsigned int)'W']= 3;
874                                                 }
875                                                 else {
876                                                         lookup[(unsigned int)'U']= 0;
877                                                         lookup[(unsigned int)'V']= 1;
878                                                         lookup[(unsigned int)'A']= 2;
879                                                 }
880                                                 for(a=0; a<pass->totchan; a++) {
881                                                         echan= pass->chan[a];
882                                                         echan->rect= pass->rect + lookup[(unsigned int)echan->chan_id];
883                                                         echan->xstride= pass->totchan;
884                                                         echan->ystride= width*pass->totchan;
885                                                         pass->chan_id[ (unsigned int)lookup[(unsigned int)echan->chan_id] ]= echan->chan_id;
886                                                 }
887                                         }
888                                         else { /* unknown */
889                                                 for(a=0; a<pass->totchan; a++) {
890                                                         echan= pass->chan[a];
891                                                         echan->rect= pass->rect + a;
892                                                         echan->xstride= pass->totchan;
893                                                         echan->ystride= width*pass->totchan;
894                                                         pass->chan_id[a]= echan->chan_id;
895                                                 }
896                                         }
897                                 }
898                         }
899                 }
900         }
901         
902         return data;
903 }
904
905
906 /* ********************************************************* */
907
908 typedef struct RGBA
909 {
910         float r;
911         float g;
912         float b;
913         float a;
914 } RGBA;
915
916
917 /* debug only */
918 static void exr_print_filecontents(InputFile *file)
919 {
920         const ChannelList &channels = file->header().channels();
921         
922         for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
923         {
924                 const Channel &channel = i.channel();
925                 printf("OpenEXR-load: Found channel %s of type %d\n", i.name(), channel.type);
926         }
927 }
928
929 /* for non-multilayer, map  R G B A channel names to something that's in this file */
930 static const char *exr_rgba_channelname(InputFile *file, const char *chan)
931 {
932         const ChannelList &channels = file->header().channels();
933         
934         for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i)
935         {
936                 /* const Channel &channel = i.channel(); */ /* Not used yet */
937                 const char *str= i.name();
938                 int len= strlen(str);
939                 if(len) {
940                         if(BLI_strcasecmp(chan, str+len-1)==0) {
941                                 return str;
942                         }
943                 }
944         }
945         return chan;
946 }
947
948
949
950 static int exr_has_zbuffer(InputFile *file)
951 {
952         return !(file->header().channels().findChannel("Z") == NULL);
953 }
954
955 static int exr_is_renderresult(InputFile *file)
956 {
957         const StringAttribute *comments= file->header().findTypedAttribute<StringAttribute>("BlenderMultiChannel");
958         if(comments)
959 //              if(comments->value() == "Blender MultiChannel")
960                         return 1;
961         return 0;
962 }
963
964 struct ImBuf *imb_load_openexr(unsigned char *mem, size_t size, int flags)
965 {
966         struct ImBuf *ibuf = NULL;
967         InputFile *file = NULL;
968         
969         if (imb_is_a_openexr(mem) == 0) return(NULL);
970         
971         try
972         {
973                 Mem_IStream *membuf = new Mem_IStream(mem, size); 
974                 int is_multi;
975                 file = new InputFile(*membuf);
976                 
977                 Box2i dw = file->header().dataWindow();
978                 int width  = dw.max.x - dw.min.x + 1;
979                 int height = dw.max.y - dw.min.y + 1;
980                 
981                 //printf("OpenEXR-load: image data window %d %d %d %d\n", 
982                 //         dw.min.x, dw.min.y, dw.max.x, dw.max.y);
983
984                 if(0) // debug
985                         exr_print_filecontents(file);
986                 
987                 is_multi= exr_is_renderresult(file);
988                 
989                 /* do not make an ibuf when */
990                 if(is_multi && !(flags & IB_test) && !(flags & IB_multilayer)) 
991                 {
992                         printf("Error: can't process EXR multilayer file\n");
993                 }
994                 else {
995                 
996                         ibuf = IMB_allocImBuf(width, height, 32, 0);
997                         ibuf->ftype = OPENEXR;
998
999                         /* openEXR is linear as per EXR spec */
1000                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1001                         
1002                         if (!(flags & IB_test))
1003                         {
1004                                 if(is_multi) /* only enters with IB_multilayer flag set */
1005                                 {
1006                                         /* constructs channels for reading, allocates memory in channels */
1007                                         ExrHandle *handle= imb_exr_begin_read_mem(file, width, height);
1008                                         if(handle) {
1009                                                 IMB_exr_read_channels(handle);
1010                                                 ibuf->userdata= handle;                 /* potential danger, the caller has to check for this! */
1011                                                 return ibuf;
1012                                         }
1013                                 }
1014                                 else {
1015                                         FrameBuffer frameBuffer;
1016                                         float *first;
1017                                         int xstride = sizeof(float) * 4;
1018                                         int ystride = - xstride*width;
1019                                         
1020                                         imb_addrectfloatImBuf(ibuf);
1021                                         
1022                                         /* inverse correct first pixel for datawindow coordinates (- dw.min.y because of y flip) */
1023                                         first= ibuf->rect_float - 4*(dw.min.x - dw.min.y*width);
1024                                         /* but, since we read y-flipped (negative y stride) we move to last scanline */
1025                                         first+= 4*(height-1)*width;
1026                                         
1027                                         frameBuffer.insert ( exr_rgba_channelname(file, "R"), 
1028                                                                                 Slice (FLOAT,  (char *) first, xstride, ystride));
1029                                         frameBuffer.insert ( exr_rgba_channelname(file, "G"), 
1030                                                                                 Slice (FLOAT,  (char *) (first+1), xstride, ystride));
1031                                         frameBuffer.insert ( exr_rgba_channelname(file, "B"), 
1032                                                                                 Slice (FLOAT,  (char *) (first+2), xstride, ystride));
1033                                                                                                                                                         
1034                                         frameBuffer.insert ( exr_rgba_channelname(file, "A"), 
1035                                                                                 Slice (FLOAT,  (char *) (first+3), xstride, ystride, 1, 1, 1.0f)); /* 1.0 is fill value */
1036
1037                                         if(exr_has_zbuffer(file)) 
1038                                         {
1039                                                 float *firstz;
1040                                                 
1041                                                 addzbuffloatImBuf(ibuf);
1042                                                 firstz= ibuf->zbuf_float - (dw.min.x - dw.min.y*width);
1043                                                 firstz+= (height-1)*width;
1044                                                 frameBuffer.insert ("Z", Slice (FLOAT,  (char *)firstz , sizeof(float), -width*sizeof(float)));
1045                                         }
1046                                         
1047                                         file->setFrameBuffer (frameBuffer);
1048                                         file->readPixels (dw.min.y, dw.max.y);
1049
1050                                         // XXX, ImBuf has no nice way to deal with this.
1051                                         // ideally IM_rect would be used when the caller wants a rect BUT
1052                                         // at the moment all functions use IM_rect.
1053                                         // Disabling this is ok because all functions should check if a rect exists and create one on demand.
1054                                         //
1055                                         // Disabling this because the sequencer frees immediate.
1056                                         //
1057                                         // if(flag & IM_rect)
1058                                         //     IMB_rect_from_float(ibuf);
1059                                 }
1060                         }
1061                         
1062                 }
1063                 delete file;
1064                 return(ibuf);
1065         }
1066         catch (const std::exception &exc)
1067         {
1068                 std::cerr << exc.what() << std::endl;
1069                 if (ibuf) IMB_freeImBuf(ibuf);
1070                 delete file;
1071                 
1072                 return (0);
1073         }
1074         
1075 }
1076
1077
1078 } // export "C"