Add API for setting resource destruction callback
[platform/core/uifw/dali-adaptor.git] / dali / internal / imaging / ubuntu-x11 / native-image-source-impl-x.cpp
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.h>
20
21 // EXTERNAL INCLUDES
22 #include <X11/Xlib.h>
23 #include <X11/Xutil.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/internal/system/linux/dali-ecore-x.h>
26
27 // INTERNAL INCLUDES
28 #include <dali/integration-api/adaptor-framework/render-surface-interface.h>
29 #include <dali/internal/adaptor/common/adaptor-impl.h>
30 #include <dali/internal/graphics/common/egl-image-extensions.h>
31 #include <dali/internal/graphics/gles/egl-graphics.h>
32
33 namespace Dali
34 {
35 namespace Internal
36 {
37 namespace Adaptor
38 {
39 using Dali::Integration::PixelBuffer;
40
41 // Pieces needed to save compressed images (temporary location while plumbing):
42 namespace
43 {
44 /**
45    * Free an allocated XImage on destruction.
46    */
47 struct XImageJanitor
48 {
49   XImageJanitor(XImage* const pXImage)
50   : mXImage(pXImage)
51   {
52     DALI_ASSERT_DEBUG(pXImage != 0 && "Null pointer to XImage.");
53   }
54
55   ~XImageJanitor()
56   {
57     if(mXImage)
58     {
59       if(!XDestroyImage(mXImage))
60       {
61         DALI_LOG_ERROR("XImage deallocation failure");
62       }
63     }
64   }
65   XImage* const mXImage;
66
67 private:
68   XImageJanitor(const XImageJanitor& rhs);
69   XImageJanitor& operator=(const XImageJanitor& rhs);
70 };
71 } // namespace
72
73 NativeImageSourceX* NativeImageSourceX::New(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource)
74 {
75   NativeImageSourceX* image = new NativeImageSourceX(width, height, depth, nativeImageSource);
76   DALI_ASSERT_DEBUG(image && "NativeImageSource allocation failed.");
77
78   // 2nd phase construction
79   if(image) //< Defensive in case we ever compile without exceptions.
80   {
81     image->Initialize();
82   }
83
84   return image;
85 }
86
87 NativeImageSourceX::NativeImageSourceX(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource)
88 : mWidth(width),
89   mHeight(height),
90   mOwnPixmap(true),
91   mPixmap(0),
92   mBlendingRequired(false),
93   mColorDepth(depth),
94   mEglImageKHR(NULL),
95   mEglImageExtensions(NULL),
96   mResourceDestructionCallback()
97 {
98   DALI_ASSERT_ALWAYS(Adaptor::IsAvailable());
99
100   GraphicsInterface* graphics    = &(Adaptor::GetImplementation(Adaptor::Get()).GetGraphicsInterface());
101   auto               eglGraphics = static_cast<EglGraphics*>(graphics);
102
103   mEglImageExtensions = eglGraphics->GetImageExtensions();
104
105   DALI_ASSERT_DEBUG(mEglImageExtensions);
106
107   // assign the pixmap
108   mPixmap = GetPixmapFromAny(nativeImageSource);
109 }
110
111 void NativeImageSourceX::Initialize()
112 {
113   // if pixmap has been created outside of X11 Image we can return
114   if(mPixmap)
115   {
116     // we don't own the pixmap
117     mOwnPixmap = false;
118
119     // find out the pixmap width / height and color depth
120     GetPixmapDetails();
121     return;
122   }
123
124   // get the pixel depth
125   int depth = GetPixelDepth(mColorDepth);
126
127   // set whether blending is required according to pixel format based on the depth
128   /* default pixel format is RGB888
129      If depth = 8, Pixel::A8;
130      If depth = 16, Pixel::RGB565;
131      If depth = 32, Pixel::RGBA8888 */
132   mBlendingRequired = (depth == 32 || depth == 8);
133
134   mPixmap = ecore_x_pixmap_new(0, mWidth, mHeight, depth);
135   ecore_x_sync();
136 }
137
138 NativeImageSourceX::~NativeImageSourceX()
139 {
140   if(mOwnPixmap && mPixmap)
141   {
142     // Temporarily disable this as this causes a crash with EFL Version 1.24.0
143     //ecore_x_pixmap_free(mPixmap);
144   }
145 }
146
147 Any NativeImageSourceX::GetNativeImageSource() const
148 {
149   // return ecore x11 type
150   return Any(mPixmap);
151 }
152
153 bool NativeImageSourceX::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const
154 {
155   DALI_ASSERT_DEBUG(sizeof(unsigned) == 4);
156   bool success = false;
157   width        = mWidth;
158   height       = mHeight;
159
160   // Open a display connection
161   Display* displayConnection = XOpenDisplay(0);
162
163   XImageJanitor xImageJanitor(XGetImage(displayConnection,
164                                         mPixmap,
165                                         0,
166                                         0, // x,y of subregion to extract.
167                                         width,
168                                         height, // of subregion to extract.
169                                         0xFFFFFFFF,
170                                         ZPixmap));
171   XImage* const pXImage = xImageJanitor.mXImage;
172   DALI_ASSERT_DEBUG(pXImage && "XImage (from pixmap) could not be retrieved from the server");
173   if(!pXImage)
174   {
175     DALI_LOG_ERROR("Could not retrieve Ximage.\n");
176   }
177   else
178   {
179     switch(pXImage->depth)
180     {
181       // Note, depth is a logical value. On target the framebuffer is still 32bpp
182       // (see pXImage->bits_per_pixel) so we go through XGetPixel() and swizzle.
183       // Note, this could be the default, fallback case for all depths if *pXImage
184       // didn't have blank RGB masks (X bug), but we have to hardcode the masks and
185       // shifts instead.
186       case 24:
187       {
188         pixelFormat = Pixel::RGB888;
189         pixbuf.resize(width * height * 3);
190         unsigned char* bufPtr = &pixbuf[0];
191
192         for(unsigned y = 0; y < height; ++y)
193         {
194           for(unsigned x = 0; x < width; ++x, bufPtr += 3)
195           {
196             const unsigned pixel = XGetPixel(pXImage, x, y);
197
198             // store as RGB
199             const unsigned blue  = pixel & 0xFFU;
200             const unsigned green = (pixel >> 8) & 0xFFU;
201             const unsigned red   = (pixel >> 16) & 0xFFU;
202
203             *bufPtr       = red;
204             *(bufPtr + 1) = green;
205             *(bufPtr + 2) = blue;
206           }
207         }
208         success = true;
209         break;
210       }
211       case 32:
212       {
213         if(pXImage->data)
214         {
215           // Sweep through the image, doing a vertical flip, but handling each scanline as
216           // an inlined intrinsic/builtin memcpy (should be fast):
217           pixbuf.resize(width * height * 4);
218           unsigned*      bufPtr        = reinterpret_cast<unsigned*>(&pixbuf[0]);
219           const unsigned xDataLineSkip = pXImage->bytes_per_line;
220           const size_t   copy_count    = static_cast<size_t>(width) * 4;
221           pixelFormat                  = Pixel::BGRA8888;
222
223           for(unsigned y = 0; y < height; ++y, bufPtr += width)
224           {
225             const char* const in = pXImage->data + xDataLineSkip * y;
226
227             // Copy a whole scanline at a time:
228             DALI_ASSERT_DEBUG(size_t(bufPtr) >= size_t(&pixbuf[0]));
229             DALI_ASSERT_DEBUG(reinterpret_cast<size_t>(bufPtr) + copy_count <= reinterpret_cast<size_t>(&pixbuf[pixbuf.size()]));
230             DALI_ASSERT_DEBUG(in >= pXImage->data);
231             DALI_ASSERT_DEBUG(in + copy_count <= pXImage->data + xDataLineSkip * height);
232             __builtin_memcpy(bufPtr, in, copy_count);
233           }
234           success = true;
235         }
236         else
237         {
238           DALI_LOG_ERROR("XImage has null data pointer.\n");
239         }
240         break;
241       }
242       // Make a case for 16 bit modes especially to remember that the only reason we don't support them is a bug in X:
243       case 16:
244       {
245         DALI_ASSERT_DEBUG(pXImage->red_mask && pXImage->green_mask && pXImage->blue_mask && "No image masks mean 16 bit modes are not possible.");
246         ///! If the above assert doesn't fail in a debug build, the X bug may have been fixed, so revisit this function.
247         ///! No break, fall through to the general unsupported format warning below.
248       }
249       default:
250       {
251         DALI_LOG_WARNING("Pixmap has unsupported bit-depth for getting pixels: %u\n", pXImage->depth);
252       }
253     }
254   }
255   if(!success)
256   {
257     DALI_LOG_ERROR("Failed to get pixels from NativeImageSource.\n");
258     pixbuf.resize(0);
259     width  = 0;
260     height = 0;
261   }
262
263   // Close the display connection
264   XCloseDisplay(displayConnection);
265
266   return success;
267 }
268
269 void NativeImageSourceX::SetSource(Any source)
270 {
271   mPixmap = GetPixmapFromAny(source);
272
273   if(mPixmap)
274   {
275     // we don't own the pixmap
276     mOwnPixmap = false;
277
278     // find out the pixmap width / height and color depth
279     GetPixmapDetails();
280   }
281 }
282
283 bool NativeImageSourceX::IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth)
284 {
285   return true;
286 }
287
288 bool NativeImageSourceX::CreateResource()
289 {
290   // if the image existed previously delete it.
291   if(mEglImageKHR != NULL)
292   {
293     DestroyResource();
294   }
295
296   // casting from an unsigned int to a void *, which should then be cast back
297   // to an unsigned int in the driver.
298   EGLClientBuffer eglBuffer = reinterpret_cast<EGLClientBuffer>(mPixmap);
299
300   mEglImageKHR = mEglImageExtensions->CreateImageKHR(eglBuffer);
301
302   return mEglImageKHR != NULL;
303 }
304
305 void NativeImageSourceX::DestroyResource()
306 {
307   mEglImageExtensions->DestroyImageKHR(mEglImageKHR);
308
309   mEglImageKHR = NULL;
310
311   if(mResourceDestructionCallback)
312   {
313     mResourceDestructionCallback->Trigger();
314   }
315 }
316
317 uint32_t NativeImageSourceX::TargetTexture()
318 {
319   mEglImageExtensions->TargetTextureKHR(mEglImageKHR);
320
321   return 0;
322 }
323
324 void NativeImageSourceX::PrepareTexture()
325 {
326 }
327
328 int NativeImageSourceX::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const
329 {
330   switch(depth)
331   {
332     case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
333     {
334       // Get the default screen depth
335       return ecore_x_default_depth_get(ecore_x_display_get(), ecore_x_default_screen_get());
336     }
337     case Dali::NativeImageSource::COLOR_DEPTH_8:
338     {
339       return 8;
340     }
341     case Dali::NativeImageSource::COLOR_DEPTH_16:
342     {
343       return 16;
344     }
345     case Dali::NativeImageSource::COLOR_DEPTH_24:
346     {
347       return 24;
348     }
349     case Dali::NativeImageSource::COLOR_DEPTH_32:
350     {
351       return 32;
352     }
353     default:
354     {
355       DALI_ASSERT_DEBUG(0 && "unknown color enum");
356       return 0;
357     }
358   }
359 }
360
361 int NativeImageSourceX::GetTextureTarget() const
362 {
363   return GL_TEXTURE_2D;
364 }
365
366 bool NativeImageSourceX::ApplyNativeFragmentShader(std::string& shader)
367 {
368   return false;
369 }
370
371 const char* NativeImageSourceX::GetCustomSamplerTypename() const
372 {
373   return nullptr;
374 }
375
376 Any NativeImageSourceX::GetNativeImageHandle() const
377 {
378   return Any(mPixmap);
379 }
380
381 bool NativeImageSourceX::SourceChanged() const
382 {
383   return false;
384 }
385
386 Ecore_X_Pixmap NativeImageSourceX::GetPixmapFromAny(Any pixmap) const
387 {
388   if(pixmap.Empty())
389   {
390     return 0;
391   }
392
393   // see if it is of type x11 pixmap
394   if(pixmap.GetType() == typeid(Pixmap))
395   {
396     // get the x pixmap type
397     Pixmap xpixmap = AnyCast<Pixmap>(pixmap);
398
399     // cast it to a ecore pixmap type
400     return static_cast<Ecore_X_Pixmap>(xpixmap);
401   }
402   else
403   {
404     return AnyCast<Ecore_X_Pixmap>(pixmap);
405   }
406 }
407
408 void NativeImageSourceX::GetPixmapDetails()
409 {
410   int x, y;
411
412   // get the width, height and depth
413   ecore_x_pixmap_geometry_get(mPixmap, &x, &y, reinterpret_cast<int*>(&mWidth), reinterpret_cast<int*>(&mHeight));
414
415   // set whether blending is required according to pixel format based on the depth
416   /* default pixel format is RGB888
417      If depth = 8, Pixel::A8;
418      If depth = 16, Pixel::RGB565;
419      If depth = 32, Pixel::RGBA8888 */
420   int depth         = ecore_x_pixmap_depth_get(mPixmap);
421   mBlendingRequired = (depth == 32 || depth == 8);
422 }
423
424 uint8_t* NativeImageSourceX::AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride)
425 {
426   return NULL;
427 }
428
429 bool NativeImageSourceX::ReleaseBuffer()
430 {
431   return false;
432 }
433
434 void NativeImageSourceX::SetResourceDestructionCallback(EventThreadCallback* callback)
435 {
436   mResourceDestructionCallback = std::unique_ptr<EventThreadCallback>(callback);
437 }
438
439 } // namespace Adaptor
440
441 } // namespace Internal
442
443 } // namespace Dali