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