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