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