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