Fix #990: Display full-resolution embedded jpg from CR3 files
[geeqie.git] / src / image-load.cc
1 /*
2  * Copyright (C) 2004 John Ellis
3  * Copyright (C) 2008 - 2016 The Geeqie Team
4  *
5  * Author: John Ellis
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include "main.h"
23 #include "image-load.h"
24 #include "image-load-cr3.h"
25 #include "image-load-gdk.h"
26 #include "image-load-jpeg.h"
27 #include "image-load-tiff.h"
28 #include "image-load-dds.h"
29 #include "image-load-djvu.h"
30 #include "image-load-external.h"
31 #include "image-load-pdf.h"
32 #include "image-load-psd.h"
33 #include "image-load-heif.h"
34 #include "image-load-ffmpegthumbnailer.h"
35 #include "image-load-collection.h"
36 #include "image-load-webp.h"
37 #include "image-load-zxscr.h"
38 #include "image-load-j2k.h"
39 #include "image-load-jpegxl.h"
40 #include "image-load-libraw.h"
41 #include "image-load-svgz.h"
42 #include "misc.h"
43
44 #include "exif.h"
45 #include "filedata.h"
46 #include "ui-fileops.h"
47 #include "gq-marshal.h"
48
49 #include <fcntl.h>
50 #include <sys/mman.h>
51
52 #define IMAGE_LOADER_READ_BUFFER_SIZE_DEFAULT   4096
53 #define IMAGE_LOADER_IDLE_READ_LOOP_COUNT_DEFAULT       1
54
55 /* image loader class */
56
57
58 enum {
59         SIGNAL_AREA_READY = 0,
60         SIGNAL_ERROR,
61         SIGNAL_DONE,
62         SIGNAL_PERCENT,
63         SIGNAL_SIZE,
64         SIGNAL_COUNT
65 };
66
67 static guint signals[SIGNAL_COUNT] = { 0 };
68
69 static void image_loader_init(GTypeInstance *instance, gpointer g_class);
70 static void image_loader_class_init_wrapper(void *data, void *user_data);
71 static void image_loader_class_init(ImageLoaderClass *loader_class);
72 static void image_loader_finalize(GObject *object);
73 static void image_loader_stop(ImageLoader *il);
74
75 GType image_loader_get_type(void)
76 {
77         static GType type = 0;
78         if (type == 0)
79                 {
80                 static const GTypeInfo info = {
81                         sizeof(ImageLoaderClass),
82                         NULL,   /* base_init */
83                         NULL,   /* base_finalize */
84                         (GClassInitFunc)image_loader_class_init_wrapper, /* class_init */
85                         NULL,   /* class_finalize */
86                         NULL,   /* class_data */
87                         sizeof(ImageLoader),
88                         0,      /* n_preallocs */
89                         (GInstanceInitFunc)image_loader_init, /* instance_init */
90                         NULL    /* value_table */
91                         };
92                 type = g_type_register_static(G_TYPE_OBJECT, "ImageLoaderType", &info, 0);
93                 }
94         return type;
95 }
96
97 static void image_loader_init(GTypeInstance *instance, gpointer UNUSED(g_class))
98 {
99         ImageLoader *il = (ImageLoader *)instance;
100
101         il->pixbuf = NULL;
102         il->idle_id = 0;
103         il->idle_priority = G_PRIORITY_DEFAULT_IDLE;
104         il->done = FALSE;
105         il->loader = NULL;
106
107         il->bytes_read = 0;
108         il->bytes_total = 0;
109
110         il->idle_done_id = 0;
111
112         il->idle_read_loop_count = IMAGE_LOADER_IDLE_READ_LOOP_COUNT_DEFAULT;
113         il->read_buffer_size = IMAGE_LOADER_READ_BUFFER_SIZE_DEFAULT;
114         il->mapped_file = NULL;
115         il->preview = IMAGE_LOADER_PREVIEW_NONE;
116
117         il->requested_width = 0;
118         il->requested_height = 0;
119         il->actual_width = 0;
120         il->actual_height = 0;
121         il->shrunk = FALSE;
122
123         il->can_destroy = TRUE;
124
125         il->data_mutex = g_new(GMutex, 1);
126         g_mutex_init(il->data_mutex);
127         il->can_destroy_cond = g_new(GCond, 1);
128         g_cond_init(il->can_destroy_cond);
129
130         DEBUG_1("new image loader %p, bufsize=%" G_GSIZE_FORMAT " idle_loop=%u", (void *)il, il->read_buffer_size, il->idle_read_loop_count);
131 }
132
133 static void image_loader_class_init_wrapper(void *data, void *UNUSED(user_data))
134 {
135         image_loader_class_init(data);
136 }
137
138 static void image_loader_class_init(ImageLoaderClass *loader_class)
139 {
140         GObjectClass *gobject_class = G_OBJECT_CLASS (loader_class);
141
142 //      gobject_class->set_property = image_loader_set_property;
143 //      gobject_class->get_property = image_loader_get_property;
144
145         gobject_class->finalize = image_loader_finalize;
146
147
148         signals[SIGNAL_AREA_READY] =
149                 g_signal_new("area_ready",
150                              G_OBJECT_CLASS_TYPE(gobject_class),
151                              G_SIGNAL_RUN_LAST,
152                              G_STRUCT_OFFSET(ImageLoaderClass, area_ready),
153                              NULL, NULL,
154                              gq_marshal_VOID__INT_INT_INT_INT,
155                              G_TYPE_NONE, 4,
156                              G_TYPE_INT,
157                              G_TYPE_INT,
158                              G_TYPE_INT,
159                              G_TYPE_INT);
160
161         signals[SIGNAL_ERROR] =
162                 g_signal_new("error",
163                              G_OBJECT_CLASS_TYPE(gobject_class),
164                              G_SIGNAL_RUN_LAST,
165                              G_STRUCT_OFFSET(ImageLoaderClass, error),
166                              NULL, NULL,
167                              g_cclosure_marshal_VOID__VOID,
168                              G_TYPE_NONE, 0);
169
170         signals[SIGNAL_DONE] =
171                 g_signal_new("done",
172                              G_OBJECT_CLASS_TYPE(gobject_class),
173                              G_SIGNAL_RUN_LAST,
174                              G_STRUCT_OFFSET(ImageLoaderClass, done),
175                              NULL, NULL,
176                              g_cclosure_marshal_VOID__VOID,
177                              G_TYPE_NONE, 0);
178
179         signals[SIGNAL_PERCENT] =
180                 g_signal_new("percent",
181                              G_OBJECT_CLASS_TYPE(gobject_class),
182                              G_SIGNAL_RUN_LAST,
183                              G_STRUCT_OFFSET(ImageLoaderClass, percent),
184                              NULL, NULL,
185                              g_cclosure_marshal_VOID__DOUBLE,
186                              G_TYPE_NONE, 1,
187                              G_TYPE_DOUBLE);
188
189         signals[SIGNAL_SIZE] =
190                 g_signal_new("size_prepared",
191                              G_OBJECT_CLASS_TYPE(gobject_class),
192                              G_SIGNAL_RUN_LAST,
193                              G_STRUCT_OFFSET(ImageLoaderClass, area_ready),
194                              NULL, NULL,
195                              gq_marshal_VOID__INT_INT,
196                              G_TYPE_NONE, 2,
197                              G_TYPE_INT,
198                              G_TYPE_INT);
199
200 }
201
202 static void image_loader_finalize(GObject *object)
203 {
204         ImageLoader *il = (ImageLoader *)object;
205
206         image_loader_stop(il);
207
208         if (il->error) DEBUG_1("%s", image_loader_get_error(il));
209
210         DEBUG_1("freeing image loader %p bytes_read=%" G_GSIZE_FORMAT, (void *)il, il->bytes_read);
211
212         if (il->idle_done_id)
213                 {
214                 g_source_remove(il->idle_done_id);
215                 il->idle_done_id = 0;
216                 }
217
218         while (g_source_remove_by_user_data(il))
219                 {
220                 DEBUG_2("pending signals detected");
221                 }
222
223         while (il->area_param_list)
224                 {
225                 DEBUG_1("pending area_ready signals detected");
226                 while (g_source_remove_by_user_data(il->area_param_list->data)) {}
227                 g_free(il->area_param_list->data);
228                 il->area_param_list = g_list_delete_link(il->area_param_list, il->area_param_list);
229                 }
230
231         while (il->area_param_delayed_list)
232                 {
233                 g_free(il->area_param_delayed_list->data);
234                 il->area_param_delayed_list = g_list_delete_link(il->area_param_delayed_list, il->area_param_delayed_list);
235                 }
236
237         if (il->pixbuf) g_object_unref(il->pixbuf);
238
239         if (il->error) g_error_free(il->error);
240
241         file_data_unref(il->fd);
242
243         g_mutex_clear(il->data_mutex);
244         g_free(il->data_mutex);
245         g_cond_clear(il->can_destroy_cond);
246         g_free(il->can_destroy_cond);
247 }
248
249 void image_loader_free(ImageLoader *il)
250 {
251         if (!il) return;
252         g_object_unref(G_OBJECT(il));
253 }
254
255
256 ImageLoader *image_loader_new(FileData *fd)
257 {
258         ImageLoader *il;
259
260         if (!fd) return NULL;
261
262         il = (ImageLoader *) g_object_new(TYPE_IMAGE_LOADER, NULL);
263
264         il->fd = file_data_ref(fd);
265
266         return il;
267 }
268
269 /**************************************************************************************/
270 /* send signals via idle calbacks - the callback are executed in the main thread */
271
272 typedef struct _ImageLoaderAreaParam ImageLoaderAreaParam;
273 struct _ImageLoaderAreaParam {
274         ImageLoader *il;
275         guint x;
276         guint y;
277         guint w;
278         guint h;
279 };
280
281
282 static gboolean image_loader_emit_area_ready_cb(gpointer data)
283 {
284         ImageLoaderAreaParam *par = data;
285         ImageLoader *il = par->il;
286         guint x, y, w, h;
287         g_mutex_lock(il->data_mutex);
288         il->area_param_list = g_list_remove(il->area_param_list, par);
289         x = par->x;
290         y = par->y;
291         w = par->w;
292         h = par->h;
293         g_free(par);
294         g_mutex_unlock(il->data_mutex);
295
296         g_signal_emit(il, signals[SIGNAL_AREA_READY], 0, x, y, w, h);
297
298         return FALSE;
299 }
300
301 static gboolean image_loader_emit_done_cb(gpointer data)
302 {
303         ImageLoader *il = data;
304         g_signal_emit(il, signals[SIGNAL_DONE], 0);
305         return FALSE;
306 }
307
308 static gboolean image_loader_emit_error_cb(gpointer data)
309 {
310         ImageLoader *il = data;
311         g_signal_emit(il, signals[SIGNAL_ERROR], 0);
312         return FALSE;
313 }
314
315 static gboolean image_loader_emit_percent_cb(gpointer data)
316 {
317         ImageLoader *il = data;
318         g_signal_emit(il, signals[SIGNAL_PERCENT], 0, image_loader_get_percent(il));
319         return FALSE;
320 }
321
322 static gboolean image_loader_emit_size_cb(gpointer data)
323 {
324         gint width, height;
325         ImageLoader *il = data;
326         g_mutex_lock(il->data_mutex);
327         width = il->actual_width;
328         height = il->actual_height;
329         g_mutex_unlock(il->data_mutex);
330         g_signal_emit(il, signals[SIGNAL_SIZE], 0, width, height);
331         return FALSE;
332 }
333
334
335 /* DONE and ERROR are emitted only once, thus they can have normal priority
336    PERCENT and AREA_READY should be processed ASAP
337 */
338
339 static void image_loader_emit_done(ImageLoader *il)
340 {
341         g_idle_add_full(il->idle_priority, image_loader_emit_done_cb, il, NULL);
342 }
343
344 static void image_loader_emit_error(ImageLoader *il)
345 {
346         g_idle_add_full(il->idle_priority, image_loader_emit_error_cb, il, NULL);
347 }
348
349 static void image_loader_emit_percent(ImageLoader *il)
350 {
351         g_idle_add_full(G_PRIORITY_HIGH, image_loader_emit_percent_cb, il, NULL);
352 }
353
354 static void image_loader_emit_size(ImageLoader *il)
355 {
356         g_idle_add_full(G_PRIORITY_HIGH, image_loader_emit_size_cb, il, NULL);
357 }
358
359 static ImageLoaderAreaParam *image_loader_queue_area_ready(ImageLoader *il, GList **list, guint x, guint y, guint w, guint h)
360 {
361         if (*list)
362                 {
363                 ImageLoaderAreaParam *prev_par = (*list)->data;
364                 if (prev_par->x == x && prev_par->w == w &&
365                     prev_par->y + prev_par->h == y)
366                         {
367                         /* we can merge the notifications */
368                         prev_par->h += h;
369                         return NULL;
370                         }
371                 if (prev_par->x == x && prev_par->w == w &&
372                     y + h == prev_par->y)
373                         {
374                         /* we can merge the notifications */
375                         prev_par->h += h;
376                         prev_par->y = y;
377                         return NULL;
378                         }
379                 if (prev_par->y == y && prev_par->h == h &&
380                     prev_par->x + prev_par->w == x)
381                         {
382                         /* we can merge the notifications */
383                         prev_par->w += w;
384                         return NULL;
385                         }
386                 if (prev_par->y == y && prev_par->h == h &&
387                     x + w == prev_par->x)
388                         {
389                         /* we can merge the notifications */
390                         prev_par->w += w;
391                         prev_par->x = x;
392                         return NULL;
393                         }
394                 }
395
396         ImageLoaderAreaParam *par = g_new0(ImageLoaderAreaParam, 1);
397         par->il = il;
398         par->x = x;
399         par->y = y;
400         par->w = w;
401         par->h = h;
402
403         *list = g_list_prepend(*list, par);
404         return par;
405 }
406
407 /* this function expects that il->data_mutex is locked by caller */
408 static void image_loader_emit_area_ready(ImageLoader *il, guint x, guint y, guint w, guint h)
409 {
410         ImageLoaderAreaParam *par = image_loader_queue_area_ready(il, &il->area_param_list, x, y, w, h);
411
412         if (par)
413                 {
414                 g_idle_add_full(G_PRIORITY_HIGH, image_loader_emit_area_ready_cb, par, NULL);
415                 }
416 }
417
418 /**************************************************************************************/
419 /* the following functions may be executed in separate thread */
420
421 /* this function expects that il->data_mutex is locked by caller */
422 static void image_loader_queue_delayed_area_ready(ImageLoader *il, guint x, guint y, guint w, guint h)
423 {
424         image_loader_queue_area_ready(il, &il->area_param_delayed_list, x, y, w, h);
425 }
426
427
428
429 static gboolean image_loader_get_stopping(ImageLoader *il)
430 {
431         gboolean ret;
432         if (!il) return FALSE;
433
434         g_mutex_lock(il->data_mutex);
435         ret = il->stopping;
436         g_mutex_unlock(il->data_mutex);
437
438         return ret;
439 }
440
441
442 static void image_loader_sync_pixbuf(ImageLoader *il)
443 {
444         GdkPixbuf *pb;
445
446         g_mutex_lock(il->data_mutex);
447
448         if (!il->loader)
449                 {
450                 g_mutex_unlock(il->data_mutex);
451                 return;
452                 }
453
454         pb = il->backend.get_pixbuf(il->loader);
455
456         if (pb == il->pixbuf)
457                 {
458                 g_mutex_unlock(il->data_mutex);
459                 return;
460                 }
461
462         if (g_ascii_strcasecmp(".jps", il->fd->extension) == 0)
463                 {
464                 g_object_set_data(G_OBJECT(pb), "stereo_data", GINT_TO_POINTER(STEREO_PIXBUF_CROSS));
465                 }
466
467         if (il->pixbuf) g_object_unref(il->pixbuf);
468
469         il->pixbuf = pb;
470         if (il->pixbuf) g_object_ref(il->pixbuf);
471
472         g_mutex_unlock(il->data_mutex);
473 }
474
475 static void image_loader_area_updated_cb(gpointer UNUSED(loader),
476                                  guint x, guint y, guint w, guint h,
477                                  gpointer data)
478 {
479         ImageLoader *il = data;
480
481         if (!image_loader_get_pixbuf(il))
482                 {
483                 image_loader_sync_pixbuf(il);
484                 if (!image_loader_get_pixbuf(il))
485                         {
486                         log_printf("critical: area_ready signal with NULL pixbuf (out of mem?)\n");
487                         }
488                 }
489
490         g_mutex_lock(il->data_mutex);
491         if (il->delay_area_ready)
492                 image_loader_queue_delayed_area_ready(il, x, y, w, h);
493         else
494                 image_loader_emit_area_ready(il, x, y, w, h);
495
496         if (il->stopping) il->backend.abort(il->loader);
497
498         g_mutex_unlock(il->data_mutex);
499 }
500
501 static void image_loader_area_prepared_cb(gpointer loader, gpointer data)
502 {
503         ImageLoader *il = data;
504         GdkPixbuf *pb;
505         guchar *pix;
506         size_t h, rs;
507
508         /* a workaround for
509            https://bugzilla.gnome.org/show_bug.cgi?id=547669
510            https://bugzilla.gnome.org/show_bug.cgi?id=589334
511         */
512         gchar *format = il->backend.get_format_name(loader);
513         if (strcmp(format, "svg") == 0 ||
514             strcmp(format, "xpm") == 0)
515                 {
516                 g_free(format);
517                 return;
518                 }
519
520         g_free(format);
521
522         pb = il->backend.get_pixbuf(loader);
523
524         h = gdk_pixbuf_get_height(pb);
525         rs = gdk_pixbuf_get_rowstride(pb);
526         pix = gdk_pixbuf_get_pixels(pb);
527
528         memset(pix, 0, rs * h); /*this should be faster than pixbuf_fill */
529
530 }
531
532 static void image_loader_size_cb(gpointer loader,
533                                  gint width, gint height, gpointer data)
534 {
535         ImageLoader *il = data;
536         gchar **mime_types;
537         gboolean scale = FALSE;
538         gint n;
539
540         g_mutex_lock(il->data_mutex);
541         il->actual_width = width;
542         il->actual_height = height;
543         if (il->requested_width < 1 || il->requested_height < 1)
544                 {
545                 g_mutex_unlock(il->data_mutex);
546                 image_loader_emit_size(il);
547                 return;
548                 }
549         g_mutex_unlock(il->data_mutex);
550
551 #ifdef HAVE_FFMPEGTHUMBNAILER
552         if (il->fd->format_class == FORMAT_CLASS_VIDEO)
553                 scale = TRUE;
554 #endif
555         mime_types = il->backend.get_format_mime_types(loader);
556         n = 0;
557         while (mime_types[n] && !scale)
558                 {
559                 if (strstr(mime_types[n], "jpeg")) scale = TRUE;
560                 n++;
561                 }
562         g_strfreev(mime_types);
563
564         if (!scale)
565                 {
566                 image_loader_emit_size(il);
567                 return;
568                 }
569
570         g_mutex_lock(il->data_mutex);
571
572         gint nw, nh;
573         if (width > il->requested_width || height > il->requested_height)
574                 {
575
576                 if (((gdouble)il->requested_width / width) < ((gdouble)il->requested_height / height))
577                         {
578                         nw = il->requested_width;
579                         nh = (gdouble)nw / width * height;
580                         if (nh < 1) nh = 1;
581                         }
582                 else
583                         {
584                         nh = il->requested_height;
585                         nw = (gdouble)nh / height * width;
586                         if (nw < 1) nw = 1;
587                         }
588
589                 il->actual_width = nw;
590                 il->actual_height = nh;
591                 il->backend.set_size(loader, nw, nh);
592                 il->shrunk = TRUE;
593                 }
594
595         g_mutex_unlock(il->data_mutex);
596         image_loader_emit_size(il);
597 }
598
599 static void image_loader_stop_loader(ImageLoader *il)
600 {
601         if (!il) return;
602
603         if (il->loader)
604                 {
605                 /* some loaders do not have a pixbuf till close, order is important here */
606                 il->backend.close(il->loader, il->error ? NULL : &il->error); /* we are interested in the first error only */
607                 image_loader_sync_pixbuf(il);
608                 il->backend.free(il->loader);
609                 il->loader = NULL;
610                 }
611         g_mutex_lock(il->data_mutex);
612         il->done = TRUE;
613         g_mutex_unlock(il->data_mutex);
614 }
615
616 static void image_loader_setup_loader(ImageLoader *il)
617 {
618 #if defined HAVE_TIFF || defined HAVE_PDF || defined HAVE_HEIF || defined HAVE_DJVU
619         gchar *format;
620 #endif
621
622         gint external_preview = 1;
623
624         g_mutex_lock(il->data_mutex);
625
626         if (options->external_preview.enable)
627                 {
628                 gchar *cmd_line;
629                 gchar *tilde_filename;
630
631                 tilde_filename = expand_tilde(options->external_preview.select);
632
633                 cmd_line = g_strdup_printf("\"%s\" \"%s\"" , tilde_filename, il->fd->path);
634
635                 external_preview = runcmd(cmd_line);
636                 g_free(cmd_line);
637                 g_free(tilde_filename);
638                 }
639
640         if (external_preview == 0)
641                 {
642                 DEBUG_1("Using custom external loader");
643                 image_loader_backend_set_external(&il->backend);
644                 }
645         else
646
647 #ifdef HAVE_FFMPEGTHUMBNAILER
648         if (il->fd->format_class == FORMAT_CLASS_VIDEO)
649                 {
650                 DEBUG_1("Using custom ffmpegthumbnailer loader");
651                 image_loader_backend_set_ft(&il->backend);
652                 }
653         else
654 #endif
655 #ifdef HAVE_PDF
656         if (il->bytes_total >= 4 &&
657             (memcmp(il->mapped_file + 0, "%PDF", 4) == 0))
658                 {
659                 DEBUG_1("Using custom pdf loader");
660                 image_loader_backend_set_pdf(&il->backend);
661                 }
662         else
663 #endif
664 #ifdef HAVE_HEIF
665         if (il->bytes_total >= 12 &&
666                 ((memcmp(il->mapped_file + 4, "ftypheic", 8) == 0) ||
667                 (memcmp(il->mapped_file + 4, "ftypmsf1", 8) == 0) ||
668                 (memcmp(il->mapped_file + 4, "ftypmif1", 8) == 0) ||
669                 (memcmp(il->mapped_file + 4, "ftypavif", 8) == 0)))
670                 {
671                 DEBUG_1("Using custom heif loader");
672                 image_loader_backend_set_heif(&il->backend);
673                 }
674         else
675 #endif
676 #ifdef HAVE_WEBP
677         if (il->bytes_total >= 12 &&
678                 (memcmp(il->mapped_file, "RIFF", 4) == 0) &&
679                 (memcmp(il->mapped_file + 8, "WEBP", 4) == 0))
680                 {
681                 DEBUG_1("Using custom webp loader");
682                 image_loader_backend_set_webp(&il->backend);
683                 }
684         else
685 #endif
686 #ifdef HAVE_DJVU
687         if (il->bytes_total >= 16 &&
688                 (memcmp(il->mapped_file, "AT&TFORM", 8) == 0) &&
689                 (memcmp(il->mapped_file + 12, "DJV", 3) == 0))
690                 {
691                 DEBUG_1("Using custom djvu loader");
692                 image_loader_backend_set_djvu(&il->backend);
693                 }
694         else
695 #endif
696 #ifdef HAVE_JPEG
697         if (il->bytes_total >= 2 && il->mapped_file[0] == 0xff && il->mapped_file[1] == 0xd8)
698                 {
699                 DEBUG_1("Using custom jpeg loader");
700                 image_loader_backend_set_jpeg(&il->backend);
701                 }
702 #ifndef HAVE_RAW
703         else
704         if (il->bytes_total >= 11 &&
705                 (memcmp(il->mapped_file + 4, "ftypcrx", 7) == 0) &&
706                 (memcmp(il->mapped_file + 64, "CanonCR3", 8) == 0))
707                 {
708                 DEBUG_1("Using custom cr3 loader");
709                 image_loader_backend_set_cr3(&il->backend);
710                 }
711 #endif
712         else
713 #endif
714 #ifdef HAVE_TIFF
715         if (il->bytes_total >= 10 &&
716             (memcmp(il->mapped_file, "MM\0*", 4) == 0 ||
717              memcmp(il->mapped_file, "MM\0+\0\x08\0\0", 8) == 0 ||
718              memcmp(il->mapped_file, "II+\0\x08\0\0\0", 8) == 0 ||
719              memcmp(il->mapped_file, "II*\0", 4) == 0))
720                 {
721                 DEBUG_1("Using custom tiff loader");
722                 image_loader_backend_set_tiff(&il->backend);
723                 }
724         else
725 #endif
726         if (il->bytes_total >= 3 && il->mapped_file[0] == 0x44 && il->mapped_file[1] == 0x44 && il->mapped_file[2] == 0x53)
727                 {
728                 DEBUG_1("Using dds loader");
729                 image_loader_backend_set_dds(&il->backend);
730                 }
731         else
732         if (il->bytes_total >= 6 &&
733                 (memcmp(il->mapped_file, "8BPS\0\x01", 6) == 0))
734                 {
735                 DEBUG_1("Using custom psd loader");
736                 image_loader_backend_set_psd(&il->backend);
737                 }
738         else
739 #ifdef HAVE_J2K
740         if (il->bytes_total >= 12 &&
741                 (memcmp(il->mapped_file, "\0\0\0\x0CjP\x20\x20\x0D\x0A\x87\x0A", 12) == 0))
742                 {
743                 DEBUG_1("Using custom j2k loader");
744                 image_loader_backend_set_j2k(&il->backend);
745                 }
746         else
747 #endif
748 #ifdef HAVE_JPEGXL
749         if (il->bytes_total >= 12 &&
750                 (memcmp(il->mapped_file, "\0\0\0\x0C\x4A\x58\x4C\x20\x0D\x0A\x87\x0A", 12) == 0))
751                 {
752                 DEBUG_1("Using custom jpeg xl loader");
753                 image_loader_backend_set_jpegxl(&il->backend);
754                 }
755         else
756         if (il->bytes_total >= 2 &&
757                 (memcmp(il->mapped_file, "\xFF\x0A", 2) == 0))
758                 {
759                 DEBUG_1("Using custom jpeg xl loader");
760                 image_loader_backend_set_jpegxl(&il->backend);
761                 }
762         else
763 #endif
764         if ((il->bytes_total == 6144 || il->bytes_total == 6912) &&
765                 (file_extension_match(il->fd->path, ".scr")))
766                 {
767                 DEBUG_1("Using custom zxscr loader");
768                 image_loader_backend_set_zxscr(&il->backend);
769                 }
770         else
771         if (il->fd->format_class == FORMAT_CLASS_COLLECTION)
772                 {
773                 DEBUG_1("Using custom collection loader");
774                 image_loader_backend_set_collection(&il->backend);
775                 }
776         else
777         if (g_strcmp0(strrchr(il->fd->path, '.'), ".svgz") == 0)
778                 {
779                 DEBUG_1("Using custom svgz loader");
780                 image_loader_backend_set_svgz(&il->backend);
781                 }
782         else
783                 image_loader_backend_set_default(&il->backend);
784
785         il->loader = il->backend.loader_new(image_loader_area_updated_cb, image_loader_size_cb, image_loader_area_prepared_cb, il);
786
787 #ifdef HAVE_TIFF
788         format = il->backend.get_format_name(il->loader);
789         if (g_strcmp0(format, "tiff") == 0)
790                 {
791                 il->backend.set_page_num(il->loader, il->fd->page_num);
792                 }
793         g_free(format);
794 #endif
795
796 #ifdef HAVE_PDF
797         format = il->backend.get_format_name(il->loader);
798         if (g_strcmp0(format, "pdf") == 0)
799                 {
800                 il->backend.set_page_num(il->loader, il->fd->page_num);
801                 }
802         g_free(format);
803 #endif
804
805 #ifdef HAVE_HEIF
806         format = il->backend.get_format_name(il->loader);
807         if (g_strcmp0(format, "heif") == 0)
808                 {
809                 il->backend.set_page_num(il->loader, il->fd->page_num);
810                 }
811         g_free(format);
812 #endif
813
814 #ifdef HAVE_DJVU
815         format = il->backend.get_format_name(il->loader);
816         if (g_strcmp0(format, "djvu") == 0)
817                 {
818                 il->backend.set_page_num(il->loader, il->fd->page_num);
819                 }
820         g_free(format);
821 #endif
822
823         il->fd->format_name = il->backend.get_format_name(il->loader);
824
825         g_mutex_unlock(il->data_mutex);
826 }
827
828
829 static void image_loader_done(ImageLoader *il)
830 {
831         image_loader_stop_loader(il);
832
833         image_loader_emit_done(il);
834 }
835
836 static void image_loader_error(ImageLoader *il)
837 {
838         image_loader_stop_loader(il);
839
840         DEBUG_1("pixbuf_loader reported load error for: %s", il->fd->path);
841
842         image_loader_emit_error(il);
843 }
844
845 static gboolean image_loader_continue(ImageLoader *il)
846 {
847         gint b;
848         gint c;
849
850         if (!il) return FALSE;
851
852         c = il->idle_read_loop_count ? il->idle_read_loop_count : 1;
853         while (c > 0 && !image_loader_get_stopping(il))
854                 {
855                 b = MIN(il->read_buffer_size, il->bytes_total - il->bytes_read);
856
857                 if (b == 0)
858                         {
859                         image_loader_done(il);
860                         return FALSE;
861                         }
862
863                 if (b < 0 || (b > 0 && !il->backend.write(il->loader, il->mapped_file + il->bytes_read, b, &il->error)))
864                         {
865                         image_loader_error(il);
866                         return FALSE;
867                         }
868
869                 il->bytes_read += b;
870
871                 c--;
872                 }
873
874         if (il->bytes_total > 0)
875                 {
876                 image_loader_emit_percent(il);
877                 }
878
879         return TRUE;
880 }
881
882 static gboolean image_loader_begin(ImageLoader *il)
883 {
884 #if defined HAVE_TIFF || defined HAVE_PDF || defined HAVE_HEIF || defined HAVE_DJVU
885         gchar *format;
886 #endif
887         gssize b;
888
889         if (il->pixbuf) return FALSE;
890
891         b = MIN(il->read_buffer_size, il->bytes_total - il->bytes_read);
892         if (b < 1) return FALSE;
893
894         image_loader_setup_loader(il);
895
896         g_assert(il->bytes_read == 0);
897         if (il->backend.load) {
898                 b = il->bytes_total;
899                 if (!il->backend.load(il->loader, il->mapped_file, b, &il->error))
900                         {
901                         image_loader_stop_loader(il);
902                         return FALSE;
903                         }
904         }
905         else if (!il->backend.write(il->loader, il->mapped_file, b, &il->error))
906                 {
907                 image_loader_stop_loader(il);
908                 return FALSE;
909                 }
910
911 #ifdef HAVE_PDF
912         format = il->backend.get_format_name(il->loader);
913         if (g_strcmp0(format, "pdf") == 0)
914                 {
915                 gint i = il->backend.get_page_total(il->loader);
916                 file_data_set_page_total(il->fd, i);
917                 }
918         g_free(format);
919 #endif
920 #ifdef HAVE_HEIF
921         format = il->backend.get_format_name(il->loader);
922         if (g_strcmp0(format, "heif") == 0)
923                 {
924                 gint i = il->backend.get_page_total(il->loader);
925                 file_data_set_page_total(il->fd, i);
926                 }
927         g_free(format);
928 #endif
929 #ifdef HAVE_DJVU
930         format = il->backend.get_format_name(il->loader);
931         if (g_strcmp0(format, "djvu") == 0)
932                 {
933                 gint i = il->backend.get_page_total(il->loader);
934                 file_data_set_page_total(il->fd, i);
935                 }
936         g_free(format);
937 #endif
938 #ifdef HAVE_TIFF
939         format = il->backend.get_format_name(il->loader);
940         if (g_strcmp0(format, "tiff") == 0)
941                 {
942                 gint i = il->backend.get_page_total(il->loader);
943                 file_data_set_page_total(il->fd, i);
944                 }
945         g_free(format);
946 #endif
947
948         il->bytes_read += b;
949
950         /* read until size is known */
951         while (il->loader && !il->backend.get_pixbuf(il->loader) && b > 0 && !image_loader_get_stopping(il))
952                 {
953                 b = MIN(il->read_buffer_size, il->bytes_total - il->bytes_read);
954                 if (b < 0 || (b > 0 && !il->backend.write(il->loader, il->mapped_file + il->bytes_read, b, &il->error)))
955                         {
956                         image_loader_stop_loader(il);
957                         return FALSE;
958                         }
959                 il->bytes_read += b;
960                 }
961         if (!il->pixbuf) image_loader_sync_pixbuf(il);
962
963         if (il->bytes_read == il->bytes_total || b < 1)
964                 {
965                 /* done, handle (broken) loaders that do not have pixbuf till close */
966                 image_loader_stop_loader(il);
967
968                 if (!il->pixbuf) return FALSE;
969
970                 image_loader_done(il);
971                 return TRUE;
972                 }
973
974         if (!il->pixbuf)
975                 {
976                 image_loader_stop_loader(il);
977                 return FALSE;
978                 }
979
980         return TRUE;
981 }
982
983 /**************************************************************************************/
984 /* the following functions are always executed in the main thread */
985
986
987 static gboolean image_loader_setup_source(ImageLoader *il)
988 {
989         struct stat st;
990         gchar *pathl;
991
992         if (!il || il->loader || il->mapped_file) return FALSE;
993
994         il->mapped_file = NULL;
995
996         if (il->fd)
997                 {
998                 ExifData *exif = exif_read_fd(il->fd);
999
1000                 if (options->thumbnails.use_exif)
1001                         {
1002                         il->mapped_file = exif_get_preview(exif, (guint *)&il->bytes_total, il->requested_width, il->requested_height);
1003
1004                         if (il->mapped_file)
1005                                 {
1006                                 il->preview = IMAGE_LOADER_PREVIEW_EXIF;
1007                                 }
1008                         }
1009                 else
1010                         {
1011                         il->mapped_file = libraw_get_preview(il, (guint *)&il->bytes_total);
1012
1013                         if (il->mapped_file)
1014                                 {
1015                                 /* Both exiv2 and libraw sometimes return a pointer to a file
1016                                  * section that is not a jpeg */
1017                                 if (!(il->mapped_file[0] == 0xFF && il->mapped_file[1] == 0xD8))
1018                                         {
1019                                         il->mapped_file = NULL;
1020                                         }
1021                                 else
1022                                         {
1023                                         il->preview = IMAGE_LOADER_PREVIEW_LIBRAW;
1024                                         }
1025                                 }
1026                         }
1027
1028                 /* If libraw does not find a thumbnail, try exiv2 */
1029                 if (!il->mapped_file)
1030                         {
1031                         il->mapped_file = exif_get_preview(exif, (guint *)&il->bytes_total, 0, 0); /* get the largest available preview image or NULL for normal images*/
1032
1033                         if (il->mapped_file)
1034                                 {
1035                                 /* Both exiv2 and libraw sometimes return a pointer to a file
1036                                  * section that is not a jpeg */
1037                                 if (!(il->mapped_file[0] == 0xFF && il->mapped_file[1] == 0xD8))
1038                                         {
1039                                         il->mapped_file = NULL;
1040                                         }
1041                                 else
1042                                         {
1043                                         il->preview = IMAGE_LOADER_PREVIEW_EXIF;
1044                                         }
1045                                 }
1046                         }
1047
1048                 if (il->mapped_file)
1049                         {
1050                         DEBUG_1("Usable reduced size (preview) image loaded from file %s", il->fd->path);
1051                         }
1052                 exif_free_fd(il->fd, exif);
1053                 }
1054
1055
1056         if (!il->mapped_file)
1057                 {
1058                 /* normal file */
1059                 gint load_fd;
1060
1061                 pathl = path_from_utf8(il->fd->path);
1062                 load_fd = open(pathl, O_RDONLY | O_NONBLOCK);
1063                 g_free(pathl);
1064                 if (load_fd == -1) return FALSE;
1065
1066                 if (fstat(load_fd, &st) == 0)
1067                         {
1068                         il->bytes_total = st.st_size;
1069                         }
1070                 else
1071                         {
1072                         close(load_fd);
1073                         return FALSE;
1074                         }
1075
1076                 il->mapped_file = mmap(0, il->bytes_total, PROT_READ|PROT_WRITE, MAP_PRIVATE, load_fd, 0);
1077                 close(load_fd);
1078                 if (il->mapped_file == MAP_FAILED)
1079                         {
1080                         il->mapped_file = 0;
1081                         return FALSE;
1082                         }
1083                 il->preview = IMAGE_LOADER_PREVIEW_NONE;
1084                 }
1085
1086         return TRUE;
1087 }
1088
1089 static void image_loader_stop_source(ImageLoader *il)
1090 {
1091         if (!il) return;
1092
1093         if (il->mapped_file)
1094                 {
1095                 if (il->preview == IMAGE_LOADER_PREVIEW_EXIF)
1096                         {
1097                         exif_free_preview(il->mapped_file);
1098                         }
1099                 else if (il->preview == IMAGE_LOADER_PREVIEW_LIBRAW)
1100                         {
1101                         libraw_free_preview(il->mapped_file);
1102                         }
1103                 else
1104                         {
1105                         munmap(il->mapped_file, il->bytes_total);
1106                         }
1107                 il->mapped_file = NULL;
1108                 }
1109 }
1110
1111 static void image_loader_stop(ImageLoader *il)
1112 {
1113         if (!il) return;
1114
1115         if (il->idle_id)
1116                 {
1117                 g_source_remove(il->idle_id);
1118                 il->idle_id = 0;
1119                 }
1120
1121         if (il->thread)
1122                 {
1123                 /* stop loader in the other thread */
1124                 g_mutex_lock(il->data_mutex);
1125                 il->stopping = TRUE;
1126                 while (!il->can_destroy) g_cond_wait(il->can_destroy_cond, il->data_mutex);
1127                 g_mutex_unlock(il->data_mutex);
1128                 }
1129
1130         image_loader_stop_loader(il);
1131         image_loader_stop_source(il);
1132
1133 }
1134
1135 void image_loader_delay_area_ready(ImageLoader *il, gboolean enable)
1136 {
1137         g_mutex_lock(il->data_mutex);
1138         il->delay_area_ready = enable;
1139         if (!enable)
1140                 {
1141                 /* send delayed */
1142                 GList *list, *work;
1143                 list = g_list_reverse(il->area_param_delayed_list);
1144                 il->area_param_delayed_list = NULL;
1145                 g_mutex_unlock(il->data_mutex);
1146
1147                 work = list;
1148
1149                 while (work)
1150                         {
1151                         ImageLoaderAreaParam *par = work->data;
1152                         work = work->next;
1153
1154                         g_signal_emit(il, signals[SIGNAL_AREA_READY], 0, par->x, par->y, par->w, par->h);
1155                         g_free(par);
1156                         }
1157                 g_list_free(list);
1158                 }
1159         else
1160                 {
1161                 /* just unlock */
1162                 g_mutex_unlock(il->data_mutex);
1163                 }
1164 }
1165
1166
1167 /**************************************************************************************/
1168 /* execution via idle calls */
1169
1170 static gboolean image_loader_idle_cb(gpointer data)
1171 {
1172         gboolean ret = FALSE;
1173         ImageLoader *il = data;
1174
1175         if (il->idle_id)
1176                 {
1177                 ret = image_loader_continue(il);
1178                 }
1179
1180         if (!ret)
1181                 {
1182                 image_loader_stop_source(il);
1183                 }
1184
1185         return ret;
1186 }
1187
1188
1189 static gboolean image_loader_start_idle(ImageLoader *il)
1190 {
1191         gboolean ret;
1192
1193         if (!il) return FALSE;
1194
1195         if (!il->fd) return FALSE;
1196
1197         if (!image_loader_setup_source(il)) return FALSE;
1198
1199         ret = image_loader_begin(il);
1200
1201         if (ret && !il->done) il->idle_id = g_idle_add_full(il->idle_priority, image_loader_idle_cb, il, NULL);
1202         return ret;
1203 }
1204
1205 /**************************************************************************************/
1206 /* execution via thread */
1207
1208 static GThreadPool *image_loader_thread_pool = NULL;
1209
1210 static GCond *image_loader_prio_cond = NULL;
1211 static GMutex *image_loader_prio_mutex = NULL;
1212 static gint image_loader_prio_num = 0;
1213
1214
1215 static void image_loader_thread_enter_high(void)
1216 {
1217         g_mutex_lock(image_loader_prio_mutex);
1218         image_loader_prio_num++;
1219         g_mutex_unlock(image_loader_prio_mutex);
1220 }
1221
1222 static void image_loader_thread_leave_high(void)
1223 {
1224         g_mutex_lock(image_loader_prio_mutex);
1225         image_loader_prio_num--;
1226         if (image_loader_prio_num == 0) g_cond_broadcast(image_loader_prio_cond); /* wake up all low prio threads */
1227         g_mutex_unlock(image_loader_prio_mutex);
1228 }
1229
1230 static void image_loader_thread_wait_high(void)
1231 {
1232         g_mutex_lock(image_loader_prio_mutex);
1233         while (image_loader_prio_num)
1234                 {
1235                 g_cond_wait(image_loader_prio_cond, image_loader_prio_mutex);
1236                 }
1237
1238         g_mutex_unlock(image_loader_prio_mutex);
1239 }
1240
1241
1242 static void image_loader_thread_run(gpointer data, gpointer UNUSED(user_data))
1243 {
1244         ImageLoader *il = data;
1245         gboolean cont;
1246         gboolean err;
1247
1248         if (il->idle_priority > G_PRIORITY_DEFAULT_IDLE)
1249                 {
1250                 /* low prio, wait until high prio tasks finishes */
1251                 image_loader_thread_wait_high();
1252                 }
1253         else
1254                 {
1255                 /* high prio */
1256                 image_loader_thread_enter_high();
1257                 }
1258
1259         err = !image_loader_begin(il);
1260
1261         if (err)
1262                 {
1263                 /*
1264                 loader failed, we have to send signal
1265                 (idle mode returns the image_loader_begin return value directly)
1266                 (success is always reported indirectly from image_loader_begin)
1267                 */
1268                 image_loader_emit_error(il);
1269                 }
1270
1271         cont = !err;
1272
1273         while (cont && !image_loader_get_is_done(il) && !image_loader_get_stopping(il))
1274                 {
1275                 if (il->idle_priority > G_PRIORITY_DEFAULT_IDLE)
1276                         {
1277                         /* low prio, wait until high prio tasks finishes */
1278                         image_loader_thread_wait_high();
1279                         }
1280                 cont = image_loader_continue(il);
1281                 }
1282         image_loader_stop_loader(il);
1283
1284         if (il->idle_priority <= G_PRIORITY_DEFAULT_IDLE)
1285                 {
1286                 /* high prio */
1287                 image_loader_thread_leave_high();
1288                 }
1289
1290         g_mutex_lock(il->data_mutex);
1291         il->can_destroy = TRUE;
1292         g_cond_signal(il->can_destroy_cond);
1293         g_mutex_unlock(il->data_mutex);
1294
1295 }
1296
1297
1298 static gboolean image_loader_start_thread(ImageLoader *il)
1299 {
1300         if (!il) return FALSE;
1301
1302         if (!il->fd) return FALSE;
1303
1304         il->thread = TRUE;
1305
1306         if (!image_loader_setup_source(il)) return FALSE;
1307
1308         if (!image_loader_thread_pool)
1309                 {
1310                 image_loader_thread_pool = g_thread_pool_new(image_loader_thread_run, NULL, -1, FALSE, NULL);
1311                 if (!image_loader_prio_cond) image_loader_prio_cond = g_new(GCond, 1);
1312                 g_cond_init(image_loader_prio_cond);
1313                 if (!image_loader_prio_mutex) image_loader_prio_mutex = g_new(GMutex, 1);
1314                 g_mutex_init(image_loader_prio_mutex);
1315                 }
1316
1317         il->can_destroy = FALSE; /* ImageLoader can't be freed until image_loader_thread_run finishes */
1318
1319         g_thread_pool_push(image_loader_thread_pool, il, NULL);
1320         DEBUG_1("Thread pool num threads: %d", g_thread_pool_get_num_threads(image_loader_thread_pool));
1321
1322         return TRUE;
1323 }
1324
1325
1326 /**************************************************************************************/
1327 /* public interface */
1328
1329
1330 gboolean image_loader_start(ImageLoader *il)
1331 {
1332         if (!il) return FALSE;
1333
1334         if (!il->fd) return FALSE;
1335
1336         return image_loader_start_thread(il);
1337 }
1338
1339
1340 /* don't forget to gdk_pixbuf_ref() it if you want to use it after image_loader_free() */
1341 GdkPixbuf *image_loader_get_pixbuf(ImageLoader *il)
1342 {
1343         GdkPixbuf *ret;
1344         if (!il) return NULL;
1345
1346         g_mutex_lock(il->data_mutex);
1347         ret = il->pixbuf;
1348         g_mutex_unlock(il->data_mutex);
1349         return ret;
1350 }
1351
1352 void image_loader_set_requested_size(ImageLoader *il, gint width, gint height)
1353 {
1354         if (!il) return;
1355
1356         g_mutex_lock(il->data_mutex);
1357         il->requested_width = width;
1358         il->requested_height = height;
1359         g_mutex_unlock(il->data_mutex);
1360 }
1361
1362 void image_loader_set_buffer_size(ImageLoader *il, guint count)
1363 {
1364         if (!il) return;
1365
1366         g_mutex_lock(il->data_mutex);
1367         il->idle_read_loop_count = count ? count : 1;
1368         g_mutex_unlock(il->data_mutex);
1369 }
1370
1371 void image_loader_set_priority(ImageLoader *il, gint priority)
1372 {
1373         if (!il) return;
1374
1375         if (il->thread) return; /* can't change prio if the thread already runs */
1376         il->idle_priority = priority;
1377 }
1378
1379
1380 gdouble image_loader_get_percent(ImageLoader *il)
1381 {
1382         gdouble ret;
1383         if (!il) return 0.0;
1384
1385         g_mutex_lock(il->data_mutex);
1386         if (il->bytes_total == 0)
1387                 {
1388                 ret = 0.0;
1389                 }
1390         else
1391                 {
1392                 ret = (gdouble)il->bytes_read / il->bytes_total;
1393                 }
1394         g_mutex_unlock(il->data_mutex);
1395         return ret;
1396 }
1397
1398 gboolean image_loader_get_is_done(ImageLoader *il)
1399 {
1400         gboolean ret;
1401         if (!il) return FALSE;
1402
1403         g_mutex_lock(il->data_mutex);
1404         ret = il->done;
1405         g_mutex_unlock(il->data_mutex);
1406
1407         return ret;
1408 }
1409
1410 FileData *image_loader_get_fd(ImageLoader *il)
1411 {
1412         FileData *ret;
1413         if (!il) return NULL;
1414
1415         g_mutex_lock(il->data_mutex);
1416         ret = il->fd;
1417         g_mutex_unlock(il->data_mutex);
1418
1419         return ret;
1420 }
1421
1422 gboolean image_loader_get_shrunk(ImageLoader *il)
1423 {
1424         gboolean ret;
1425         if (!il) return FALSE;
1426
1427         g_mutex_lock(il->data_mutex);
1428         ret = il->shrunk;
1429         g_mutex_unlock(il->data_mutex);
1430         return ret;
1431 }
1432
1433 const gchar *image_loader_get_error(ImageLoader *il)
1434 {
1435         const gchar *ret = NULL;
1436         if (!il) return NULL;
1437         g_mutex_lock(il->data_mutex);
1438         if (il->error) ret = il->error->message;
1439         g_mutex_unlock(il->data_mutex);
1440         return ret;
1441 }
1442
1443 gboolean image_load_dimensions(FileData *fd, gint *width, gint *height)
1444 {
1445         gboolean success;
1446         gint width_file = 0;
1447         gint height_file = 0;
1448
1449         gdk_pixbuf_get_file_info(fd->path, &width_file, &height_file);
1450
1451         if (width_file && height_file)
1452                 {
1453                 *width = width_file;
1454                 *height = height_file;
1455                 success = TRUE;
1456                 }
1457         else
1458                 {
1459                 *width = -1;
1460                 *height = -1;
1461                 success = FALSE;
1462                 }
1463
1464         return success;
1465 }
1466 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */