add --version to booh and booh-classifier
[booh] / ext / rbbooh.cc
1 /*
2  *                         *  BOOH  *
3  *
4  * A.k.a `Best web-album Of the world, Or your money back, Humerus'.
5  *
6  * The acronyn sucks, however this is a tribute to Dragon Ball by
7  * Akira Toriyama, where the last enemy beaten by heroes of Dragon
8  * Ball is named "Boo". But there was already a free software project
9  * called Boo, so this one will be it "Booh". Or whatever.
10  *
11  *
12  * Copyright (c) 2005-2008 Guillaume Cottenceau
13  *
14  * This software may be freely redistributed under the terms of the GNU
15  * public license version 2.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22
23 #include <math.h>
24
25 #include <exiv2/image.hpp>
26 #include <exiv2/exif.hpp>
27
28 #define GDK_PIXBUF_ENABLE_BACKEND
29 #include <gtk/gtk.h>
30 #include "rbgobject.h"
31
32 #define _SELF(s) GDK_PIXBUF(RVAL2GOBJ(s)) 
33
34 static VALUE whitebalance(VALUE self, VALUE level) {
35         double red_filter[256], blue_filter[256];
36         int i, x, y;
37         guchar* pixels = gdk_pixbuf_get_pixels(_SELF(self));
38         int rowstride = gdk_pixbuf_get_rowstride(_SELF(self));
39
40         double factor = 1 + fabs(NUM2DBL(level))/100;
41         if (NUM2DBL(level) < 0) {
42                 factor = 1/factor;
43         }
44
45         for (i = 0; i < 256; i++) {
46                 red_filter[i]  = pow(((double)i)/255, 1/factor) * 255;
47                 blue_filter[i] = pow(((double)i)/255, factor) * 255;
48         }
49     
50         for (y = 0; y < gdk_pixbuf_get_height(_SELF(self)); y++) {
51                 guchar* pixline = &(pixels[rowstride*y]);
52                 for (x = 0; x < gdk_pixbuf_get_width(_SELF(self)); x++) {
53                         pixline[x*3]   = (guchar) red_filter[pixline[x*3]];
54                         pixline[x*3+2] = (guchar) blue_filter[pixline[x*3+2]];
55                 }
56         }
57
58         return self;
59 }
60
61 static VALUE gammacorrect(VALUE self, VALUE level) {
62         double filter[256];
63         int i, x, y;
64         guchar* pixels = gdk_pixbuf_get_pixels(_SELF(self));
65         int rowstride = gdk_pixbuf_get_rowstride(_SELF(self));
66
67         double factor = 1 + fabs(NUM2DBL(level))/100;
68         if (NUM2DBL(level) > 0) {
69                 factor = 1/factor;
70         }
71
72         for (i = 0; i < 256; i++) {
73                 filter[i] = pow(((double)i)/255, factor) * 255;
74         }
75     
76         for (y = 0; y < gdk_pixbuf_get_height(_SELF(self)); y++) {
77                 guchar* pixline = &(pixels[rowstride*y]);
78                 for (x = 0; x < gdk_pixbuf_get_width(_SELF(self)); x++) {
79                         pixline[x*3]   = (guchar) filter[pixline[x*3]];
80                         pixline[x*3+1] = (guchar) filter[pixline[x*3+1]];
81                         pixline[x*3+2] = (guchar) filter[pixline[x*3+2]];
82                 }
83         }
84
85         return self;
86 }
87
88 static VALUE exif_orientation(VALUE module, VALUE filename) {
89         try {
90                 Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(StringValuePtr(filename));
91                 image->readMetadata();
92                 Exiv2::ExifData &exifData = image->exifData();
93                 if (exifData.empty()) {
94                         return Qnil;
95                 }
96                 Exiv2::ExifData::const_iterator i = exifData.findKey(Exiv2::ExifKey("Exif.Image.Orientation"));
97                 if (i != exifData.end()) {
98                         return INT2NUM(i->value().toLong());
99                 }
100                 return Qnil;
101         } catch (Exiv2::AnyError& e) {
102                 // actually, I don't care about exceptions because I will try non JPG images
103                 // std::cerr << "Caught Exiv2 exception: " << e << "\n";
104                 return Qnil;
105         }
106 }
107
108 static VALUE exif_set_orientation(VALUE module, VALUE filename, VALUE val) {
109         try {
110                 Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(StringValuePtr(filename));
111                 image->readMetadata();
112                 Exiv2::ExifData &exifData = image->exifData();
113                 exifData["Exif.Image.Orientation"] = uint16_t(NUM2INT(val));
114                 image->writeMetadata();
115         } catch (Exiv2::AnyError& e) {
116                 // actually, I don't care about exceptions because I will try non JPG images
117                 // std::cout << "Caught Exiv2 exception: " << e << "\n";
118         }
119         return Qnil;
120 }
121
122 static VALUE exif_datetimeoriginal(VALUE module, VALUE filename) {
123         try {
124                 Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(StringValuePtr(filename));
125                 image->readMetadata();
126                 Exiv2::ExifData &exifData = image->exifData();
127                 if (exifData.empty()) {
128                         return Qnil;
129                 }
130                 Exiv2::ExifData::const_iterator i = exifData.findKey(Exiv2::ExifKey("Exif.Photo.DateTimeOriginal"));
131                 if (i != exifData.end()) {
132                         return rb_str_new2(i->value().toString().c_str());
133                 }
134                 return Qnil;
135         } catch (Exiv2::AnyError& e) {
136                 // actually, I don't care about exceptions because I will try non JPG images
137                 // std::cout << "Caught Exiv2 exception: " << e << "\n";
138                 return Qnil;
139         }
140 }
141
142 // internalize drawing "video" borders, it is too slow in ruby (0.12 secs on my p4 2.8 GHz, whereas it's barely measurable with this implementation)
143 static VALUE draw_borders(VALUE self, VALUE pixbuf, VALUE x1, VALUE x2, VALUE ystart, VALUE yend) {
144         GdkDrawable* drawable = GDK_DRAWABLE(RVAL2GOBJ(self));
145         int y = NUM2INT(ystart);
146         int yend_ = NUM2INT(yend);
147         GdkPixbuf* pb = GDK_PIXBUF(RVAL2GOBJ(pixbuf));
148         int height = gdk_pixbuf_get_height(pb);
149         while (y < yend_) {
150                 int render_height = MIN(height, yend_ - y);
151                 gdk_draw_pixbuf(drawable, NULL, pb, 0, 0, NUM2INT(x1), y, -1, render_height, GDK_RGB_DITHER_NONE, -1, -1);
152                 gdk_draw_pixbuf(drawable, NULL, pb, 0, 0, NUM2INT(x2), y, -1, render_height, GDK_RGB_DITHER_NONE, -1, -1);
153                 y += height;
154         }
155         return self;
156 }
157
158 // internalize memory leak fix for GdkPixbuf.rotate
159 // (bugged as of rg2 0.16.0)
160 static VALUE rotate_noleak(VALUE self, VALUE angle) {
161         VALUE ret;
162         GdkPixbuf* dest = gdk_pixbuf_rotate_simple(_SELF(self), (GdkPixbufRotation) RVAL2GENUM(angle, GDK_TYPE_PIXBUF_ROTATION));
163         if (dest == NULL)
164                 return Qnil;
165         ret = GOBJ2RVAL(dest);
166         g_object_unref(dest);
167         return ret;
168 }
169
170 // internalize allowing to pass Qnil to RVAL2BOXED to have NULL passed to Gtk
171 // (bugged as of rg2 0.16.0)
172 static VALUE modify_bg(VALUE self, VALUE state, VALUE color) {
173         gtk_widget_modify_bg(GTK_WIDGET(RVAL2GOBJ(self)), (GtkStateType) RVAL2GENUM(state, GTK_TYPE_STATE_TYPE),
174                              NIL_P(color) ? NULL : (GdkColor*) RVAL2BOXED(color, GDK_TYPE_COLOR));
175         return self;
176 }
177
178 static int counter = 0;
179
180 // internalize pixbuf loading for 30% more speedup
181 static VALUE load_not_freezing_ui(VALUE self, VALUE path, VALUE interruptable, VALUE area_prepared_signal_id) {
182         int interruptable_ = RTEST(interruptable);
183         char buf[65536];
184         size_t amount;
185         GdkPixbufLoader* loader = GDK_PIXBUF_LOADER(RVAL2GOBJ(self));
186         GError* error = NULL;
187         FILE* f = fopen(RVAL2CSTR(path), "r");
188         if (!f) {
189                 rb_raise(rb_eRuntimeError, "Unable to open file %s for reading", RVAL2CSTR(path));
190         }
191         counter++;
192         while ((amount = fread(buf, 1, 65536, f)) > 0) {
193                 if (!gdk_pixbuf_loader_write(loader, (const guchar*) buf, amount, &error)) {
194                         fclose(f);
195                         RAISE_GERROR(error);
196                 }
197                 if (counter < 52) {
198                         // if the user scrolls too fast between thumbnails, there can be large amount of recursions,
199                         // and program may abort - probably on exhausted stack size; this figure is completely empiric
200                         while (gtk_events_pending()) {
201                                 gtk_main_iteration();
202                         }
203                         if (interruptable_ && RTEST(rb_eval_string("$interrupt_loading"))) {
204                                 // interrupted, case when the user clicked/keyboarded too quickly for this image to
205                                 // display; we cancel this loading, but before we disconnect the area-prepared
206                                 // signal handler, else the call to gdk_pixbuf_loader_get_pixbuf will take ages
207                                 // (between 100 and 400 ms on my p4 for a large photo!)
208                                 g_signal_handler_disconnect(loader, NUM2INT(area_prepared_signal_id));
209                                 gdk_pixbuf_loader_close(loader, NULL);
210                                 fclose(f);
211                                 counter--;
212                                 return Qfalse;
213                         }
214                 }
215         }
216         fclose(f);
217         counter--;
218         return Qtrue;
219 }
220
221 extern "C" {
222 void 
223 Init_libadds()
224 {
225     RGObjClassInfo* cinfo = (RGObjClassInfo*)rbgobj_lookup_class_by_gtype(GDK_TYPE_PIXBUF, Qnil);
226     rb_define_method(cinfo->klass, "whitebalance!", (VALUE (*)(...)) whitebalance, 1); 
227     rb_define_method(cinfo->klass, "gammacorrect!", (VALUE (*)(...)) gammacorrect, 1); 
228     rb_define_method(cinfo->klass, "rotate", (VALUE (*)(...)) rotate_noleak, 1); 
229
230     cinfo = (RGObjClassInfo*)rbgobj_lookup_class_by_gtype(GDK_TYPE_DRAWABLE, Qnil);
231     rb_define_method(cinfo->klass, "draw_borders", (VALUE (*)(...)) draw_borders, 5);
232
233     cinfo = (RGObjClassInfo*)rbgobj_lookup_class_by_gtype(GTK_TYPE_WIDGET, Qnil);
234     rb_define_method(cinfo->klass, "modify_bg", (VALUE (*)(...)) modify_bg, 2);
235
236     cinfo = (RGObjClassInfo*)rbgobj_lookup_class_by_gtype(GDK_TYPE_PIXBUF_LOADER, Qnil);
237     rb_define_method(cinfo->klass, "load_not_freezing_ui", (VALUE (*)(...)) load_not_freezing_ui, 3);
238
239     VALUE exif = rb_define_module("Exif");
240     rb_define_module_function(exif, "orientation", (VALUE (*)(...)) exif_orientation, 1);
241     rb_define_module_function(exif, "set_orientation", (VALUE (*)(...)) exif_set_orientation, 2);
242     rb_define_module_function(exif, "datetimeoriginal", (VALUE (*)(...)) exif_datetimeoriginal, 1);
243 }
244 }