GTK2 no longer supported
[geeqie.git] / src / image_load_psd.c
1 /*
2  * Copyright (C) 20019 - The Geeqie Team
3  *
4  * Author: Colin Clark
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  *
20  * 
21  * Derived from:
22  * 
23  * GdkPixbuf library - PSD image loader
24  *
25  * Copyright (C) 2008 Jan Dudek
26  *
27  * Authors: Jan Dudek <jd@jandudek.com>
28  *
29  * This library is free software; you can redistribute it and/or
30  * modify it under the terms of the GNU Lesser General Public
31  * License as published by the Free Software Foundation; either
32  * version 2 of the License, or (at your option) any later version.
33  *
34  * This library is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
37  * Lesser General Public License for more
38  * You should have received a copy of the GNU Lesser General Public
39  * License along with this library; if not, write to the
40  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
41  * Boston, MA 02111-1307, USA.
42  */
43
44 /*
45  * TODO
46  * - report errors from parse_psd_header
47  * - other color modes (CMYK at least)
48  * - i18n
49  */
50
51 #include "main.h"
52
53 #include "image-load.h"
54 #include "image_load_psd.h"
55
56 typedef struct _ImageLoaderPSD ImageLoaderPSD;
57 struct _ImageLoaderPSD {
58         ImageLoaderBackendCbAreaUpdated area_updated_cb;
59         ImageLoaderBackendCbSize size_cb;
60         ImageLoaderBackendCbAreaPrepared area_prepared_cb;
61         gpointer data;
62         GdkPixbuf *pixbuf;
63         guint requested_width;
64         guint requested_height;
65         gboolean abort;
66 };
67
68 typedef struct
69 {
70         guchar  signature[4];  /* file ID, always "8BPS" */
71         guint16 version;       /* version number, always 1 */
72         guchar  resetved[6];
73         guint16 channels;      /* number of color channels (1-24) */
74         guint32 rows;          /* height of image in pixels (1-30000) */
75         guint32 columns;       /* width of image in pixels (1-30000) */
76         guint16 depth;         /* number of bits per channel (1, 8, 16 or 32) */
77         guint16 color_mode;    /* color mode as defined below */
78 } PsdHeader;
79
80 #define PSD_HEADER_SIZE 26
81
82 typedef enum
83 {
84         PSD_MODE_MONO = 0,
85         PSD_MODE_GRAYSCALE = 1,
86         PSD_MODE_INDEXED = 2,
87         PSD_MODE_RGB = 3,
88         PSD_MODE_CMYK = 4,
89         PSD_MODE_MULTICHANNEL = 7,
90         PSD_MODE_DUOTONE = 8,
91         PSD_MODE_LAB = 9,
92 } PsdColorMode;
93
94 typedef enum
95 {
96         PSD_COMPRESSION_NONE = 0,
97         PSD_COMPRESSION_RLE = 1
98 } PsdCompressionType;
99
100 typedef enum
101 {
102         PSD_STATE_HEADER,
103         PSD_STATE_COLOR_MODE_BLOCK,
104         PSD_STATE_RESOURCES_BLOCK,
105         PSD_STATE_LAYERS_BLOCK,
106         PSD_STATE_COMPRESSION,
107         PSD_STATE_LINES_LENGTHS,
108         PSD_STATE_CHANNEL_DATA,
109         PSD_STATE_DONE
110 } PsdReadState;
111
112 typedef struct
113 {
114         PsdReadState       state;
115         
116         GdkPixbuf*                  pixbuf;
117         gpointer                    user_data;
118
119         guchar*            buffer;
120         guint              bytes_read;
121         guint32            bytes_to_skip;
122         gboolean           bytes_to_skip_known;
123
124         guint32            width;
125         guint32            height;
126         guint16            channels;
127         guint16            depth;
128         guint16            depth_bytes;
129         PsdColorMode       color_mode;
130         PsdCompressionType compression;
131
132         guchar**           ch_bufs;       /* channels buffers */
133         guint              curr_ch;       /* current channel */
134         guint              curr_row;
135         guint              pos;
136         guint16*           lines_lengths;
137         gboolean           finalized;
138 } PsdContext;
139
140
141 static guint16
142 read_uint16 (guchar* buf)
143 {
144         return (buf[0] << 8) | buf[1];
145 }
146
147 static guint32
148 read_uint32 (guchar* buf)
149 {
150         return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
151 }
152
153
154 /*
155  * Parse Psdheader from buffer
156  *
157  * str is expected to be at least PSD_HEADER_SIZE long
158  */
159 static PsdHeader
160 psd_parse_header (guchar* str)
161 {
162         PsdHeader hd;
163         
164         memcpy(hd.signature, str, 4);
165         hd.version = read_uint16(str + 4);
166         hd.channels = read_uint16(str + 12);
167         hd.rows = read_uint32(str + 14);
168         hd.columns = read_uint32(str + 18);
169         hd.depth = read_uint16(str + 22);
170         hd.color_mode = read_uint16(str + 24);
171
172         return hd;
173 }
174
175 /*
176  * Attempts to read bytes_needed bytes from data and stores them in buffer.
177  *
178  * Returns true if there were enough bytes and false otherwise
179  * (which means we need to call feed_buffer again)
180  */
181 static gboolean
182 feed_buffer (guchar*        buffer,
183              guint*         bytes_read,
184              const guchar** data,
185              guint*         size,
186              guint          bytes_needed)
187 {
188         guint how_many = bytes_needed - *bytes_read;
189         if (how_many > *size) {
190                 how_many = *size;
191         }
192         memcpy(buffer + *bytes_read, *data, how_many);
193         *bytes_read += how_many;
194         *data += how_many;
195         *size -= how_many;
196         return (*bytes_read == bytes_needed);
197 }
198
199 /*
200  * Attempts to read size of the block and then skip this block.
201  *
202  * Returns true when finishes consuming block data, otherwise false
203  * (false means we need to call skip_block again)
204  */
205 static gboolean
206 skip_block (PsdContext* context, const guchar** data, guint* size)
207 {
208         if (!context->bytes_to_skip_known) {
209                 context->bytes_read = 0;
210                 if (feed_buffer(context->buffer, &context->bytes_read, data, size, 4)) {
211                         context->bytes_to_skip = read_uint32(context->buffer);
212                         context->bytes_to_skip_known = TRUE;
213                 } else {
214                         return FALSE;
215                 }
216         }
217         if (*size < context->bytes_to_skip) {
218                 *data += *size;
219                 context->bytes_to_skip -= *size;
220                 *size = 0;
221                 return FALSE;
222         } else {
223                 *size -= context->bytes_to_skip;
224                 *data += context->bytes_to_skip;
225                 return TRUE;
226         }
227 }
228
229 /*
230  * Decodes RLE-compressed data
231  */
232 static void
233 decompress_line(const guchar* src, guint line_length, guchar* dest)
234 {
235         guint16 bytes_read = 0;
236         int k;
237         while (bytes_read < line_length) {
238                 gchar byte = src[bytes_read];
239                 ++bytes_read;
240         
241                 if (byte == -128) {
242                         continue;
243                 } else if (byte > -1) {
244                         gint count = byte + 1;
245                 
246                         /* copy next count bytes */
247                         for (k = 0; k < count; ++k) {
248                                 *dest = src[bytes_read];
249                                 ++dest;
250                                 ++bytes_read;
251                         }
252                 } else {
253                         gint count = -byte + 1;
254                 
255                         /* copy next byte count times */
256                         guchar next_byte = src[bytes_read];
257                         ++bytes_read; 
258                         for (k = 0; k < count; ++k) {
259                                 *dest = next_byte;
260                                 ++dest;
261                         }
262                 }
263         }
264 }
265
266 static void
267 reset_context_buffer(PsdContext* ctx)
268 {
269         ctx->bytes_read = 0;
270         ctx->bytes_to_skip = 0;
271         ctx->bytes_to_skip_known = FALSE;
272 }
273
274 static void free_context(PsdContext *ctx)
275 {
276         g_free(ctx->buffer);
277         g_free(ctx->lines_lengths);
278         if (ctx->ch_bufs) {
279                 int i;
280                 for (i = 0; i < ctx->channels; i++) {
281                         g_free(ctx->ch_bufs[i]);
282                 }
283         }
284         g_free(ctx);
285 }
286
287 static gboolean image_loader_psd_load(gpointer loader, const guchar *buf, gsize count, GError **UNUSED(error))
288 {
289         ImageLoaderPSD *ld = (ImageLoaderPSD *) loader;
290         PsdContext* ctx = g_new0(PsdContext, 1);
291         guint i;
292         guint32 j;
293         guint size = count;
294
295         ctx->state = PSD_STATE_HEADER;
296
297         /* we'll allocate larger buffer once we know image size */
298         ctx->buffer = g_malloc(PSD_HEADER_SIZE);
299         reset_context_buffer(ctx);
300
301         ctx->ch_bufs = NULL;
302         ctx->curr_ch = 0;
303         ctx->curr_row = 0;
304         ctx->pos = 0;
305         ctx->lines_lengths = NULL;
306         ctx->finalized = FALSE;
307
308         while (size > 0) {
309                 switch (ctx->state) {
310                         case PSD_STATE_HEADER:
311                                 if (feed_buffer(
312                                                 ctx->buffer, &ctx->bytes_read,
313                                                 &buf, &size, PSD_HEADER_SIZE))
314                                 {
315                                         PsdHeader hd = psd_parse_header(ctx->buffer);
316
317                                         ctx->width = hd.columns;
318                                         ctx->height = hd.rows;
319                                         ctx->channels = hd.channels;
320                                         ctx->depth = hd.depth;
321                                         ctx->depth_bytes = (ctx->depth/8 > 0 ? ctx->depth/8 : 1);
322                                         ctx->color_mode = hd.color_mode;
323                                         
324                                         if (ctx->color_mode != PSD_MODE_RGB
325                                             && ctx->color_mode != PSD_MODE_GRAYSCALE
326                                             && ctx->color_mode != PSD_MODE_CMYK
327                                             && ctx->color_mode != PSD_MODE_DUOTONE
328                                         ) {
329                                                 log_printf("warning: psd - Unsupported color mode\n");
330                                                 free_context(ctx);
331                                                 return FALSE;
332                                         }
333                                         
334                                         if (ctx->depth != 8 && ctx->depth != 16) {
335                                                 log_printf("warning: psd - Unsupported color depth\n");
336                                                 free_context(ctx);
337                                                 return FALSE;
338                                         }
339
340                                         /* we need buffer that can contain one channel data for one
341                                            row in RLE compressed format. 2*width should be enough */
342                                         g_free(ctx->buffer);
343                                         ctx->buffer = g_malloc(ctx->width * 2 * ctx->depth_bytes);
344                                         
345                                         /* this will be needed for RLE decompression */
346                                         ctx->lines_lengths =
347                                                 g_malloc(2 * ctx->channels * ctx->height);
348                                         
349                                         ctx->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB,
350                                                 FALSE, 8, ctx->width, ctx->height);
351
352                                         if (ctx->lines_lengths == NULL || ctx->buffer == NULL ||
353                                                 ctx->pixbuf == NULL)
354                                         {
355                                                 log_printf("warning: Insufficient memory to load PSD image file\n");
356                                                 free_context(ctx);
357                                                 return FALSE;
358                                         }
359                                         
360                                         /* create separate buffers for each channel */
361                                         ctx->ch_bufs = g_malloc(sizeof(guchar*) * ctx->channels);
362                                         for (i = 0; i < ctx->channels; i++) {
363                                                 ctx->ch_bufs[i] =
364                                                         g_malloc(ctx->width*ctx->height*ctx->depth_bytes);
365
366                                                 if (ctx->ch_bufs[i] == NULL) {
367                                                 log_printf("warning: Insufficient memory to load PSD image file\n");
368                                                 free_context(ctx);
369                                                 return FALSE;
370                                                 }       
371                                         }
372
373                                         ctx->state = PSD_STATE_COLOR_MODE_BLOCK;
374                                         reset_context_buffer(ctx);
375                                 }
376                                 break;
377                         case PSD_STATE_COLOR_MODE_BLOCK:
378                                 if (skip_block(ctx, &buf, &size)) {
379                                         ctx->state = PSD_STATE_RESOURCES_BLOCK;
380                                         reset_context_buffer(ctx);
381                                 }
382                                 break;
383                         case PSD_STATE_RESOURCES_BLOCK:
384                                 if (skip_block(ctx, &buf, &size)) {
385                                         ctx->state = PSD_STATE_LAYERS_BLOCK;
386                                         reset_context_buffer(ctx);
387                                 }
388                                 break;
389                         case PSD_STATE_LAYERS_BLOCK:
390                                 if (skip_block(ctx, &buf, &size)) {
391                                         ctx->state = PSD_STATE_COMPRESSION;
392                                         reset_context_buffer(ctx);
393                                 }
394                                 break;
395                         case PSD_STATE_COMPRESSION:
396                                 if (feed_buffer(ctx->buffer, &ctx->bytes_read, &buf, &size, 2))
397                                 {
398                                         ctx->compression = read_uint16(ctx->buffer);
399
400                                         if (ctx->compression == PSD_COMPRESSION_RLE) {
401                                                 ctx->state = PSD_STATE_LINES_LENGTHS;
402                                                 reset_context_buffer(ctx);
403                                         } else if (ctx->compression == PSD_COMPRESSION_NONE) {
404                                                 ctx->state = PSD_STATE_CHANNEL_DATA;
405                                                 reset_context_buffer(ctx);
406                                         } else {
407                                                 log_printf("warning: psd - Unsupported compression type\n");
408                                                 return FALSE;
409                                         }
410                                 }
411                                 break;
412                         case PSD_STATE_LINES_LENGTHS:
413                                 if (feed_buffer(
414                                                 (guchar*) ctx->lines_lengths, &ctx->bytes_read, &buf,
415                                                  &size, 2 * ctx->height * ctx->channels))
416                                 {
417                                         /* convert from different endianness */
418                                         for (i = 0; i < ctx->height * ctx->channels; i++) {
419                                                 ctx->lines_lengths[i] = read_uint16(
420                                                         (guchar*) &ctx->lines_lengths[i]);
421                                         }
422                                         ctx->state = PSD_STATE_CHANNEL_DATA;
423                                         reset_context_buffer(ctx);
424                                 }
425                                 break;
426                         case PSD_STATE_CHANNEL_DATA:
427                                 {
428                                         guint line_length = ctx->width * ctx->depth_bytes;
429                                         if (ctx->compression == PSD_COMPRESSION_RLE) {
430                                                 line_length = ctx->lines_lengths[
431                                                         ctx->curr_ch * ctx->height + ctx->curr_row];
432                                         }
433                                         
434                                         if (feed_buffer(ctx->buffer, &ctx->bytes_read, &buf, &size,
435                                                         line_length))
436                                         {
437                                                 if (ctx->compression == PSD_COMPRESSION_RLE) {
438                                                         decompress_line(ctx->buffer, line_length,
439                                                                 ctx->ch_bufs[ctx->curr_ch] + ctx->pos
440                                                         );
441                                                 } else {
442                                                         memcpy(ctx->ch_bufs[ctx->curr_ch] + ctx->pos,
443                                                                 ctx->buffer, line_length);
444                                                 }
445                                                 
446                                                 ctx->pos += ctx->width * ctx->depth_bytes;
447                                                 ++ctx->curr_row;
448                                         
449                                                 if (ctx->curr_row >= ctx->height) {
450                                                         ++ctx->curr_ch;
451                                                         ctx->curr_row = 0;
452                                                         ctx->pos = 0;
453                                                         if (ctx->curr_ch >= ctx->channels) {
454                                                                 ctx->state = PSD_STATE_DONE;
455                                                         }
456                                                 }
457                                                 
458                                                 reset_context_buffer(ctx);
459                                         }
460                                 }
461                                 break;
462                         case PSD_STATE_DONE:
463                         default:
464                                 size = 0;
465                                 break;
466                 }
467         }
468         
469         if (ctx->state == PSD_STATE_DONE && !ctx->finalized) {
470                 /* convert or copy channel buffers to our GdkPixbuf */
471                 guchar* pixels = gdk_pixbuf_get_pixels(ctx->pixbuf);
472                 guint b = ctx->depth_bytes;
473
474                 if (ctx->color_mode == PSD_MODE_RGB) {
475                         for (i = 0; i < ctx->height; i++) {
476                                 for (j = 0; j < ctx->width; j++) {
477                                         pixels[3*j+0] = ctx->ch_bufs[0][ctx->width*i*b + j*b];
478                                         pixels[3*j+1] = ctx->ch_bufs[1][ctx->width*i*b + j*b];
479                                         pixels[3*j+2] = ctx->ch_bufs[2][ctx->width*i*b + j*b];
480                                 }
481                                 pixels += gdk_pixbuf_get_rowstride(ctx->pixbuf);
482                         }
483                 } else if (ctx->color_mode == PSD_MODE_GRAYSCALE ||
484                            ctx->color_mode == PSD_MODE_DUOTONE)
485                 {
486                         for (i = 0; i < ctx->height; i++) {
487                                 for (j = 0; j < ctx->width; j++) {
488                                         pixels[3*j+0] = pixels[3*j+1] = pixels[3*j+2] =
489                                                 ctx->ch_bufs[0][ctx->width*i*b + j*b];
490                                 }
491                                 pixels += gdk_pixbuf_get_rowstride(ctx->pixbuf);
492                         }
493                 } else if (ctx->color_mode == PSD_MODE_CMYK) {
494                         /* unfortunately, this doesn't work 100% correctly...
495                            CMYK-RGB conversion distorts colors significantly  */
496                 
497                         guchar* pixels = gdk_pixbuf_get_pixels(ctx->pixbuf);
498                         for (i = 0; i < ctx->height; i++) {
499                                 for (j = 0; j < ctx->width; j++) {
500                                         double c = 1.0 -
501                                                 (double) ctx->ch_bufs[0][ctx->width*i + j] / 255.0;
502                                         double m = 1.0 -
503                                                 (double) ctx->ch_bufs[1][ctx->width*i + j] / 255.0;
504                                         double y = 1.0 -
505                                                 (double) ctx->ch_bufs[2][ctx->width*i + j] / 255.0;
506                                         double k = 1.0 -
507                                                 (double) ctx->ch_bufs[3][ctx->width*i + j] / 255.0;
508                                         
509                                         pixels[3*j+0] = (1.0 - (c * (1.0 - k) + k)) * 255.0;
510                                         pixels[3*j+1] = (1.0 - (m * (1.0 - k) + k)) * 255.0;
511                                         pixels[3*j+2] = (1.0 - (y * (1.0 - k) + k)) * 255.0;
512                                 }
513                                 pixels += gdk_pixbuf_get_rowstride(ctx->pixbuf);
514                         }
515                 }
516                 ctx->finalized = TRUE;
517                 ld->pixbuf = ctx->pixbuf;
518                 ld->area_updated_cb(loader, 0, 0, ctx->width, ctx->height, ld->data);
519                 free_context(ctx);
520
521                 return TRUE;
522         }
523
524         free_context(ctx);
525         return FALSE;
526 }
527
528 /* ------- Geeqie ------------ */
529
530 static gpointer image_loader_psd_new(ImageLoaderBackendCbAreaUpdated area_updated_cb, ImageLoaderBackendCbSize size_cb, ImageLoaderBackendCbAreaPrepared area_prepared_cb, gpointer data)
531 {
532         ImageLoaderPSD *loader = g_new0(ImageLoaderPSD, 1);
533         loader->area_updated_cb = area_updated_cb;
534         loader->size_cb = size_cb;
535         loader->area_prepared_cb = area_prepared_cb;
536         loader->data = data;
537         return (gpointer) loader;
538 }
539
540 static void image_loader_psd_set_size(gpointer loader, int width, int height)
541 {
542         ImageLoaderPSD *ld = (ImageLoaderPSD *) loader;
543         ld->requested_width = width;
544         ld->requested_height = height;
545 }
546
547 static GdkPixbuf* image_loader_psd_get_pixbuf(gpointer loader)
548 {
549         ImageLoaderPSD *ld = (ImageLoaderPSD *) loader;
550         return ld->pixbuf;
551 }
552
553 static gchar* image_loader_psd_get_format_name(gpointer UNUSED(loader))
554 {
555         return g_strdup("psd");
556 }
557
558 static gchar** image_loader_psd_get_format_mime_types(gpointer UNUSED(loader))
559 {
560         static gchar *mime[] = {"application/psd", NULL};
561         return g_strdupv(mime);
562 }
563
564 static gboolean image_loader_psd_close(gpointer UNUSED(loader), GError **UNUSED(error))
565 {
566         return TRUE;
567 }
568
569 static void image_loader_psd_abort(gpointer loader)
570 {
571         ImageLoaderPSD *ld = (ImageLoaderPSD *) loader;
572         ld->abort = TRUE;
573 }
574
575 static void image_loader_psd_free(gpointer loader)
576 {
577         ImageLoaderPSD *ld = (ImageLoaderPSD *) loader;
578         if (ld->pixbuf) g_object_unref(ld->pixbuf);
579         g_free(ld);
580 }
581
582 void image_loader_backend_set_psd(ImageLoaderBackend *funcs)
583 {
584         funcs->loader_new = image_loader_psd_new;
585         funcs->set_size = image_loader_psd_set_size;
586         funcs->load = image_loader_psd_load;
587         funcs->write = NULL;
588         funcs->get_pixbuf = image_loader_psd_get_pixbuf;
589         funcs->close = image_loader_psd_close;
590         funcs->abort = image_loader_psd_abort;
591         funcs->free = image_loader_psd_free;
592         funcs->get_format_name = image_loader_psd_get_format_name;
593         funcs->get_format_mime_types = image_loader_psd_get_format_mime_types;
594 }
595 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */