1 /*
2  * Copyright (c) 2014-2019, The Linux Foundation. All rights reserved.
3  * Not a Contribution.
4  *
5  * Copyright 2015 The Android Open Source Project
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 
20 #include "hwc_layers.h"
21 #include <utils/debug.h>
22 #include <stdint.h>
23 #include <utility>
24 #include <cmath>
25 #include <qdMetaData.h>
26 
27 #define __CLASS__ "HWCLayer"
28 
29 namespace sdm {
30 
31 std::atomic<hwc2_layer_t> HWCLayer::next_id_(1);
32 
SetCSC(const private_handle_t * pvt_handle,ColorMetaData * color_metadata)33 DisplayError SetCSC(const private_handle_t *pvt_handle, ColorMetaData *color_metadata) {
34   if (getMetaData(const_cast<private_handle_t *>(pvt_handle), GET_COLOR_METADATA,
35                   color_metadata) != 0) {
36     ColorSpace_t csc = ITU_R_601;
37     if (getMetaData(const_cast<private_handle_t *>(pvt_handle),  GET_COLOR_SPACE,
38                     &csc) == 0) {
39       if (csc == ITU_R_601_FR || csc == ITU_R_2020_FR) {
40         color_metadata->range = Range_Full;
41       }
42 
43       switch (csc) {
44         case ITU_R_601:
45         case ITU_R_601_FR:
46           // video and display driver uses 601_525
47           color_metadata->colorPrimaries = ColorPrimaries_BT601_6_525;
48           break;
49         case ITU_R_709:
50           color_metadata->colorPrimaries = ColorPrimaries_BT709_5;
51           break;
52         case ITU_R_2020:
53         case ITU_R_2020_FR:
54           color_metadata->colorPrimaries = ColorPrimaries_BT2020;
55           break;
56         default:
57           DLOGE("Unsupported CSC: %d", csc);
58           return kErrorNotSupported;
59       }
60     }
61   }
62 
63   return kErrorNone;
64 }
65 
66 // Returns true when color primary is supported
GetColorPrimary(const int32_t & dataspace,ColorPrimaries * color_primary)67 bool GetColorPrimary(const int32_t &dataspace, ColorPrimaries *color_primary) {
68   auto standard = dataspace & HAL_DATASPACE_STANDARD_MASK;
69   bool supported_csc = true;
70   switch (standard) {
71     case  HAL_DATASPACE_STANDARD_BT709:
72       *color_primary = ColorPrimaries_BT709_5;
73       break;
74     case HAL_DATASPACE_STANDARD_BT601_525:
75     case HAL_DATASPACE_STANDARD_BT601_525_UNADJUSTED:
76       *color_primary = ColorPrimaries_BT601_6_525;
77       break;
78     case HAL_DATASPACE_STANDARD_BT601_625:
79     case HAL_DATASPACE_STANDARD_BT601_625_UNADJUSTED:
80       *color_primary = ColorPrimaries_BT601_6_625;
81       break;
82     case HAL_DATASPACE_STANDARD_DCI_P3:
83       *color_primary = ColorPrimaries_DCIP3;
84       break;
85     case HAL_DATASPACE_STANDARD_BT2020:
86       *color_primary = ColorPrimaries_BT2020;
87       break;
88     default:
89       DLOGW_IF(kTagClient, "Unsupported Standard Request = %d", standard);
90       supported_csc = false;
91   }
92   return supported_csc;
93 }
94 
GetTransfer(const int32_t & dataspace,GammaTransfer * gamma_transfer)95 bool GetTransfer(const int32_t &dataspace, GammaTransfer *gamma_transfer) {
96   auto transfer = dataspace & HAL_DATASPACE_TRANSFER_MASK;
97   bool supported_transfer = true;
98   switch (transfer) {
99     case HAL_DATASPACE_TRANSFER_SRGB:
100       *gamma_transfer = Transfer_sRGB;
101       break;
102     case HAL_DATASPACE_TRANSFER_SMPTE_170M:
103       *gamma_transfer = Transfer_SMPTE_170M;
104       break;
105     case HAL_DATASPACE_TRANSFER_ST2084:
106       *gamma_transfer = Transfer_SMPTE_ST2084;
107       break;
108     case HAL_DATASPACE_TRANSFER_HLG:
109       *gamma_transfer = Transfer_HLG;
110       break;
111     case HAL_DATASPACE_TRANSFER_LINEAR:
112       *gamma_transfer = Transfer_Linear;
113       break;
114     case HAL_DATASPACE_TRANSFER_GAMMA2_2:
115       *gamma_transfer = Transfer_Gamma2_2;
116       break;
117     case HAL_DATASPACE_TRANSFER_GAMMA2_8:
118       *gamma_transfer = Transfer_Gamma2_8;
119       break;
120     default:
121       DLOGW_IF(kTagClient, "Unsupported Transfer Request = %d", transfer);
122       supported_transfer = false;
123   }
124   return supported_transfer;
125 }
126 
GetRange(const int32_t & dataspace,ColorRange * color_range)127 bool GetRange(const int32_t &dataspace, ColorRange *color_range) {
128   auto range = dataspace & HAL_DATASPACE_RANGE_MASK;
129   switch (range) {
130     case HAL_DATASPACE_RANGE_FULL:
131       *color_range = Range_Full;
132       break;
133     case HAL_DATASPACE_RANGE_LIMITED:
134       *color_range = Range_Limited;
135       break;
136     case HAL_DATASPACE_RANGE_EXTENDED:
137       *color_range = Range_Extended;
138       return false;
139     default:
140       DLOGW_IF(kTagClient, "Unsupported Range Request = %d", range);
141       return false;
142   }
143   return true;
144 }
145 
IsBT2020(const ColorPrimaries & color_primary)146 bool IsBT2020(const ColorPrimaries &color_primary) {
147   switch (color_primary) {
148   case ColorPrimaries_BT2020:
149     return true;
150     break;
151   default:
152     return false;
153   }
154 }
155 
TranslateFromLegacyDataspace(const int32_t & legacy_ds)156 int32_t TranslateFromLegacyDataspace(const int32_t &legacy_ds) {
157   int32_t dataspace = legacy_ds;
158 
159   if (dataspace & 0xffff) {
160     switch (dataspace & 0xffff) {
161       case HAL_DATASPACE_SRGB:
162         dataspace = HAL_DATASPACE_V0_SRGB;
163         break;
164       case HAL_DATASPACE_JFIF:
165         dataspace = HAL_DATASPACE_V0_JFIF;
166         break;
167       case HAL_DATASPACE_SRGB_LINEAR:
168         dataspace = HAL_DATASPACE_V0_SRGB_LINEAR;
169         break;
170       case HAL_DATASPACE_BT601_625:
171         dataspace = HAL_DATASPACE_V0_BT601_625;
172         break;
173       case HAL_DATASPACE_BT601_525:
174         dataspace = HAL_DATASPACE_V0_BT601_525;
175         break;
176       case HAL_DATASPACE_BT709:
177         dataspace = HAL_DATASPACE_V0_BT709;
178         break;
179       default:
180         // unknown legacy dataspace
181         DLOGW_IF(kTagClient, "Unsupported dataspace type %d", dataspace);
182     }
183   }
184 
185   if (dataspace == HAL_DATASPACE_UNKNOWN) {
186     dataspace = HAL_DATASPACE_V0_SRGB;
187   }
188 
189   return dataspace;
190 }
191 
192 // Retrieve ColorMetaData from android_data_space_t (STANDARD|TRANSFER|RANGE)
GetSDMColorSpace(const int32_t & dataspace,ColorMetaData * color_metadata)193 bool GetSDMColorSpace(const int32_t &dataspace, ColorMetaData *color_metadata) {
194   bool valid = false;
195   valid = GetColorPrimary(dataspace, &(color_metadata->colorPrimaries));
196   if (valid) {
197     valid = GetTransfer(dataspace, &(color_metadata->transfer));
198   }
199   if (valid) {
200     valid = GetRange(dataspace, &(color_metadata->range));
201   }
202 
203   return valid;
204 }
205 
206 // Layer operations
HWCLayer(hwc2_display_t display_id,HWCBufferAllocator * buf_allocator)207 HWCLayer::HWCLayer(hwc2_display_t display_id, HWCBufferAllocator *buf_allocator)
208   : id_(next_id_++), display_id_(display_id), buffer_allocator_(buf_allocator) {
209   layer_ = new Layer();
210   // Fences are deferred, so the first time this layer is presented, return -1
211   // TODO(user): Verify that fences are properly obtained on suspend/resume
212   release_fences_.push_back(-1);
213 }
214 
~HWCLayer()215 HWCLayer::~HWCLayer() {
216   // Close any fences left for this layer
217   while (!release_fences_.empty()) {
218     ::close(release_fences_.front());
219     release_fences_.pop_front();
220   }
221   if (layer_) {
222     if (layer_->input_buffer.acquire_fence_fd >= 0) {
223       ::close(layer_->input_buffer.acquire_fence_fd);
224     }
225     if (buffer_fd_ >= 0) {
226       ::close(buffer_fd_);
227     }
228     delete layer_;
229   }
230 }
231 
SetLayerBuffer(buffer_handle_t buffer,int32_t acquire_fence)232 HWC2::Error HWCLayer::SetLayerBuffer(buffer_handle_t buffer, int32_t acquire_fence) {
233   if (!buffer) {
234     if (client_requested_ == HWC2::Composition::Device ||
235         client_requested_ == HWC2::Composition::Cursor) {
236       DLOGE("Invalid buffer handle: %p on layer: %d client requested comp type %d", buffer, id_,
237             client_requested_);
238       ::close(acquire_fence);
239       return HWC2::Error::BadParameter;
240     } else {
241       return HWC2::Error::None;
242     }
243   }
244 
245   if (acquire_fence == 0) {
246     DLOGW("acquire_fence is zero");
247     return HWC2::Error::BadParameter;
248   }
249 
250   const private_handle_t *handle = static_cast<const private_handle_t *>(buffer);
251 
252   if (handle->fd < 0) {
253     return HWC2::Error::BadParameter;
254   }
255 
256   LayerBuffer *layer_buffer = &layer_->input_buffer;
257   int aligned_width, aligned_height;
258   buffer_allocator_->GetCustomWidthAndHeight(handle, &aligned_width, &aligned_height);
259 
260   LayerBufferFormat format = GetSDMFormat(handle->format, handle->flags);
261   if ((format != layer_buffer->format) || (UINT32(aligned_width) != layer_buffer->width) ||
262       (UINT32(aligned_height) != layer_buffer->height)) {
263     // Layer buffer geometry has changed.
264     geometry_changes_ |= kBufferGeometry;
265   }
266 
267   layer_buffer->format = format;
268   layer_buffer->width = UINT32(aligned_width);
269   layer_buffer->height = UINT32(aligned_height);
270   layer_buffer->unaligned_width = UINT32(handle->unaligned_width);
271   layer_buffer->unaligned_height = UINT32(handle->unaligned_height);
272 
273   if (SetMetaData(const_cast<private_handle_t *>(handle), layer_) != kErrorNone) {
274     return HWC2::Error::BadLayer;
275   }
276 
277   layer_buffer->flags.video = (handle->buffer_type == BUFFER_TYPE_VIDEO) ? true : false;
278 
279   // TZ Protected Buffer - L1
280   bool secure = (handle->flags & private_handle_t::PRIV_FLAGS_SECURE_BUFFER);
281   bool secure_camera = secure && (handle->flags & private_handle_t::PRIV_FLAGS_CAMERA_WRITE);
282   bool secure_display = (handle->flags & private_handle_t::PRIV_FLAGS_SECURE_DISPLAY);
283   if (secure != layer_buffer->flags.secure || secure_camera != layer_buffer->flags.secure_camera ||
284       secure_display != layer_buffer->flags.secure_display) {
285     // Secure attribute of layer buffer has changed.
286     layer_->update_mask.set(kSecurity);
287   }
288 
289   layer_buffer->flags.secure = secure;
290   layer_buffer->flags.secure_camera = secure_camera;
291   layer_buffer->flags.secure_display = secure_display;
292 
293   if (layer_buffer->acquire_fence_fd >= 0) {
294     ::close(layer_buffer->acquire_fence_fd);
295   }
296   layer_buffer->acquire_fence_fd = acquire_fence;
297   if (buffer_fd_ >= 0) {
298     ::close(buffer_fd_);
299   }
300   buffer_fd_ = ::dup(handle->fd);
301   layer_buffer->planes[0].fd = buffer_fd_;
302   layer_buffer->planes[0].offset = handle->offset;
303   layer_buffer->planes[0].stride = UINT32(handle->width);
304   layer_buffer->size = handle->size;
305   buffer_flipped_ = reinterpret_cast<uint64_t>(handle) != layer_buffer->buffer_id;
306   layer_buffer->buffer_id = reinterpret_cast<uint64_t>(handle);
307   layer_buffer->handle_id = handle->id;
308 
309   return HWC2::Error::None;
310 }
311 
SetLayerSurfaceDamage(hwc_region_t damage)312 HWC2::Error HWCLayer::SetLayerSurfaceDamage(hwc_region_t damage) {
313   surface_updated_ = true;
314   if ((damage.numRects == 1) && (damage.rects[0].bottom == 0) && (damage.rects[0].right == 0)) {
315     surface_updated_ = false;
316   }
317 
318   if (!layer_->flags.updating && surface_updated_) {
319     layer_->update_mask.set(kSurfaceInvalidate);
320   }
321 
322   if (!partial_update_enabled_) {
323     SetDirtyRegions(damage);
324     return HWC2::Error::None;
325   }
326 
327   // Check if there is an update in SurfaceDamage rects.
328   if (layer_->dirty_regions.size() != damage.numRects) {
329     layer_->update_mask.set(kSurfaceInvalidate);
330   } else {
331     for (uint32_t j = 0; j < damage.numRects; j++) {
332       LayerRect damage_rect;
333       SetRect(damage.rects[j], &damage_rect);
334       if (damage_rect != layer_->dirty_regions.at(j)) {
335         layer_->update_mask.set(kSurfaceDamage);
336         break;
337       }
338     }
339   }
340 
341   SetDirtyRegions(damage);
342   return HWC2::Error::None;
343 }
344 
SetLayerBlendMode(HWC2::BlendMode mode)345 HWC2::Error HWCLayer::SetLayerBlendMode(HWC2::BlendMode mode) {
346   LayerBlending blending = kBlendingPremultiplied;
347   switch (mode) {
348     case HWC2::BlendMode::Coverage:
349       blending = kBlendingCoverage;
350       break;
351     case HWC2::BlendMode::Premultiplied:
352       blending = kBlendingPremultiplied;
353       break;
354     case HWC2::BlendMode::None:
355       blending = kBlendingOpaque;
356       break;
357     default:
358       return HWC2::Error::BadParameter;
359   }
360 
361   if (layer_->blending != blending) {
362     geometry_changes_ |= kBlendMode;
363     layer_->blending = blending;
364   }
365   return HWC2::Error::None;
366 }
367 
SetLayerColor(hwc_color_t color)368 HWC2::Error HWCLayer::SetLayerColor(hwc_color_t color) {
369   if (client_requested_ != HWC2::Composition::SolidColor) {
370     return HWC2::Error::None;
371   }
372   if (layer_->solid_fill_color != GetUint32Color(color)) {
373     layer_->solid_fill_color = GetUint32Color(color);
374     layer_->update_mask.set(kSurfaceInvalidate);
375     surface_updated_ = true;
376   } else {
377     surface_updated_ = false;
378   }
379 
380   layer_->input_buffer.format = kFormatARGB8888;
381   DLOGV_IF(kTagClient, "[%" PRIu64 "][%" PRIu64 "] Layer color set to %x", display_id_, id_,
382            layer_->solid_fill_color);
383   return HWC2::Error::None;
384 }
385 
SetLayerCompositionType(HWC2::Composition type)386 HWC2::Error HWCLayer::SetLayerCompositionType(HWC2::Composition type) {
387   // Validation is required when the client changes the composition type
388   if (client_requested_ != type) {
389     layer_->update_mask.set(kClientCompRequest);
390   }
391   client_requested_ = type;
392   switch (type) {
393     case HWC2::Composition::Client:
394       break;
395     case HWC2::Composition::Device:
396       // We try and default to this in SDM
397       break;
398     case HWC2::Composition::SolidColor:
399       break;
400     case HWC2::Composition::Cursor:
401       break;
402     case HWC2::Composition::Invalid:
403       return HWC2::Error::BadParameter;
404     default:
405       return HWC2::Error::Unsupported;
406   }
407 
408   return HWC2::Error::None;
409 }
410 
SetLayerDataspace(int32_t dataspace)411 HWC2::Error HWCLayer::SetLayerDataspace(int32_t dataspace) {
412   // Map deprecated dataspace values to appropriate new enums
413   dataspace = TranslateFromLegacyDataspace(dataspace);
414 
415   // cache the dataspace, to be used later to update SDM ColorMetaData
416   if (dataspace_ != dataspace) {
417     geometry_changes_ |= kDataspace;
418     dataspace_ = dataspace;
419   }
420   return HWC2::Error::None;
421 }
422 
SetLayerDisplayFrame(hwc_rect_t frame)423 HWC2::Error HWCLayer::SetLayerDisplayFrame(hwc_rect_t frame) {
424   LayerRect dst_rect = {};
425 
426   SetRect(frame, &dst_rect);
427   if (dst_rect_ != dst_rect) {
428     geometry_changes_ |= kDisplayFrame;
429     dst_rect_ = dst_rect;
430   }
431 
432   return HWC2::Error::None;
433 }
434 
ResetPerFrameData()435 void HWCLayer::ResetPerFrameData() {
436   layer_->dst_rect = dst_rect_;
437   layer_->transform = layer_transform_;
438 }
439 
SetCursorPosition(int32_t x,int32_t y)440 HWC2::Error HWCLayer::SetCursorPosition(int32_t x, int32_t y) {
441   hwc_rect_t frame = {};
442   frame.left = x;
443   frame.top = y;
444   frame.right = x + INT(layer_->dst_rect.right - layer_->dst_rect.left);
445   frame.bottom = y + INT(layer_->dst_rect.bottom - layer_->dst_rect.top);
446   SetLayerDisplayFrame(frame);
447 
448   return HWC2::Error::None;
449 }
450 
SetLayerPlaneAlpha(float alpha)451 HWC2::Error HWCLayer::SetLayerPlaneAlpha(float alpha) {
452   if (alpha < 0.0f || alpha > 1.0f) {
453     return HWC2::Error::BadParameter;
454   }
455 
456   //  Conversion of float alpha in range 0.0 to 1.0 similar to the HWC Adapter
457   uint8_t plane_alpha = static_cast<uint8_t>(std::round(255.0f * alpha));
458 
459   if (layer_->plane_alpha != plane_alpha) {
460     geometry_changes_ |= kPlaneAlpha;
461     layer_->plane_alpha = plane_alpha;
462   }
463 
464   return HWC2::Error::None;
465 }
466 
SetLayerSourceCrop(hwc_frect_t crop)467 HWC2::Error HWCLayer::SetLayerSourceCrop(hwc_frect_t crop) {
468   LayerRect src_rect = {};
469   SetRect(crop, &src_rect);
470   non_integral_source_crop_ = ((crop.left != roundf(crop.left)) ||
471                               (crop.top != roundf(crop.top)) ||
472                               (crop.right != roundf(crop.right)) ||
473                               (crop.bottom != roundf(crop.bottom)));
474   if (non_integral_source_crop_) {
475     DLOGV_IF(kTagClient, "Crop: LTRB %f %f %f %f", crop.left, crop.top, crop.right, crop.bottom);
476   }
477   if (layer_->src_rect != src_rect) {
478     geometry_changes_ |= kSourceCrop;
479     layer_->src_rect = src_rect;
480   }
481 
482   return HWC2::Error::None;
483 }
484 
SetLayerTransform(HWC2::Transform transform)485 HWC2::Error HWCLayer::SetLayerTransform(HWC2::Transform transform) {
486   LayerTransform layer_transform = {};
487   switch (transform) {
488     case HWC2::Transform::FlipH:
489       layer_transform.flip_horizontal = true;
490       break;
491     case HWC2::Transform::FlipV:
492       layer_transform.flip_vertical = true;
493       break;
494     case HWC2::Transform::Rotate90:
495       layer_transform.rotation = 90.0f;
496       break;
497     case HWC2::Transform::Rotate180:
498       layer_transform.flip_horizontal = true;
499       layer_transform.flip_vertical = true;
500       break;
501     case HWC2::Transform::Rotate270:
502       layer_transform.rotation = 90.0f;
503       layer_transform.flip_horizontal = true;
504       layer_transform.flip_vertical = true;
505       break;
506     case HWC2::Transform::FlipHRotate90:
507       layer_transform.rotation = 90.0f;
508       layer_transform.flip_horizontal = true;
509       break;
510     case HWC2::Transform::FlipVRotate90:
511       layer_transform.rotation = 90.0f;
512       layer_transform.flip_vertical = true;
513       break;
514     case HWC2::Transform::None:
515       break;
516     default:
517       //  bad transform
518       return HWC2::Error::BadParameter;
519   }
520 
521   if (layer_transform_ != layer_transform) {
522     geometry_changes_ |= kTransform;
523     layer_transform_ = layer_transform;
524   }
525 
526   return HWC2::Error::None;
527 }
528 
SetLayerVisibleRegion(hwc_region_t visible)529 HWC2::Error HWCLayer::SetLayerVisibleRegion(hwc_region_t visible) {
530   layer_->visible_regions.clear();
531   for (uint32_t i = 0; i < visible.numRects; i++) {
532     LayerRect rect;
533     SetRect(visible.rects[i], &rect);
534     layer_->visible_regions.push_back(rect);
535   }
536 
537   return HWC2::Error::None;
538 }
539 
SetLayerZOrder(uint32_t z)540 HWC2::Error HWCLayer::SetLayerZOrder(uint32_t z) {
541   if (z_ != z) {
542     geometry_changes_ |= kZOrder;
543     z_ = z;
544   }
545   return HWC2::Error::None;
546 }
547 
SetLayerColorTransform(const float * matrix)548 HWC2::Error HWCLayer::SetLayerColorTransform(const float *matrix) {
549   color_transform_matrix_set_ =
550       (std::memcmp(matrix, kIdentityMatrix, sizeof(kIdentityMatrix)) != 0);
551   return HWC2::Error::None;
552 }
553 
SetLayerPerFrameMetadata(uint32_t num_elements,const PerFrameMetadataKey * keys,const float * metadata)554 HWC2::Error HWCLayer::SetLayerPerFrameMetadata(uint32_t num_elements,
555                                                const PerFrameMetadataKey *keys,
556                                                const float *metadata) {
557   auto &mastering_display = layer_->input_buffer.color_metadata.masteringDisplayInfo;
558   auto &content_light = layer_->input_buffer.color_metadata.contentLightLevel;
559   for (uint32_t i = 0; i < num_elements; i++) {
560     switch (keys[i]) {
561       case PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X:
562         mastering_display.colorVolumeSEIEnabled = true;
563         mastering_display.primaries.rgbPrimaries[0][0] = UINT32(metadata[i] * 50000);
564         break;
565       case PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y:
566         mastering_display.primaries.rgbPrimaries[0][1] = UINT32(metadata[i] * 50000);
567         break;
568       case PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X:
569         mastering_display.primaries.rgbPrimaries[1][0] = UINT32(metadata[i] * 50000);
570         break;
571       case PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y:
572         mastering_display.primaries.rgbPrimaries[1][1] = UINT32(metadata[i] * 50000);
573         break;
574       case PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X:
575         mastering_display.primaries.rgbPrimaries[2][0] = UINT32(metadata[i] * 50000);
576         break;
577       case PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y:
578         mastering_display.primaries.rgbPrimaries[2][1] = UINT32(metadata[i] * 50000);
579         break;
580       case PerFrameMetadataKey::WHITE_POINT_X:
581         mastering_display.primaries.whitePoint[0] = UINT32(metadata[i] * 50000);
582         break;
583       case PerFrameMetadataKey::WHITE_POINT_Y:
584         mastering_display.primaries.whitePoint[1] = UINT32(metadata[i] * 50000);
585         break;
586       case PerFrameMetadataKey::MAX_LUMINANCE:
587         mastering_display.maxDisplayLuminance = UINT32(metadata[i]);
588         break;
589       case PerFrameMetadataKey::MIN_LUMINANCE:
590         mastering_display.minDisplayLuminance = UINT32(metadata[i] * 10000);
591         break;
592       case PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL:
593         content_light.lightLevelSEIEnabled = true;
594         content_light.maxContentLightLevel = UINT32(metadata[i]);
595         break;
596       case PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL:
597         content_light.minPicAverageLightLevel = UINT32(metadata[i] * 10000);
598         break;
599     }
600   }
601   return HWC2::Error::None;
602 }
603 
SetRect(const hwc_rect_t & source,LayerRect * target)604 void HWCLayer::SetRect(const hwc_rect_t &source, LayerRect *target) {
605   target->left = FLOAT(source.left);
606   target->top = FLOAT(source.top);
607   target->right = FLOAT(source.right);
608   target->bottom = FLOAT(source.bottom);
609 }
610 
SetRect(const hwc_frect_t & source,LayerRect * target)611 void HWCLayer::SetRect(const hwc_frect_t &source, LayerRect *target) {
612   // Recommended way of rounding as in hwcomposer2.h - SetLayerSourceCrop
613   target->left = std::ceil(source.left);
614   target->top = std::ceil(source.top);
615   target->right = std::floor(source.right);
616   target->bottom = std::floor(source.bottom);
617 }
618 
GetUint32Color(const hwc_color_t & source)619 uint32_t HWCLayer::GetUint32Color(const hwc_color_t &source) {
620   // Returns 32 bit ARGB
621   uint32_t a = UINT32(source.a) << 24;
622   uint32_t r = UINT32(source.r) << 16;
623   uint32_t g = UINT32(source.g) << 8;
624   uint32_t b = UINT32(source.b);
625   uint32_t color = a | r | g | b;
626   return color;
627 }
628 
GetSDMFormat(const int32_t & source,const int flags)629 LayerBufferFormat HWCLayer::GetSDMFormat(const int32_t &source, const int flags) {
630   LayerBufferFormat format = kFormatInvalid;
631   if (flags & private_handle_t::PRIV_FLAGS_UBWC_ALIGNED) {
632     switch (source) {
633       case HAL_PIXEL_FORMAT_RGBA_8888:
634         format = kFormatRGBA8888Ubwc;
635         break;
636       case HAL_PIXEL_FORMAT_RGBX_8888:
637         format = kFormatRGBX8888Ubwc;
638         break;
639       case HAL_PIXEL_FORMAT_BGR_565:
640         format = kFormatBGR565Ubwc;
641         break;
642       case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
643       case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
644       case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
645         format = kFormatYCbCr420SPVenusUbwc;
646         break;
647       case HAL_PIXEL_FORMAT_RGBA_1010102:
648         format = kFormatRGBA1010102Ubwc;
649         break;
650       case HAL_PIXEL_FORMAT_RGBX_1010102:
651         format = kFormatRGBX1010102Ubwc;
652         break;
653       case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC:
654         format = kFormatYCbCr420TP10Ubwc;
655         break;
656       case HAL_PIXEL_FORMAT_YCbCr_420_P010_UBWC:
657         format = kFormatYCbCr420P010Ubwc;
658         break;
659       default:
660         DLOGE("Unsupported format type for UBWC %d", source);
661         return kFormatInvalid;
662     }
663     return format;
664   }
665 
666   switch (source) {
667     case HAL_PIXEL_FORMAT_RGBA_8888:
668       format = kFormatRGBA8888;
669       break;
670     case HAL_PIXEL_FORMAT_RGBA_5551:
671       format = kFormatRGBA5551;
672       break;
673     case HAL_PIXEL_FORMAT_RGBA_4444:
674       format = kFormatRGBA4444;
675       break;
676     case HAL_PIXEL_FORMAT_BGRA_8888:
677       format = kFormatBGRA8888;
678       break;
679     case HAL_PIXEL_FORMAT_RGBX_8888:
680       format = kFormatRGBX8888;
681       break;
682     case HAL_PIXEL_FORMAT_BGRX_8888:
683       format = kFormatBGRX8888;
684       break;
685     case HAL_PIXEL_FORMAT_RGB_888:
686       format = kFormatRGB888;
687       break;
688     case HAL_PIXEL_FORMAT_BGR_888:
689       format = kFormatBGR888;
690       break;
691     case HAL_PIXEL_FORMAT_RGB_565:
692       format = kFormatRGB565;
693       break;
694     case HAL_PIXEL_FORMAT_BGR_565:
695       format = kFormatBGR565;
696       break;
697     case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
698     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
699       format = kFormatYCbCr420SemiPlanarVenus;
700       break;
701     case HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS:
702       format = kFormatYCrCb420SemiPlanarVenus;
703       break;
704     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
705       format = kFormatYCbCr420SPVenusUbwc;
706       break;
707     case HAL_PIXEL_FORMAT_YV12:
708       format = kFormatYCrCb420PlanarStride16;
709       break;
710     case HAL_PIXEL_FORMAT_YCrCb_420_SP:
711       format = kFormatYCrCb420SemiPlanar;
712       break;
713     case HAL_PIXEL_FORMAT_YCbCr_420_SP:
714       format = kFormatYCbCr420SemiPlanar;
715       break;
716     case HAL_PIXEL_FORMAT_YCbCr_422_SP:
717       format = kFormatYCbCr422H2V1SemiPlanar;
718       break;
719     case HAL_PIXEL_FORMAT_YCbCr_422_I:
720       format = kFormatYCbCr422H2V1Packed;
721       break;
722     case HAL_PIXEL_FORMAT_CbYCrY_422_I:
723       format = kFormatCbYCrY422H2V1Packed;
724       break;
725     case HAL_PIXEL_FORMAT_RGBA_1010102:
726       format = kFormatRGBA1010102;
727       break;
728     case HAL_PIXEL_FORMAT_ARGB_2101010:
729       format = kFormatARGB2101010;
730       break;
731     case HAL_PIXEL_FORMAT_RGBX_1010102:
732       format = kFormatRGBX1010102;
733       break;
734     case HAL_PIXEL_FORMAT_XRGB_2101010:
735       format = kFormatXRGB2101010;
736       break;
737     case HAL_PIXEL_FORMAT_BGRA_1010102:
738       format = kFormatBGRA1010102;
739       break;
740     case HAL_PIXEL_FORMAT_ABGR_2101010:
741       format = kFormatABGR2101010;
742       break;
743     case HAL_PIXEL_FORMAT_BGRX_1010102:
744       format = kFormatBGRX1010102;
745       break;
746     case HAL_PIXEL_FORMAT_XBGR_2101010:
747       format = kFormatXBGR2101010;
748       break;
749     case HAL_PIXEL_FORMAT_YCbCr_420_P010:
750       format = kFormatYCbCr420P010;
751       break;
752     case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC:
753       format = kFormatYCbCr420TP10Ubwc;
754       break;
755     case HAL_PIXEL_FORMAT_YCbCr_420_P010_UBWC:
756       format = kFormatYCbCr420P010Ubwc;
757       break;
758     case HAL_PIXEL_FORMAT_YCbCr_420_P010_VENUS:
759       format = kFormatYCbCr420P010Venus;
760       break;
761     case HAL_PIXEL_FORMAT_RGBA_FP16:
762       format = kFormatInvalid;
763       break;
764     default:
765       DLOGW("Unsupported format type = %d", source);
766       return kFormatInvalid;
767   }
768 
769   return format;
770 }
771 
GetS3DFormat(uint32_t s3d_format)772 LayerBufferS3DFormat HWCLayer::GetS3DFormat(uint32_t s3d_format) {
773   LayerBufferS3DFormat sdm_s3d_format = kS3dFormatNone;
774   switch (s3d_format) {
775     case HAL_NO_3D:
776       sdm_s3d_format = kS3dFormatNone;
777       break;
778     case HAL_3D_SIDE_BY_SIDE_L_R:
779       sdm_s3d_format = kS3dFormatLeftRight;
780       break;
781     case HAL_3D_SIDE_BY_SIDE_R_L:
782       sdm_s3d_format = kS3dFormatRightLeft;
783       break;
784     case HAL_3D_TOP_BOTTOM:
785       sdm_s3d_format = kS3dFormatTopBottom;
786       break;
787     default:
788       DLOGW("Invalid S3D format %d", s3d_format);
789   }
790   return sdm_s3d_format;
791 }
792 
GetUBWCStatsFromMetaData(UBWCStats * cr_stats,UbwcCrStatsVector * cr_vec)793 void HWCLayer::GetUBWCStatsFromMetaData(UBWCStats *cr_stats, UbwcCrStatsVector *cr_vec) {
794   // TODO(user): Check if we can use UBWCStats directly
795   // in layer_buffer or copy directly to Vector
796   if (cr_stats->bDataValid) {
797     switch (cr_stats->version) {
798       case UBWC_3_0:
799       case UBWC_2_0:
800         cr_vec->push_back(std::make_pair(32, cr_stats->ubwc_stats.nCRStatsTile32));
801         cr_vec->push_back(std::make_pair(64, cr_stats->ubwc_stats.nCRStatsTile64));
802         cr_vec->push_back(std::make_pair(96, cr_stats->ubwc_stats.nCRStatsTile96));
803         cr_vec->push_back(std::make_pair(128, cr_stats->ubwc_stats.nCRStatsTile128));
804         cr_vec->push_back(std::make_pair(160, cr_stats->ubwc_stats.nCRStatsTile160));
805         cr_vec->push_back(std::make_pair(192, cr_stats->ubwc_stats.nCRStatsTile192));
806         cr_vec->push_back(std::make_pair(256, cr_stats->ubwc_stats.nCRStatsTile256));
807         break;
808       default:
809         DLOGW("Invalid UBWC Version %d", cr_stats->version);
810         break;
811     }  // switch(cr_stats->version)
812   }  // if (cr_stats->bDatvalid)
813 }
814 
SetMetaData(const private_handle_t * pvt_handle,Layer * layer)815 DisplayError HWCLayer::SetMetaData(const private_handle_t *pvt_handle, Layer *layer) {
816   LayerBuffer *layer_buffer = &layer->input_buffer;
817   private_handle_t *handle = const_cast<private_handle_t *>(pvt_handle);
818   IGC_t igc = {};
819   LayerIGC layer_igc = layer_buffer->igc;
820   if (getMetaData(handle, GET_IGC, &igc) == 0) {
821     if (SetIGC(igc, &layer_igc) != kErrorNone) {
822       return kErrorNotSupported;
823     }
824   }
825 
826   float fps = 0;
827   uint32_t frame_rate = layer->frame_rate;
828   if (getMetaData(handle, GET_REFRESH_RATE, &fps) == 0) {
829     frame_rate = (fps != 0) ? RoundToStandardFPS(fps) : layer->frame_rate;
830     has_metadata_refresh_rate_ = true;
831   }
832 
833   int32_t interlaced = 0;
834   getMetaData(handle, GET_PP_PARAM_INTERLACED, &interlaced);
835   bool interlace = interlaced ? true : false;
836 
837   if (interlace != layer_buffer->flags.interlace) {
838     DLOGI("Layer buffer interlaced metadata has changed. old=%d, new=%d",
839           layer_buffer->flags.interlace, interlace);
840   }
841 
842   uint32_t linear_format = 0;
843   if (getMetaData(handle, GET_LINEAR_FORMAT, &linear_format) == 0) {
844     layer_buffer->format = GetSDMFormat(INT32(linear_format), 0);
845   }
846 
847   uint32_t s3d = 0;
848   LayerBufferS3DFormat s3d_format = layer_buffer->s3d_format;
849   if (getMetaData(handle, GET_S3D_FORMAT, &s3d) == 0) {
850     s3d_format = GetS3DFormat(s3d);
851   }
852 
853   if ((layer_igc != layer_buffer->igc) || (interlace != layer_buffer->flags.interlace) ||
854       (frame_rate != layer->frame_rate) || (s3d_format != layer_buffer->s3d_format)) {
855     // Layer buffer metadata has changed.
856     layer_buffer->igc = layer_igc;
857     layer->frame_rate = frame_rate;
858     layer_buffer->s3d_format = s3d_format;
859     layer_buffer->flags.interlace = interlace;
860     layer_->update_mask.set(kMetadataUpdate);
861   }
862 
863   // Check if metadata is set
864   struct UBWCStats cr_stats[NUM_UBWC_CR_STATS_LAYERS] = {};
865 
866   for (int i = 0; i < NUM_UBWC_CR_STATS_LAYERS; i++) {
867     layer_buffer->ubwc_crstats[i].clear();
868   }
869 
870   if (getMetaData(handle, GET_UBWC_CR_STATS_INFO, cr_stats) == 0) {
871   // Only copy top layer for now as only top field for interlaced is used
872     GetUBWCStatsFromMetaData(&cr_stats[0], &(layer_buffer->ubwc_crstats[0]));
873   }  // if (getMetaData)
874 
875   uint32_t single_buffer = 0;
876   getMetaData(const_cast<private_handle_t *>(handle), GET_SINGLE_BUFFER_MODE, &single_buffer);
877   single_buffer_ = (single_buffer == 1);
878 
879   // Handle colorMetaData / Dataspace handling now
880   ValidateAndSetCSC(handle);
881 
882   return kErrorNone;
883 }
884 
SetIGC(IGC_t source,LayerIGC * target)885 DisplayError HWCLayer::SetIGC(IGC_t source, LayerIGC *target) {
886   switch (source) {
887     case IGC_NotSpecified:
888       *target = kIGCNotSpecified;
889       break;
890     case IGC_sRGB:
891       *target = kIGCsRGB;
892       break;
893     default:
894       DLOGE("Unsupported IGC: %d", source);
895       return kErrorNotSupported;
896   }
897 
898   return kErrorNone;
899 }
900 
IsDataSpaceSupported()901 bool HWCLayer::IsDataSpaceSupported() {
902   if (client_requested_ != HWC2::Composition::Device &&
903       client_requested_ != HWC2::Composition::Cursor) {
904     // Layers marked for GPU can have any dataspace
905     return true;
906   }
907 
908   return dataspace_supported_;
909 }
910 
ValidateAndSetCSC(const private_handle_t * handle)911 void HWCLayer::ValidateAndSetCSC(const private_handle_t *handle) {
912   LayerBuffer *layer_buffer = &layer_->input_buffer;
913   bool use_color_metadata = true;
914   ColorMetaData csc = {};
915   if (dataspace_ != HAL_DATASPACE_UNKNOWN) {
916     use_color_metadata = false;
917     bool valid_csc = GetSDMColorSpace(dataspace_, &csc);
918     if (!valid_csc) {
919       dataspace_supported_ = false;
920       return;
921     }
922 
923     if (layer_buffer->color_metadata.transfer != csc.transfer ||
924        layer_buffer->color_metadata.colorPrimaries != csc.colorPrimaries ||
925        layer_buffer->color_metadata.range != csc.range) {
926         // ColorMetadata updated. Needs validate.
927         layer_->update_mask.set(kMetadataUpdate);
928         // if we are here here, update the sdm layer csc.
929         layer_buffer->color_metadata.transfer = csc.transfer;
930         layer_buffer->color_metadata.colorPrimaries = csc.colorPrimaries;
931         layer_buffer->color_metadata.range = csc.range;
932     }
933   }
934 
935   // Only Video module populates the Color Metadata in handle.
936   if (layer_buffer->flags.video && IsBT2020(layer_buffer->color_metadata.colorPrimaries)) {
937      // android_dataspace_t doesnt support mastering display and light levels
938      // so retrieve it from metadata for BT2020(HDR)
939      use_color_metadata = true;
940   }
941 
942   if (use_color_metadata) {
943     ColorMetaData old_meta_data = layer_buffer->color_metadata;
944     if (sdm::SetCSC(handle, &layer_buffer->color_metadata) == kErrorNone) {
945       if ((layer_buffer->color_metadata.colorPrimaries != old_meta_data.colorPrimaries) ||
946           (layer_buffer->color_metadata.transfer != old_meta_data.transfer) ||
947           (layer_buffer->color_metadata.range != old_meta_data.range)) {
948         layer_->update_mask.set(kMetadataUpdate);
949       }
950       if (layer_buffer->color_metadata.dynamicMetaDataValid &&
951           !SameConfig(layer_buffer->color_metadata.dynamicMetaDataPayload,
952           old_meta_data.dynamicMetaDataPayload, HDR_DYNAMIC_META_DATA_SZ)) {
953         layer_->update_mask.set(kMetadataUpdate);
954       }
955     } else {
956       dataspace_supported_ = false;
957       return;
958     }
959   }
960 
961   dataspace_supported_ = true;
962 }
963 
964 
RoundToStandardFPS(float fps)965 uint32_t HWCLayer::RoundToStandardFPS(float fps) {
966   static const uint32_t standard_fps[4] = {24, 30, 48, 60};
967   uint32_t frame_rate = (uint32_t)(fps);
968 
969   int count = INT(sizeof(standard_fps) / sizeof(standard_fps[0]));
970   for (int i = 0; i < count; i++) {
971     if ((standard_fps[i] - frame_rate) < 2) {
972       // Most likely used for video, the fps can fluctuate
973       // Ex: b/w 29 and 30 for 30 fps clip
974       return standard_fps[i];
975     }
976   }
977 
978   return frame_rate;
979 }
980 
SetComposition(const LayerComposition & sdm_composition)981 void HWCLayer::SetComposition(const LayerComposition &sdm_composition) {
982   auto hwc_composition = HWC2::Composition::Invalid;
983   switch (sdm_composition) {
984     case kCompositionGPU:
985       hwc_composition = HWC2::Composition::Client;
986       break;
987     case kCompositionCursor:
988       hwc_composition = HWC2::Composition::Cursor;
989       break;
990     default:
991       hwc_composition = HWC2::Composition::Device;
992       break;
993   }
994   // Update solid fill composition
995   if (sdm_composition == kCompositionSDE && layer_->flags.solid_fill != 0) {
996     hwc_composition = HWC2::Composition::SolidColor;
997   }
998   device_selected_ = hwc_composition;
999 
1000   return;
1001 }
1002 
PushBackReleaseFence(int32_t fence)1003 void HWCLayer::PushBackReleaseFence(int32_t fence) {
1004   release_fences_.push_back(fence);
1005 }
1006 
PopBackReleaseFence()1007 int32_t HWCLayer::PopBackReleaseFence() {
1008   if (release_fences_.empty())
1009     return -1;
1010 
1011   auto fence = release_fences_.back();
1012   release_fences_.pop_back();
1013 
1014   return fence;
1015 }
1016 
PopFrontReleaseFence()1017 int32_t HWCLayer::PopFrontReleaseFence() {
1018   if (release_fences_.empty())
1019     return -1;
1020 
1021   auto fence = release_fences_.front();
1022   release_fences_.pop_front();
1023 
1024   return fence;
1025 }
1026 
IsRotationPresent()1027 bool HWCLayer::IsRotationPresent() {
1028   return ((layer_->transform.rotation != 0.0f) ||
1029          layer_->transform.flip_horizontal ||
1030          layer_->transform.flip_vertical);
1031 }
1032 
IsScalingPresent()1033 bool HWCLayer::IsScalingPresent() {
1034   uint32_t src_width  = static_cast<uint32_t>(layer_->src_rect.right - layer_->src_rect.left);
1035   uint32_t src_height = static_cast<uint32_t>(layer_->src_rect.bottom - layer_->src_rect.top);
1036   uint32_t dst_width  = static_cast<uint32_t>(layer_->dst_rect.right - layer_->dst_rect.left);
1037   uint32_t dst_height = static_cast<uint32_t>(layer_->dst_rect.bottom - layer_->dst_rect.top);
1038 
1039   return ((src_width != dst_width) || (dst_height != src_height));
1040 }
1041 
SetDirtyRegions(hwc_region_t surface_damage)1042 void HWCLayer::SetDirtyRegions(hwc_region_t surface_damage) {
1043   layer_->dirty_regions.clear();
1044   for (uint32_t i = 0; i < surface_damage.numRects; i++) {
1045     LayerRect rect;
1046     SetRect(surface_damage.rects[i], &rect);
1047     layer_->dirty_regions.push_back(rect);
1048   }
1049 }
1050 
SetLayerAsMask()1051 void HWCLayer::SetLayerAsMask() {
1052   layer_->input_buffer.flags.mask_layer = true;
1053   DLOGV_IF(kTagClient, " Layer Id: ""[%" PRIu64 "]", id_);
1054 }
1055 
1056 }  // namespace sdm
1057