fbf72a173a6f2c064d6397ddbb09bdd6e6a327bc
[platform/core/uifw/dali-adaptor.git] / adaptors / common / pixel-buffer-impl.cpp
1 /*
2  * Copyright (c) 2018 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 "pixel-buffer-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <stdlib.h>
23 #include <cstring>
24
25 // INTERNAL INCLUDES
26 #include "pixel-manipulation.h"
27 #include "alpha-mask.h"
28 #include "gaussian-blur.h"
29 #include <platform-abstractions/portable/image-operations.h>
30 #include <platform-abstractions/portable/pixel-manipulation.h>
31
32 namespace Dali
33 {
34
35 namespace Internal
36 {
37
38 namespace Adaptor
39 {
40
41 namespace
42 {
43 const float TWO_PI = 2.f * Math::PI; ///< 360 degrees in radians
44 } // namespace
45
46 PixelBuffer::PixelBuffer( unsigned char* buffer,
47                           unsigned int bufferSize,
48                           unsigned int width,
49                           unsigned int height,
50                           Dali::Pixel::Format pixelFormat )
51 : mMetadata(),
52   mBuffer( buffer ),
53   mBufferSize( bufferSize ),
54   mWidth( width ),
55   mHeight( height ),
56   mPixelFormat( pixelFormat )
57 {
58 }
59
60 PixelBuffer::~PixelBuffer()
61 {
62   ReleaseBuffer();
63 }
64
65 PixelBufferPtr PixelBuffer::New( unsigned int width,
66                                  unsigned int height,
67                                  Dali::Pixel::Format pixelFormat )
68 {
69   unsigned int bufferSize = width * height * Dali::Pixel::GetBytesPerPixel( pixelFormat );
70   unsigned char* buffer = NULL;
71   if( bufferSize > 0 )
72   {
73     buffer = static_cast<unsigned char*>( malloc ( bufferSize ) );
74   }
75   return new PixelBuffer( buffer, bufferSize, width, height, pixelFormat );
76 }
77
78 PixelBufferPtr PixelBuffer::New( unsigned char* buffer,
79                                  unsigned int bufferSize,
80                                  unsigned int width,
81                                  unsigned int height,
82                                  Dali::Pixel::Format pixelFormat )
83 {
84   return new PixelBuffer( buffer, bufferSize, width, height, pixelFormat );
85 }
86
87 Dali::PixelData PixelBuffer::Convert( PixelBuffer& pixelBuffer )
88 {
89   Dali::PixelData pixelData = Dali::PixelData::New( pixelBuffer.mBuffer,
90                                                     pixelBuffer.mBufferSize,
91                                                     pixelBuffer.mWidth,
92                                                     pixelBuffer.mHeight,
93                                                     pixelBuffer.mPixelFormat,
94                                                     Dali::PixelData::FREE );
95   pixelBuffer.mBuffer = NULL;
96   pixelBuffer.mWidth = 0;
97   pixelBuffer.mHeight = 0;
98   pixelBuffer.mBufferSize = 0;
99
100   return pixelData;
101 }
102
103 unsigned int PixelBuffer::GetWidth() const
104 {
105   return mWidth;
106 }
107
108 unsigned int PixelBuffer::GetHeight() const
109 {
110   return mHeight;
111 }
112
113 Dali::Pixel::Format PixelBuffer::GetPixelFormat() const
114 {
115   return mPixelFormat;
116 }
117
118 unsigned char* PixelBuffer::GetBuffer() const
119 {
120   return mBuffer;
121 }
122
123 unsigned int PixelBuffer::GetBufferSize() const
124 {
125   return mBufferSize;
126 }
127
128 Dali::PixelData PixelBuffer::CreatePixelData() const
129 {
130   unsigned char* destBuffer = NULL;
131
132   if( mBufferSize > 0 )
133   {
134     destBuffer = static_cast<unsigned char*>( malloc( mBufferSize ) );
135     memcpy( destBuffer, mBuffer, mBufferSize );
136   }
137
138   Dali::PixelData pixelData = Dali::PixelData::New( destBuffer, mBufferSize,
139                                                     mWidth, mHeight,
140                                                     mPixelFormat,
141                                                     Dali::PixelData::FREE );
142   return pixelData;
143 }
144
145 void PixelBuffer::ApplyMask( const PixelBuffer& inMask, float contentScale, bool cropToMask )
146 {
147   if( cropToMask )
148   {
149     // First scale this buffer by the contentScale, and crop to the mask size
150     // If it's too small, then scale the mask to match the image size
151     // Then apply the mask
152     ScaleAndCrop( contentScale, ImageDimensions( inMask.GetWidth(), inMask.GetHeight() ) );
153
154     if( inMask.mWidth > mWidth || inMask.mHeight > mHeight )
155     {
156       PixelBufferPtr mask = NewResize( inMask, ImageDimensions( mWidth, mHeight ) );
157       ApplyMaskInternal( *mask );
158     }
159     else
160     {
161       ApplyMaskInternal( inMask );
162     }
163   }
164   else
165   {
166     // First, scale the mask to match the image size,
167     // then apply the mask.
168     PixelBufferPtr mask = NewResize( inMask, ImageDimensions( mWidth, mHeight ) );
169     ApplyMaskInternal( *mask );
170   }
171 }
172
173 void PixelBuffer::ApplyMaskInternal( const PixelBuffer& mask )
174 {
175   int byteOffset=0;
176   int bitMask=0;
177
178   Dali::Pixel::GetAlphaOffsetAndMask(mPixelFormat, byteOffset, bitMask);
179   if( Dali::Pixel::HasAlpha( mPixelFormat ) && bitMask == 255 )
180   {
181     ApplyMaskToAlphaChannel( *this, mask );
182   }
183   else
184   {
185     PixelBufferPtr newPixelBuffer = CreateNewMaskedBuffer( *this, mask );
186     TakeOwnershipOfBuffer( *newPixelBuffer );
187     // On leaving scope, newPixelBuffer will get destroyed.
188   }
189 }
190
191 void PixelBuffer::TakeOwnershipOfBuffer( PixelBuffer& pixelBuffer )
192 {
193   ReleaseBuffer();
194
195   // Take ownership of new buffer
196   mBuffer = pixelBuffer.mBuffer;
197   pixelBuffer.mBuffer = NULL;
198   mBufferSize = pixelBuffer.mBufferSize;
199   mWidth = pixelBuffer.mWidth;
200   mHeight = pixelBuffer.mHeight;
201   mPixelFormat = pixelBuffer.mPixelFormat;
202 }
203
204 void PixelBuffer::ReleaseBuffer()
205 {
206   if( mBuffer )
207   {
208     free( mBuffer );
209   }
210 }
211
212 void PixelBuffer::AllocateFixedSize( uint32_t size )
213 {
214   ReleaseBuffer();
215   mBuffer = reinterpret_cast<unsigned char*>(malloc( size ));
216   mBufferSize = size;
217 }
218
219 void PixelBuffer::Rotate( Degree angle )
220 {
221   // Check first if Rotate() can perform the operation in the current pixel buffer.
222
223   bool validPixelFormat = false;
224   switch( mPixelFormat )
225   {
226     case Pixel::A8:
227     case Pixel::L8:
228     case Pixel::LA88:
229     case Pixel::RGB888:
230     case Pixel::RGB8888:
231     case Pixel::BGR8888:
232     case Pixel::RGBA8888:
233     case Pixel::BGRA8888: // FALL THROUGH
234     {
235       validPixelFormat = true;
236       break;
237     }
238     default:
239     {
240       // This pixel format is not supported for this operation.
241       validPixelFormat = false;
242       break;
243     }
244   }
245
246   if( !validPixelFormat )
247   {
248     // Can't rotate the pixel buffer with the current pixel format.
249     DALI_LOG_ERROR( "Can't rotate the pixel buffer with the current pixel format\n" );
250     return;
251   }
252
253   float radians = Radian( angle ).radian;
254
255   // Transform the input angle into the range [0..2PI]
256   radians = fmod( radians, TWO_PI );
257   radians += ( radians < 0.f ) ? TWO_PI : 0.f;
258
259   if( radians < Dali::Math::MACHINE_EPSILON_10 )
260   {
261     // Nothing to do if the angle is zero.
262     return;
263   }
264
265   const unsigned int pixelSize = Pixel::GetBytesPerPixel( mPixelFormat );
266
267   uint8_t* pixelsOut = nullptr;
268   Platform::RotateByShear( mBuffer,
269                            mWidth,
270                            mHeight,
271                            pixelSize,
272                            radians,
273                            pixelsOut,
274                            mWidth,
275                            mHeight );
276
277   // Release the memory of the current pixel buffer.
278   ReleaseBuffer();
279
280   // Set the new pixel buffer.
281   mBuffer = pixelsOut;
282   pixelsOut = nullptr;
283   mBufferSize = mWidth * mHeight * pixelSize;
284 }
285
286 void PixelBuffer::ScaleAndCrop( float scaleFactor, ImageDimensions cropDimensions )
287 {
288   ImageDimensions outDimensions( float(mWidth) * scaleFactor,
289                                  float(mHeight) * scaleFactor );
290
291   if( outDimensions.GetWidth() != mWidth || outDimensions.GetHeight() != mHeight )
292   {
293     Resize( outDimensions );
294   }
295
296   ImageDimensions postCropDimensions(
297     std::min(cropDimensions.GetWidth(), outDimensions.GetWidth()),
298     std::min(cropDimensions.GetHeight(), outDimensions.GetHeight()));
299
300   if( postCropDimensions.GetWidth() < outDimensions.GetWidth() ||
301       postCropDimensions.GetHeight() < outDimensions.GetHeight() )
302   {
303     uint16_t x = ( outDimensions.GetWidth()  - postCropDimensions.GetWidth() ) / 2;
304     uint16_t y = ( outDimensions.GetHeight() - postCropDimensions.GetHeight() ) / 2;
305     Crop( x, y, postCropDimensions );
306   }
307 }
308
309 void PixelBuffer::Crop( uint16_t x, uint16_t y, ImageDimensions cropDimensions )
310 {
311   PixelBufferPtr outBuffer = NewCrop( *this, x, y, cropDimensions );
312   TakeOwnershipOfBuffer( *outBuffer );
313 }
314
315 PixelBufferPtr PixelBuffer::NewCrop( const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions )
316 {
317   PixelBufferPtr outBuffer = PixelBuffer::New( cropDimensions.GetWidth(), cropDimensions.GetHeight(), inBuffer.GetPixelFormat() );
318   int bytesPerPixel = Pixel::GetBytesPerPixel( inBuffer.mPixelFormat );
319   int srcStride = inBuffer.mWidth * bytesPerPixel;
320   int destStride = cropDimensions.GetWidth() * bytesPerPixel;
321
322   // Clamp crop to right edge
323   if( x + cropDimensions.GetWidth() > inBuffer.mWidth )
324   {
325     destStride = ( inBuffer.mWidth - x ) * bytesPerPixel;
326   }
327
328   int srcOffset = x * bytesPerPixel + y * srcStride;
329   int destOffset = 0;
330   unsigned char* destBuffer = outBuffer->mBuffer;
331
332   // Clamp crop to last row
333   unsigned int endRow = y + cropDimensions.GetHeight();
334   if( endRow > inBuffer.mHeight )
335   {
336     endRow = inBuffer.mHeight - 1 ;
337   }
338   for( uint16_t row = y; row < endRow; ++row )
339   {
340     memcpy(destBuffer + destOffset, inBuffer.mBuffer + srcOffset, destStride );
341     srcOffset += srcStride;
342     destOffset += destStride;
343   }
344   return outBuffer;
345
346 }
347
348 void PixelBuffer::SetMetadata( const Property::Map& map )
349 {
350   mMetadata.reset(new Property::Map(map));
351 }
352
353 bool PixelBuffer::GetMetadata(Property::Map& outMetadata) const
354 {
355   if( !mMetadata )
356   {
357     return false;
358   }
359   outMetadata = *mMetadata;
360   return true;
361 }
362
363 void PixelBuffer::SetMetadata(std::unique_ptr<Property::Map> metadata)
364 {
365   mMetadata = std::move(metadata);
366 }
367
368 void PixelBuffer::Resize( ImageDimensions outDimensions )
369 {
370   if( mWidth != outDimensions.GetWidth() || mHeight != outDimensions.GetHeight() )
371   {
372     PixelBufferPtr outBuffer = NewResize( *this, outDimensions );
373     TakeOwnershipOfBuffer( *outBuffer );
374   }
375 }
376
377 PixelBufferPtr PixelBuffer::NewResize( const PixelBuffer& inBuffer, ImageDimensions outDimensions )
378 {
379   PixelBufferPtr outBuffer = PixelBuffer::New( outDimensions.GetWidth(), outDimensions.GetHeight(), inBuffer.GetPixelFormat() );
380   ImageDimensions inDimensions( inBuffer.mWidth, inBuffer.mHeight );
381
382   bool hasAlpha = Pixel::HasAlpha( inBuffer.mPixelFormat );
383   int bytesPerPixel = Pixel::GetBytesPerPixel( inBuffer.mPixelFormat );
384
385   Resampler::Filter filterType = Resampler::LANCZOS4;
386   if( inDimensions.GetWidth() < outDimensions.GetWidth() && inDimensions.GetHeight() < outDimensions.GetHeight() )
387   {
388     filterType = Resampler::MITCHELL;
389   }
390
391   // This method only really works for 8 bit wide channels.
392   // (But could be expanded to work)
393   if( inBuffer.mPixelFormat == Pixel::A8 ||
394       inBuffer.mPixelFormat == Pixel::L8 ||
395       inBuffer.mPixelFormat == Pixel::LA88 ||
396       inBuffer.mPixelFormat == Pixel::RGB888 ||
397       inBuffer.mPixelFormat == Pixel::RGB8888 ||
398       inBuffer.mPixelFormat == Pixel::BGR8888 ||
399       inBuffer.mPixelFormat == Pixel::RGBA8888 ||
400       inBuffer.mPixelFormat == Pixel::BGRA8888 )
401   {
402     Dali::Internal::Platform::Resample( inBuffer.mBuffer, inDimensions,
403                                         outBuffer->GetBuffer(), outDimensions,
404                                         filterType, bytesPerPixel, hasAlpha );
405   }
406   else
407   {
408     DALI_LOG_ERROR( "Trying to resize an image with too narrow a channel width" );
409   }
410
411   return outBuffer;
412 }
413
414 void PixelBuffer::ApplyGaussianBlur( const float blurRadius )
415 {
416   // This method only works for pixel buffer in RGBA format.
417   if( mWidth > 0 && mHeight > 0 && mPixelFormat == Pixel::RGBA8888 )
418   {
419     if ( blurRadius > Math::MACHINE_EPSILON_1 )
420     {
421       PerformGaussianBlurRGBA( *this, blurRadius );
422     }
423   }
424   else
425   {
426     DALI_LOG_ERROR( "Trying to apply gaussian blur to an empty pixel buffer or a pixel buffer not in RGBA format" );
427   }
428 }
429
430 void PixelBuffer::MultiplyColorByAlpha()
431 {
432   auto bytesPerPixel = Pixel::GetBytesPerPixel( mPixelFormat );
433
434   // Compressed textures have unknown size of the pixel. Alpha premultiplication
435   // must be skipped in such case
436   if( Pixel::GetBytesPerPixel(mPixelFormat) && Pixel::HasAlpha(mPixelFormat) )
437   {
438     unsigned char* pixel = mBuffer;
439     const unsigned int bufferSize = mWidth * mHeight;
440
441     for( unsigned int i=0; i<bufferSize; ++i )
442     {
443       unsigned int alpha = ReadChannel( pixel, mPixelFormat, Adaptor::ALPHA );
444       {
445         auto red       = ReadChannel( pixel, mPixelFormat, Adaptor::RED);
446         auto green     = ReadChannel( pixel, mPixelFormat, Adaptor::GREEN);
447         auto blue      = ReadChannel( pixel, mPixelFormat, Adaptor::BLUE);
448         auto luminance = ReadChannel( pixel, mPixelFormat, Adaptor::LUMINANCE);
449         WriteChannel( pixel, mPixelFormat, Adaptor::RED, red*alpha / 255 );
450         WriteChannel( pixel, mPixelFormat, Adaptor::GREEN, green*alpha/255 );
451         WriteChannel( pixel, mPixelFormat, Adaptor::BLUE, blue*alpha/255 );
452         WriteChannel( pixel, mPixelFormat, Adaptor::LUMINANCE, luminance*alpha/255 );
453       }
454       pixel += bytesPerPixel;
455     }
456   }
457 }
458
459
460
461
462 }// namespace Adaptor
463 }// namespace Internal
464 }// namespace Dali