Mac / COCOA :
[blender-staging.git] / source / blender / imbuf / intern / imbuf_cocoa.m
1 /*
2  * imbuf_coca.m
3  *
4  * $Id$
5  * 
6  * ***** BEGIN GPL LICENSE 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * Contributor(s): Damien Plisson 10/2009
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /**
28  * Provides image file loading and saving for Blender, via Cocoa.
29  *
30  */
31
32 #include <stdint.h>
33 #include <string.h>
34 #import <Cocoa/Cocoa.h>
35
36 #include "imbuf.h"
37 #include "imbuf_patch.h"
38
39 #include "IMB_cocoa.h"
40
41 #include "BKE_global.h"
42 #include "BKE_colortools.h"
43
44 #include "IMB_imbuf_types.h"
45 #include "IMB_imbuf.h"
46
47 #include "IMB_allocimbuf.h"
48
49
50
51 #pragma mark load/save functions
52
53 /**
54  * Loads an image from the supplied buffer
55  *
56  * Loads any Core Graphics supported type
57  * Currently is : TIFF, BMP, JPEG, GIF, PNG, DIB, ICO, and various RAW formats
58  *
59  * @param mem:   Memory containing the bitmap image
60  * @param size:  Size of the mem buffer.
61  * @param flags: If flags has IB_test set then the file is not actually loaded,
62  *                but all other operations take place.
63  *
64  * @return: A newly allocated ImBuf structure if successful, otherwise NULL.
65  */
66 struct ImBuf *imb_cocoaLoadImage(unsigned char *mem, int size, int flags)
67 {
68         struct ImBuf *ibuf = NULL;
69         uint32_t width, height;
70         uchar *rasterRGB = NULL;
71         uchar *rasterRGBA = NULL;
72         uchar *toIBuf = NULL;
73         int x, y, to_i, from_i;
74         NSData *data;
75         NSBitmapImageRep *bitmapImage;
76         NSBitmapImageRep *blBitmapFormatImageRGB,*blBitmapFormatImageRGBA;
77         NSAutoreleasePool *pool;
78         
79         pool = [[NSAutoreleasePool alloc] init];
80         
81         data = [NSData dataWithBytes:mem length:size];
82         bitmapImage = [[NSBitmapImageRep alloc] initWithData:data];
83
84         if (!bitmapImage) {
85                 fprintf(stderr, "imb_cocoaLoadImage: error loading image\n");
86                 [pool drain];
87                 return NULL;
88         }
89         
90         width = [bitmapImage pixelsWide];
91         height = [bitmapImage pixelsHigh];
92         
93         /* allocate the image buffer */
94         ibuf = IMB_allocImBuf(width, height, 32/*RGBA*/, 0, 0);
95         if (!ibuf) {
96                 fprintf(stderr, 
97                         "imb_cocoaLoadImage: could not allocate memory for the " \
98                         "image.\n");
99                 [bitmapImage release];
100                 [pool drain];
101                 return NULL;
102         }
103
104         /* read in the image data */
105         if (!(flags & IB_test)) {
106
107                 /* allocate memory for the ibuf->rect */
108                 imb_addrectImBuf(ibuf);
109
110                 /* Convert the image in a RGBA 32bit format */
111                 /* As Core Graphics does not support contextes with non premutliplied alpha,
112                  we need to get alpha key values in a separate batch */
113                 
114                 /* First get RGB values w/o Alpha to avoid pre-multiplication, 32bit but last byte is unused */
115                 blBitmapFormatImageRGB = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
116                                                                                                                                           pixelsWide:width 
117                                                                                                                                           pixelsHigh:height
118                                                                                                                                    bitsPerSample:8 samplesPerPixel:3 hasAlpha:NO isPlanar:NO
119                                                                                                                                   colorSpaceName:NSCalibratedRGBColorSpace 
120                                                                                                                                         bitmapFormat:0
121                                                                                                                                          bytesPerRow:4*width
122                                                                                                                                         bitsPerPixel:32/*RGB format padded to 32bits*/];
123                                 
124                 [NSGraphicsContext saveGraphicsState];
125                 [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:blBitmapFormatImageRGB]];
126                 [bitmapImage draw];
127                 [NSGraphicsContext restoreGraphicsState];
128                 
129                 rasterRGB = (uchar*)[blBitmapFormatImageRGB bitmapData];
130                 if (rasterRGB == NULL) {
131                         [bitmapImage release];
132                         [blBitmapFormatImageRGB release];
133                         [pool drain];
134                         return NULL;
135                 }
136
137                 /* Then get Alpha values by getting the RGBA image (that is premultiplied btw) */
138                 blBitmapFormatImageRGBA = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
139                                                                                                                                                   pixelsWide:width
140                                                                                                                                                   pixelsHigh:height
141                                                                                                                                            bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
142                                                                                                                                           colorSpaceName:NSCalibratedRGBColorSpace
143                                                                                                                                                 bitmapFormat:0
144                                                                                                                                                  bytesPerRow:4*width
145                                                                                                                                                 bitsPerPixel:32/* RGBA */];
146                 
147                 [NSGraphicsContext saveGraphicsState];
148                 [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:blBitmapFormatImageRGBA]];
149                 [bitmapImage draw];
150                 [NSGraphicsContext restoreGraphicsState];
151                 
152                 rasterRGBA = (uchar*)[blBitmapFormatImageRGBA bitmapData];
153                 if (rasterRGBA == NULL) {
154                         [bitmapImage release];
155                         [blBitmapFormatImageRGB release];
156                         [blBitmapFormatImageRGBA release];
157                         [pool drain];
158                         return NULL;
159                 }
160                 
161                 /*Copy the image to ibuf, flipping it vertically*/
162                 toIBuf = (uchar*)ibuf->rect;
163                 for (x = 0; x < width; x++) {
164                         for (y = 0; y < height; y++) {
165                                 to_i = (height-y-1)*width + x;
166                                 from_i = y*width + x;
167
168                                 toIBuf[4*to_i] = rasterRGB[4*from_i]; /* R */
169                                 toIBuf[4*to_i+1] = rasterRGB[4*from_i+1]; /* G */
170                                 toIBuf[4*to_i+2] = rasterRGB[4*from_i+2]; /* B */
171                                 toIBuf[4*to_i+3] = rasterRGBA[4*from_i+3]; /* A */
172                         }
173                 }
174
175                 [blBitmapFormatImageRGB release];
176                 [blBitmapFormatImageRGBA release];
177         }
178
179         /* release the cocoa objects */
180         [bitmapImage release];
181         [pool drain];
182
183         if (ENDIAN_ORDER == B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
184
185         /* return successfully */
186         return (ibuf);
187 }
188
189 /**
190  * Saves an image to a file.
191  *
192  * ImBuf structures with 1, 3 or 4 bytes per pixel (GRAY, RGB, RGBA 
193  * respectively) are accepted, and interpreted correctly. 
194  *
195  * Accepted formats: TIFF, GIF, BMP, PNG, JPEG, JPEG2000
196  *
197  * @param ibuf:  Image buffer.
198  * @param name:  Name of the image file to create.
199  * @param flags: Currently largely ignored.
200  *
201  * @return: 1 if the function is successful, 0 on failure.
202  */
203
204 #define FTOUSHORT(val) ((val >= 1.0f-0.5f/65535)? 65535: (val <= 0.0f)? 0: (unsigned short)(val*65535.0f + 0.5f))
205
206 short imb_cocoaSaveImage(struct ImBuf *ibuf, char *name, int flags)
207 {
208         uint16_t samplesperpixel, bitspersample;
209         unsigned char *from = NULL, *to = NULL;
210         unsigned short *to16 = NULL;
211         float *fromf = NULL;
212         int x, y, from_i, to_i, i;
213         int success;
214         BOOL hasAlpha;
215         NSString* colorSpace;
216         NSBitmapImageRep *blBitmapFormatImage;
217         NSData *dataToWrite;
218         NSDictionary *imageProperties;
219         
220         NSAutoreleasePool *pool;
221         
222         if (!ibuf) return FALSE;
223         if (!name) return FALSE;
224         
225         /* check for a valid number of bytes per pixel.  Like the PNG writer,
226          * the TIFF writer supports 1, 3 or 4 bytes per pixel, corresponding
227          * to gray, RGB, RGBA respectively. */
228         samplesperpixel = (uint16_t)((ibuf->depth + 7) >> 3);
229         switch (samplesperpixel) {
230                 case 4: /*RGBA type*/
231                         hasAlpha = YES;
232                         colorSpace = NSCalibratedRGBColorSpace;
233                         break;
234                 case 3: /*RGB type*/
235                         hasAlpha = NO;
236                         colorSpace = NSCalibratedRGBColorSpace;
237                         break;
238                 case 1:
239                         hasAlpha = NO;
240                         colorSpace = NSCalibratedWhiteColorSpace;
241                         break;
242                 default:
243                         fprintf(stderr,
244                                         "imb_cocoaSaveImage: unsupported number of bytes per " 
245                                         "pixel: %d\n", samplesperpixel);
246                         return (0);
247         }
248
249         if((ibuf->ftype & TIF_16BIT) && ibuf->rect_float)
250                 bitspersample = 16;
251         else
252                 bitspersample = 8;
253
254         pool = [[NSAutoreleasePool alloc] init];
255         
256         /* Create bitmap image rep in blender format */
257         blBitmapFormatImage = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
258                                                                                                                                   pixelsWide:ibuf->x 
259                                                                                                                                   pixelsHigh:ibuf->y
260                                                                                                                            bitsPerSample:bitspersample samplesPerPixel:samplesperpixel hasAlpha:hasAlpha isPlanar:NO
261                                                                                                                           colorSpaceName:colorSpace 
262                                                                                                                                 bitmapFormat:NSAlphaNonpremultipliedBitmapFormat
263                                                                                                                                  bytesPerRow:(ibuf->x*bitspersample*samplesperpixel/8)
264                                                                                                                                 bitsPerPixel:(bitspersample*samplesperpixel)];
265         if (!blBitmapFormatImage) {
266                 [pool drain];
267                 return FALSE;
268         }
269         
270         /* setup pointers */
271         if(bitspersample == 16) {
272                 fromf = ibuf->rect_float;
273                 to16   = (unsigned short*)[blBitmapFormatImage bitmapData];
274         }
275         else {
276                 from = (unsigned char*)ibuf->rect;
277                 to   = (unsigned char*)[blBitmapFormatImage bitmapData];
278         }
279
280         /* copy pixel data.  While copying, we flip the image vertically. */
281         for (x = 0; x < ibuf->x; x++) {
282                 for (y = 0; y < ibuf->y; y++) {
283                         from_i = 4*(y*ibuf->x+x);
284                         to_i   = samplesperpixel*((ibuf->y-y-1)*ibuf->x+x);
285                         
286                         if(bitspersample == 16) {
287                                 if (ibuf->profile == IB_PROFILE_SRGB) {
288                                         switch (samplesperpixel) {
289                                                 case 4 /*RGBA*/:
290                                                         to16[to_i] = FTOUSHORT(linearrgb_to_srgb(fromf[from_i]));
291                                                         to16[to_i+1] = FTOUSHORT(linearrgb_to_srgb(fromf[from_i+1]));
292                                                         to16[to_i+2] = FTOUSHORT(linearrgb_to_srgb(fromf[from_i+2]));
293                                                         to16[to_i+3] = FTOUSHORT(fromf[from_i+3]);
294                                                         break;
295                                                 case 3 /*RGB*/:
296                                                         to16[to_i] = FTOUSHORT(linearrgb_to_srgb(fromf[from_i]));
297                                                         to16[to_i+1] = FTOUSHORT(linearrgb_to_srgb(fromf[from_i+1]));
298                                                         to16[to_i+2] = FTOUSHORT(linearrgb_to_srgb(fromf[from_i+2]));
299                                                         break;
300                                                 case 1 /*BW*/:
301                                                         to16[to_i] = FTOUSHORT(linearrgb_to_srgb(fromf[from_i]));
302                                                         break;
303                                         }
304                                 } 
305                                 else {
306                                         for (i = 0; i < samplesperpixel; i++, to_i++, from_i++)
307                                                         to16[to_i] = FTOUSHORT(fromf[from_i]);
308                                 }
309                         }
310                         else {
311                                 /* 8bits per sample*/
312                                 for (i = 0; i < samplesperpixel; i++, to_i++, from_i++)
313                                         to[to_i] = from[from_i];
314                         }
315                 }
316         }
317         
318         /* generate file data */
319         if (IS_tiff(ibuf)) {
320                 dataToWrite = [blBitmapFormatImage TIFFRepresentationUsingCompression:NSTIFFCompressionLZW factor:1.0];
321         }
322         else if (IS_png(ibuf)) {
323                 imageProperties = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], NSImageInterlaced,
324                                                    nil];
325                 dataToWrite = [blBitmapFormatImage representationUsingType:NSPNGFileType properties:imageProperties];
326         }
327         else if (IS_bmp(ibuf)) {
328                 dataToWrite = [blBitmapFormatImage representationUsingType:NSBMPFileType properties:nil];
329         }
330         else {/* JPEG by default */
331                 int quality;
332                 
333                 quality = ibuf->ftype & 0xff;
334                 if (quality <= 0) quality = 90; /* Standard quality if wrong supplied*/
335                 if (quality > 100) quality = 100;
336                 
337                 imageProperties = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:quality], NSImageCompressionFactor,
338                                                    [NSNumber numberWithBool:true], NSImageProgressive, 
339                                                    nil];
340                 dataToWrite = [blBitmapFormatImage representationUsingType:NSJPEGFileType properties:imageProperties];
341         }
342
343         /* Write the file */
344         success = [dataToWrite writeToFile:[NSString stringWithCString:name encoding:NSISOLatin1StringEncoding]
345                                   atomically:YES];
346
347         [blBitmapFormatImage release];
348         [pool drain];
349         
350         return success;
351 }
352
353 #pragma mark format checking functions
354
355 /* Currently, only tiff format is handled, so need to include here function that was previously in tiff.c */
356
357 /**
358  * Checks whether a given memory buffer contains a TIFF file.
359  *
360  * FIXME: Possible memory leak if mem is less than IMB_TIFF_NCB bytes long.
361  *        However, changing this will require up-stream modifications.
362  *
363  * This method uses the format identifiers from:
364  *     http://www.faqs.org/faqs/graphics/fileformats-faq/part4/section-9.html
365  * The first four bytes of big-endian and little-endian TIFF files
366  * respectively are (hex):
367  *      4d 4d 00 2a
368  *      49 49 2a 00
369  * Note that TIFF files on *any* platform can be either big- or little-endian;
370  * it's not platform-specific.
371  *
372  * AFAICT, libtiff doesn't provide a method to do this automatically, and
373  * hence my manual comparison. - Jonathan Merritt (lancelet) 4th Sept 2005.
374  */
375 #define IMB_TIFF_NCB 4          /* number of comparison bytes used */
376 int imb_is_a_tiff(void *mem)
377 {
378         char big_endian[IMB_TIFF_NCB] = { 0x4d, 0x4d, 0x00, 0x2a };
379         char lil_endian[IMB_TIFF_NCB] = { 0x49, 0x49, 0x2a, 0x00 };
380         
381         return ( (memcmp(big_endian, mem, IMB_TIFF_NCB) == 0) ||
382                         (memcmp(lil_endian, mem, IMB_TIFF_NCB) == 0) );
383 }