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