Debian Codegraph @

src/utilities/utilities_blur.py

raw symbols SCIP
1 # Licensed under GPL3 https://github.com/maoschanz/drawing/blob/master/LICENSE
2
3 import cairo, threading
4 # from datetime import datetime # Not actually needed, just to measure perfs
5
6 class BlurType(int):
7 INVALID = -1
8 AUTO = 0
9 PX_BOX = 1
10 PX_BOX_MULTI = 2
11 CAIRO_REPAINTS = 3
12 TILES = 4
13
14 class BlurDirection(int):
15 INVALID = -1
16 BOTH = 0
17 HORIZONTAL = 1
18 VERTICAL = 2
19
20 ################################################################################
21
22 def utilities_blur_surface(surface, radius, blur_type, blur_direction):
23 """This is the 'official' method to access the blur algorithms.
24 The third argument is an integer corresponding to the BlurType enumeration.
25 The 4th one is an integer corresponding to the BlurDirection enumeration."""
26 radius = int(radius)
27 if radius < 1:
28 return surface
29 blurred_surface = None
30 # time0 = datetime.now()
31 # print('blurring begins, using algo ', blur_type, '-', blur_direction)
32
33 if blur_type == BlurType.INVALID:
34 return surface
35 elif blur_type == BlurType.AUTO:
36 blur_type = BlurType.PX_BOX
37 # XXX c'est nul ça mdr, mais bon c'est peu utilisé
38
39 if blur_type == BlurType.PX_BOX:
40 blurred_surface = _generic_px_box_blur(surface, radius, blur_direction)
41 elif blur_type == BlurType.PX_BOX_MULTI:
42 blurred_surface = _generic_multi_threaded_blur(surface, radius, blur_direction)
43 elif blur_type == BlurType.CAIRO_REPAINTS:
44 blurred_surface = _generic_cairo_blur(surface, radius, blur_direction)
45 elif blur_type == BlurType.TILES:
46 blurred_surface = _generic_tiled_blur(surface, radius, blur_direction)
47
48 # time1 = datetime.now()
49 # print('blurring ended, total time:', time1 - time0)
50 return blurred_surface
51
52 ################################################################################
53 # BlurType.PX_BOX ##############################################################
54
55 def _generic_px_box_blur(surface, radius, blur_direction):
56 w = surface.get_width()
57 h = surface.get_height()
58 channels = 4 # ARGB
59 if radius > w - 1 or radius > h - 1:
60 return surface
61
62 # this code a modified version of this https://github.com/elementary/granite/blob/14e3aaa216b61f7e63762214c0b36ee97fa7c52b/lib/Drawing/BufferSurface.vala#L230
63 # the main differences (aside of the language) is the poor attempt to use
64 # multithreading (i'm quite sure the access to buffers are not safe at all).
65 # The 2 phases of the algo have been separated to allow directional blur.
66 original = cairo.ImageSurface(cairo.Format.ARGB32, w, h)
67 cairo_context = cairo.Context(original)
68 # cairo_context.set_operator(cairo.Operator.SOURCE)
69 cairo_context.set_source_surface(surface, 0, 0)
70 cairo_context.paint() # XXX is this copy useful?
71 original.flush()
72 pixels = original.get_data()
73
74 buffer0 = [None] * (w * h * channels)
75 vmin = [None] * max(w, h)
76 vmax = [None] * max(w, h)
77 div = 2 * radius + 1
78 dv = [None] * (256 * div)
79 for i in range(0, len(dv)):
80 dv[i] = int(i / div)
81
82 iterations = 1
83 while iterations > 0:
84 iterations = iterations - 1
85 if blur_direction == BlurDirection.VERTICAL:
86 for i in range(0, len(pixels)):
87 buffer0[i] = pixels[i]
88 else:
89 _box_blur_1st_phase(w, h, channels, radius, pixels, buffer0, vmin, vmax, dv)
90 # print('end of the 1st phase…', datetime.now() - time0)
91 if blur_direction == BlurDirection.HORIZONTAL:
92 for i in range(0, len(buffer0)):
93 pixels[i] = buffer0[i]
94 else:
95 _box_blur_2nd_phase(w, h, channels, radius, pixels, buffer0, vmin, vmax, dv)
96 return original
97
98 # this code a modified version of a naïve approach to box blur, copied from
99 # here: https://github.com/elementary/granite/blob/14e3aaa216b61f7e63762214c0b36ee97fa7c52b/lib/Drawing/BufferSurface.vala#L230
100 # The 2 phases of the algo have been separated to allow directional blur.
101
102 def _box_blur_1st_phase(w, h, channels, radius, pixels, buff0, vmin, vmax, dv):
103 """Horizontal blurring"""
104 for x in range(0, w):
105 vmin[x] = min(x + radius + 1, w - 1)
106 vmax[x] = max(x - radius, 0)
107 for y in range(0, h):
108 cur_pixel = y * w * channels
109 asum = radius * pixels[cur_pixel + 0]
110 rsum = radius * pixels[cur_pixel + 1]
111 gsum = radius * pixels[cur_pixel + 2]
112 bsum = radius * pixels[cur_pixel + 3]
113 for i in range(0, radius+1):
114 asum += pixels[cur_pixel + 0]
115 rsum += pixels[cur_pixel + 1]
116 gsum += pixels[cur_pixel + 2]
117 bsum += pixels[cur_pixel + 3]
118 cur_pixel += channels
119 cur_pixel = y * w * channels
120 for x in range(0, w):
121 p1 = (y * w + vmin[x]) * channels
122 p2 = (y * w + vmax[x]) * channels
123 buff0[cur_pixel + 0] = dv[asum]
124 buff0[cur_pixel + 1] = dv[rsum]
125 buff0[cur_pixel + 2] = dv[gsum]
126 buff0[cur_pixel + 3] = dv[bsum]
127 asum += pixels[p1 + 0] - pixels[p2 + 0]
128 rsum += pixels[p1 + 1] - pixels[p2 + 1]
129 gsum += pixels[p1 + 2] - pixels[p2 + 2]
130 bsum += pixels[p1 + 3] - pixels[p2 + 3]
131 cur_pixel += channels
132
133 def _box_blur_2nd_phase(w, h, channels, radius, pixels, buff0, vmin, vmax, dv):
134 """Vertical blurring"""
135 for y in range(0, h):
136 vmin[y] = min(y + radius + 1, h - 1) * w
137 vmax[y] = max (y - radius, 0) * w
138 for x in range(0, w):
139 cur_pixel = x * channels
140 asum = radius * buff0[cur_pixel + 0]
141 rsum = radius * buff0[cur_pixel + 1]
142 gsum = radius * buff0[cur_pixel + 2]
143 bsum = radius * buff0[cur_pixel + 3]
144 for i in range(0, radius+1):
145 asum += buff0[cur_pixel + 0]
146 rsum += buff0[cur_pixel + 1]
147 gsum += buff0[cur_pixel + 2]
148 bsum += buff0[cur_pixel + 3]
149 cur_pixel += w * channels
150 cur_pixel = x * channels
151 for y in range(0, h):
152 p1 = (x + vmin[y]) * channels
153 p2 = (x + vmax[y]) * channels
154 pixels[cur_pixel + 0] = dv[asum]
155 pixels[cur_pixel + 1] = dv[rsum]
156 pixels[cur_pixel + 2] = dv[gsum]
157 pixels[cur_pixel + 3] = dv[bsum]
158 asum += buff0[p1 + 0] - buff0[p2 + 0]
159 rsum += buff0[p1 + 1] - buff0[p2 + 1]
160 gsum += buff0[p1 + 2] - buff0[p2 + 2]
161 bsum += buff0[p1 + 3] - buff0[p2 + 3]
162 cur_pixel += w * channels
163
164 ################################################################################
165 # BlurType.PX_BOX_MULTI ########################################################
166
167 def _generic_multi_threaded_blur(surface, radius, blur_direction):
168 """Experimental multi-threaded blur. The parameter `blur_direction` will be
169 ignored (it always blurs in both directions)."""
170 w = surface.get_width()
171 h = surface.get_height()
172 channels = 4 # ARGB
173 if radius > w - 1 or radius > h - 1:
174 return
175
176 original = cairo.ImageSurface(cairo.Format.ARGB32, w, h)
177 cairo_context = cairo.Context(original)
178 # cairo_context.set_operator(cairo.Operator.SOURCE)
179 cairo_context.set_source_surface(surface, 0, 0)
180 cairo_context.paint()
181 original.flush()
182 pixels = original.get_data()
183
184 buffer0 = [None] * (w * h * channels)
185 vmin = [None] * max(w, h)
186 vmax = [None] * max(w, h)
187 div = 2 * radius + 1
188 dv = [None] * (256 * div)
189 for i in range(0, len(dv)):
190 dv[i] = int(i / div)
191
192 full_buff = _box_blur_1st_phase_multi(w, h, channels, radius, pixels, vmin, vmax, dv)
193 # print('end of the 1st phase…', datetime.now() - time0)
194 _box_blur_2nd_phase(w, h, channels, radius, pixels, full_buff, vmin, vmax, dv)
195
196 return original
197
198 # this code a modified version of a naïve approach to box blur, copied from
199 # here: https://github.com/elementary/granite/blob/14e3aaa216b61f7e63762214c0b36ee97fa7c52b/lib/Drawing/BufferSurface.vala#L230
200 # the main differences (aside of the language) is the poor attempt to use
201 # multithreading (i'm quite sure the access to buffers are not safe at all)
202 # during the first phase. Multithreading of the second phase has not even been
203 # tried because this multithreaded version is slower than _box_blur_1st_phase
204
205 def _box_blur_1st_phase_multi(w, h, channels, radius, pixels, vmin, vmax, dv):
206 NB_THREADS = 4
207 t1 = [None] * NB_THREADS
208 full_buffer = []
209 buffers = []
210 y_end = 0
211 for x in range(0, w):
212 vmin[x] = min(x + radius + 1, w - 1)
213 vmax[x] = max(x - radius, 0)
214 for t in range(0, NB_THREADS):
215 y_start = y_end
216 if t == NB_THREADS - 1:
217 y_end = h
218 else:
219 y_end = y_start + int(h / NB_THREADS)
220 buff_size = w * (y_end - y_start) * channels
221 buff = [0] * buff_size
222 buffers.append(buff)
223 t1[t] = threading.Thread(target=_blur_rows3, args=(x, y_start, y_end, \
224 w, channels, radius, pixels, buff, vmin, vmax, dv))
225 for t in range(0, NB_THREADS):
226 t1[t].start()
227 for t in range(0, NB_THREADS):
228 t1[t].join()
229 full_buffer += buffers[t]
230 return full_buffer
231
232 def _blur_rows3(x, y0, y1, w, channels, radius, pixels, buff0, vmin, vmax, dv):
233 # print('row thread with', y0, y1, '(begin)')
234 diff = y0 * w * channels
235 for y in range(y0, y1):
236 cur_pixel = y * w * channels
237 asum = radius * pixels[cur_pixel + 0]
238 rsum = radius * pixels[cur_pixel + 1]
239 gsum = radius * pixels[cur_pixel + 2]
240 bsum = radius * pixels[cur_pixel + 3]
241 for i in range(0, radius+1):
242 asum += pixels[cur_pixel + 0]
243 rsum += pixels[cur_pixel + 1]
244 gsum += pixels[cur_pixel + 2]
245 bsum += pixels[cur_pixel + 3]
246 cur_pixel += channels
247 cur_pixel = y * w * channels - diff
248 for x in range(0, w):
249 p1 = (y * w + vmin[x]) * channels
250 p2 = (y * w + vmax[x]) * channels
251 buff0[cur_pixel + 0] = dv[asum]
252 buff0[cur_pixel + 1] = dv[rsum]
253 buff0[cur_pixel + 2] = dv[gsum]
254 buff0[cur_pixel + 3] = dv[bsum]
255 asum += pixels[p1 + 0] - pixels[p2 + 0]
256 rsum += pixels[p1 + 1] - pixels[p2 + 1]
257 gsum += pixels[p1 + 2] - pixels[p2 + 2]
258 bsum += pixels[p1 + 3] - pixels[p2 + 3]
259 cur_pixel += channels
260 # print('row thread with', y0, y1, '(end)')
261
262 ################################################################################
263 # BlurType.CAIRO_REPAINTS ######################################################
264
265 def _generic_cairo_blur(surface, radius, blur_direction):
266 if blur_direction == BlurDirection.HORIZONTAL:
267 surface = _cairo_directional_blur(surface, radius, False)
268 elif blur_direction == BlurDirection.VERTICAL:
269 surface = _cairo_directional_blur(surface, radius, True)
270 else:
271 # XXX with some big radius, it's visible that it's just a sequence of
272 # 2 directional blurs instead of an actual algorithm
273 surface = _cairo_directional_blur(surface, radius, True)
274 surface = _cairo_directional_blur(surface, radius, False)
275 return surface
276
277 # Weird attempt to produce a blurred image using cairo. I mean ok, the image is
278 # blurred, and with amazing performances, but the quality is not convincing and
279 # the result when the area has (semi-)transparency really sucks.
280
281 def _cairo_directional_blur(surface, radius, is_vertical):
282 cairo_context = cairo.Context(surface)
283 if radius < 10:
284 step = 1
285 alpha = min(0.9, step / radius)
286 elif radius < 15:
287 step = 1
288 alpha = min(0.9, (0.5 + step) / radius)
289 else:
290 step = int(radius / 6) # why 6? mystery
291 # cette optimisation donne de légers glitchs aux grands radius, qui ne
292 # sont de toutes manières pas beaux car on voit en partie à travers
293 alpha = min(0.9, (1 + step) / radius)
294 for i in range(-1 * radius, radius, step):
295 if is_vertical:
296 cairo_context.set_source_surface(surface, 0, i)
297 else:
298 cairo_context.set_source_surface(surface, i, 0)
299 cairo_context.paint_with_alpha(alpha)
300 surface.flush()
301 return surface
302
303 ################################################################################
304 # BlurType.TILES ###############################################################
305
306 def _generic_tiled_blur(surface, radius, blur_direction):
307 if blur_direction == BlurDirection.HORIZONTAL:
308 tile_width = radius
309 tile_height = 1
310 elif blur_direction == BlurDirection.VERTICAL:
311 tile_width = 1
312 tile_height = radius
313 else:
314 tile_width = radius
315 tile_height = radius
316 return _get_tiled_surface(surface, tile_width, tile_height)
317
318 def _get_tiled_surface(surface, tile_width, tile_height):
319 w = surface.get_width()
320 h = surface.get_height()
321 channels = 4 # ARGB
322 pixels = surface.get_data()
323 pixel_max = w * h * channels
324
325 for x in range(0, w, tile_width):
326 for y in range(0, h, tile_height):
327 current_pixel = (x + (w * y)) * channels
328 if current_pixel >= pixel_max:
329 continue
330 tile_b = pixels[current_pixel + 0]
331 tile_g = pixels[current_pixel + 1]
332 tile_r = pixels[current_pixel + 2]
333 tile_a = pixels[current_pixel + 3]
334 for tx in range(0, tile_width):
335 for ty in range(0, tile_height):
336 current_pixel = ((x + tx) + (w * (y + ty))) * channels
337 if current_pixel >= pixel_max:
338 continue
339 if current_pixel >= (w * (y + ty + 1)) * channels:
340 # the current tile is out of the surface, this guard
341 # clause avoids corrupting the next tile
342 continue
343 pixels[current_pixel + 0] = tile_b
344 pixels[current_pixel + 1] = tile_g
345 pixels[current_pixel + 2] = tile_r
346 pixels[current_pixel + 3] = tile_a
347 # end of one tile
348 # end of the "for each tile"
349 return surface
350
351 ################################################################################
352