1 /*
2 * Copyright (c) 2014 - 2016, The Linux Foundation. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *     * Redistributions of source code must retain the above copyright
8 *       notice, this list of conditions and the following disclaimer.
9 *     * Redistributions in binary form must reproduce the above
10 *       copyright notice, this list of conditions and the following
11 *       disclaimer in the documentation and/or other materials provided
12 *       with the distribution.
13 *     * Neither the name of The Linux Foundation nor the names of its
14 *       contributors may be used to endorse or promote products derived
15 *       from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29 
30 #include <math.h>
31 #include <errno.h>
32 #include <gralloc_priv.h>
33 #include <gr.h>
34 #include <utils/constants.h>
35 #include <utils/rect.h>
36 #include <utils/debug.h>
37 #include <sync/sync.h>
38 #include <cutils/properties.h>
39 #include <map>
40 #include <utility>
41 
42 #include "hwc_display.h"
43 #include "hwc_debugger.h"
44 #include "blit_engine_c2d.h"
45 
46 #ifdef QTI_BSP
47 #include <hardware/display_defs.h>
48 #endif
49 
50 #define __CLASS__ "HWCDisplay"
51 
52 namespace sdm {
53 
AssignLayerRegionsAddress(LayerRectArray * region,uint32_t rect_count,uint8_t ** base_address)54 static void AssignLayerRegionsAddress(LayerRectArray *region, uint32_t rect_count,
55                                       uint8_t **base_address) {
56   if (rect_count) {
57     region->rect = reinterpret_cast<LayerRect *>(*base_address);
58     for (uint32_t i = 0; i < rect_count; i++) {
59       region->rect[i] = LayerRect();
60     }
61     *base_address += rect_count * sizeof(LayerRect);
62   }
63   region->count = rect_count;
64 }
65 
ApplyDeInterlaceAdjustment(Layer * layer)66 static void ApplyDeInterlaceAdjustment(Layer *layer) {
67   // De-interlacing adjustment
68   if (layer->input_buffer->flags.interlace) {
69     float height = (layer->src_rect.bottom - layer->src_rect.top) / 2.0f;
70     layer->src_rect.top = ROUND_UP_ALIGN_DOWN(layer->src_rect.top / 2.0f, 2);
71     layer->src_rect.bottom = layer->src_rect.top + floorf(height);
72   }
73 }
74 
HWCDisplay(CoreInterface * core_intf,hwc_procs_t const ** hwc_procs,DisplayType type,int id,bool needs_blit)75 HWCDisplay::HWCDisplay(CoreInterface *core_intf, hwc_procs_t const **hwc_procs, DisplayType type,
76                        int id, bool needs_blit)
77   : core_intf_(core_intf), hwc_procs_(hwc_procs), type_(type), id_(id), needs_blit_(needs_blit) {
78 }
79 
Init()80 int HWCDisplay::Init() {
81   DisplayError error = core_intf_->CreateDisplay(type_, this, &display_intf_);
82   if (error != kErrorNone) {
83     DLOGE("Display create failed. Error = %d display_type %d event_handler %p disp_intf %p",
84       error, type_, this, &display_intf_);
85     return -EINVAL;
86   }
87 
88   int property_swap_interval = 1;
89   HWCDebugHandler::Get()->GetProperty("debug.egl.swapinterval", &property_swap_interval);
90   if (property_swap_interval == 0) {
91     swap_interval_zero_ = true;
92   }
93 
94   framebuffer_config_ = new DisplayConfigVariableInfo();
95   if (!framebuffer_config_) {
96     DLOGV("Failed to allocate memory for custom framebuffer config.");
97     core_intf_->DestroyDisplay(display_intf_);
98     return -EINVAL;
99   }
100 
101   if (needs_blit_) {
102     blit_engine_ = new BlitEngineC2d();
103     if (!blit_engine_) {
104       DLOGI("Create Blit Engine C2D failed");
105     } else {
106       if (blit_engine_->Init() < 0) {
107         DLOGI("Blit Engine Init failed, Blit Composition will not be used!!");
108         delete blit_engine_;
109         blit_engine_ = NULL;
110       }
111     }
112   }
113 
114   display_intf_->GetRefreshRateRange(&min_refresh_rate_, &max_refresh_rate_);
115   current_refresh_rate_ = max_refresh_rate_;
116 
117   s3d_format_hwc_to_sdm_.insert(std::pair<int, LayerBufferS3DFormat>(HAL_NO_3D, kS3dFormatNone));
118   s3d_format_hwc_to_sdm_.insert(std::pair<int, LayerBufferS3DFormat>(HAL_3D_SIDE_BY_SIDE_L_R,
119                                 kS3dFormatLeftRight));
120   s3d_format_hwc_to_sdm_.insert(std::pair<int, LayerBufferS3DFormat>(HAL_3D_SIDE_BY_SIDE_R_L,
121                                 kS3dFormatRightLeft));
122   s3d_format_hwc_to_sdm_.insert(std::pair<int, LayerBufferS3DFormat>(HAL_3D_TOP_BOTTOM,
123                                 kS3dFormatTopBottom));
124 
125   return 0;
126 }
127 
Deinit()128 int HWCDisplay::Deinit() {
129   DisplayError error = core_intf_->DestroyDisplay(display_intf_);
130   if (error != kErrorNone) {
131     DLOGE("Display destroy failed. Error = %d", error);
132     return -EINVAL;
133   }
134 
135   if (layer_stack_memory_.raw) {
136     delete[] layer_stack_memory_.raw;
137     layer_stack_memory_.raw = NULL;
138   }
139 
140   delete framebuffer_config_;
141 
142   if (blit_engine_) {
143     blit_engine_->DeInit();
144     delete blit_engine_;
145     blit_engine_ = NULL;
146   }
147 
148   return 0;
149 }
150 
EventControl(int event,int enable)151 int HWCDisplay::EventControl(int event, int enable) {
152   DisplayError error = kErrorNone;
153 
154   if (shutdown_pending_) {
155     return 0;
156   }
157 
158   switch (event) {
159   case HWC_EVENT_VSYNC:
160     error = display_intf_->SetVSyncState(enable);
161     break;
162   default:
163     DLOGW("Unsupported event = %d", event);
164   }
165 
166   if (error != kErrorNone) {
167     if (error == kErrorShutDown) {
168       shutdown_pending_ = true;
169       return 0;
170     }
171     DLOGE("Failed. event = %d, enable = %d, error = %d", event, enable, error);
172     return -EINVAL;
173   }
174 
175   return 0;
176 }
177 
SetPowerMode(int mode)178 int HWCDisplay::SetPowerMode(int mode) {
179   DLOGI("display = %d, mode = %d", id_, mode);
180   DisplayState state = kStateOff;
181   bool flush_on_error = flush_on_error_;
182 
183   if (shutdown_pending_) {
184     return 0;
185   }
186 
187   switch (mode) {
188   case HWC_POWER_MODE_OFF:
189     // During power off, all of the buffers are released.
190     // Do not flush until a buffer is successfully submitted again.
191     flush_on_error = false;
192     state = kStateOff;
193     break;
194 
195   case HWC_POWER_MODE_NORMAL:
196     state = kStateOn;
197     last_power_mode_ = HWC_POWER_MODE_NORMAL;
198     break;
199 
200   case HWC_POWER_MODE_DOZE:
201     state = kStateDoze;
202     last_power_mode_ = HWC_POWER_MODE_DOZE;
203     break;
204 
205   case HWC_POWER_MODE_DOZE_SUSPEND:
206     state = kStateDozeSuspend;
207     last_power_mode_ = HWC_POWER_MODE_DOZE_SUSPEND;
208     break;
209 
210   default:
211     return -EINVAL;
212   }
213 
214   DisplayError error = display_intf_->SetDisplayState(state);
215   if (error == kErrorNone) {
216     flush_on_error_ = flush_on_error;
217   } else {
218     if (error == kErrorShutDown) {
219       shutdown_pending_ = true;
220       return 0;
221     }
222     DLOGE("Set state failed. Error = %d", error);
223     return -EINVAL;
224   }
225 
226   return 0;
227 }
228 
GetDisplayConfigs(uint32_t * configs,size_t * num_configs)229 int HWCDisplay::GetDisplayConfigs(uint32_t *configs, size_t *num_configs) {
230   if (*num_configs > 0) {
231     configs[0] = 0;
232     *num_configs = 1;
233   }
234 
235   return 0;
236 }
237 
GetDisplayAttributes(uint32_t config,const uint32_t * attributes,int32_t * values)238 int HWCDisplay::GetDisplayAttributes(uint32_t config, const uint32_t *attributes, int32_t *values) {
239   DisplayConfigVariableInfo variable_config = *framebuffer_config_;
240 
241   for (int i = 0; attributes[i] != HWC_DISPLAY_NO_ATTRIBUTE; i++) {
242     switch (attributes[i]) {
243     case HWC_DISPLAY_VSYNC_PERIOD:
244       values[i] = INT32(variable_config.vsync_period_ns);
245       break;
246     case HWC_DISPLAY_WIDTH:
247       values[i] = INT32(variable_config.x_pixels);
248       break;
249     case HWC_DISPLAY_HEIGHT:
250       values[i] = INT32(variable_config.y_pixels);
251       break;
252     case HWC_DISPLAY_DPI_X:
253       values[i] = INT32(variable_config.x_dpi * 1000.0f);
254       break;
255     case HWC_DISPLAY_DPI_Y:
256       values[i] = INT32(variable_config.y_dpi * 1000.0f);
257       break;
258     default:
259       DLOGW("Spurious attribute type = %d", attributes[i]);
260       return -EINVAL;
261     }
262   }
263 
264   return 0;
265 }
266 
GetActiveConfig()267 int HWCDisplay::GetActiveConfig() {
268   return 0;
269 }
270 
SetActiveConfig(int index)271 int HWCDisplay::SetActiveConfig(int index) {
272   return -1;
273 }
274 
SetFrameDumpConfig(uint32_t count,uint32_t bit_mask_layer_type)275 void HWCDisplay::SetFrameDumpConfig(uint32_t count, uint32_t bit_mask_layer_type) {
276   dump_frame_count_ = count;
277   dump_frame_index_ = 0;
278   dump_input_layers_ = ((bit_mask_layer_type & (1 << INPUT_LAYER_DUMP)) != 0);
279 
280   if (blit_engine_) {
281     blit_engine_->SetFrameDumpConfig(count);
282   }
283 
284   DLOGI("num_frame_dump %d, input_layer_dump_enable %d", dump_frame_count_, dump_input_layers_);
285 }
286 
GetLastPowerMode()287 uint32_t HWCDisplay::GetLastPowerMode() {
288   return last_power_mode_;
289 }
290 
VSync(const DisplayEventVSync & vsync)291 DisplayError HWCDisplay::VSync(const DisplayEventVSync &vsync) {
292   const hwc_procs_t *hwc_procs = *hwc_procs_;
293 
294   if (!hwc_procs) {
295     return kErrorParameters;
296   }
297 
298   hwc_procs->vsync(hwc_procs, id_, vsync.timestamp);
299 
300   return kErrorNone;
301 }
302 
Refresh()303 DisplayError HWCDisplay::Refresh() {
304   return kErrorNotSupported;
305 }
306 
AllocateLayerStack(hwc_display_contents_1_t * content_list)307 int HWCDisplay::AllocateLayerStack(hwc_display_contents_1_t *content_list) {
308   if (!content_list || !content_list->numHwLayers) {
309     DLOGW("Invalid content list");
310     return -EINVAL;
311   }
312 
313   size_t num_hw_layers = content_list->numHwLayers;
314   uint32_t blit_target_count = 0;
315 
316   if (needs_blit_ && blit_engine_) {
317     blit_target_count = kMaxBlitTargetLayers;
318   }
319 
320   // Allocate memory for
321   //  a) total number of layers
322   //  b) buffer handle for each layer
323   //  c) number of visible rectangles in each layer
324   //  d) number of dirty rectangles in each layer
325   //  e) number of blit rectangles in each layer
326   size_t required_size = (num_hw_layers + blit_target_count) *
327                          (sizeof(Layer) + sizeof(LayerBuffer));
328 
329   for (size_t i = 0; i < num_hw_layers + blit_target_count; i++) {
330     uint32_t num_visible_rects = 0;
331     uint32_t num_dirty_rects = 0;
332 
333     if (i < num_hw_layers) {
334       hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
335       num_visible_rects = UINT32(hwc_layer.visibleRegionScreen.numRects);
336       num_dirty_rects = UINT32(hwc_layer.surfaceDamage.numRects);
337     }
338 
339     // visible rectangles + dirty rectangles + blit rectangle
340     size_t num_rects = num_visible_rects + num_dirty_rects + blit_target_count;
341     required_size += num_rects * sizeof(LayerRect);
342   }
343 
344   // Layer array may be large enough to hold current number of layers.
345   // If not, re-allocate it now.
346   if (layer_stack_memory_.size < required_size) {
347     if (layer_stack_memory_.raw) {
348       delete[] layer_stack_memory_.raw;
349       layer_stack_memory_.size = 0;
350     }
351 
352     // Allocate in multiple of kSizeSteps.
353     required_size = ROUND_UP(required_size, layer_stack_memory_.kSizeSteps);
354     layer_stack_memory_.raw = new uint8_t[required_size];
355     if (!layer_stack_memory_.raw) {
356       return -ENOMEM;
357     }
358 
359     layer_stack_memory_.size = required_size;
360   }
361 
362   // Assign memory addresses now.
363   uint8_t *current_address = layer_stack_memory_.raw;
364 
365   // Layer array address
366   layer_stack_ = LayerStack();
367   layer_stack_.layers = reinterpret_cast<Layer *>(current_address);
368   layer_stack_.layer_count = UINT32(num_hw_layers + blit_target_count);
369   current_address += (num_hw_layers + blit_target_count) * sizeof(Layer);
370 
371   for (size_t i = 0; i < num_hw_layers + blit_target_count; i++) {
372     uint32_t num_visible_rects = 0;
373     uint32_t num_dirty_rects = 0;
374 
375     if (i < num_hw_layers) {
376       hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
377       num_visible_rects = UINT32(hwc_layer.visibleRegionScreen.numRects);
378       num_dirty_rects = UINT32(hwc_layer.surfaceDamage.numRects);
379     }
380 
381     Layer &layer = layer_stack_.layers[i];
382     layer = Layer();
383 
384     // Layer buffer handle address
385     layer.input_buffer = reinterpret_cast<LayerBuffer *>(current_address);
386     *layer.input_buffer = LayerBuffer();
387     current_address += sizeof(LayerBuffer);
388 
389     // Visible/Dirty/Blit rectangle address
390     AssignLayerRegionsAddress(&layer.visible_regions, num_visible_rects, &current_address);
391     AssignLayerRegionsAddress(&layer.dirty_regions, num_dirty_rects, &current_address);
392     AssignLayerRegionsAddress(&layer.blit_regions, blit_target_count, &current_address);
393   }
394 
395   return 0;
396 }
397 
PrepareLayerParams(hwc_layer_1_t * hwc_layer,Layer * layer)398 int HWCDisplay::PrepareLayerParams(hwc_layer_1_t *hwc_layer, Layer *layer) {
399   const private_handle_t *pvt_handle = static_cast<const private_handle_t *>(hwc_layer->handle);
400 
401   LayerBuffer *layer_buffer = layer->input_buffer;
402 
403   if (pvt_handle) {
404     layer_buffer->format = GetSDMFormat(pvt_handle->format, pvt_handle->flags);
405     layer_buffer->width = UINT32(pvt_handle->width);
406     layer_buffer->height = UINT32(pvt_handle->height);
407 
408     if (SetMetaData(pvt_handle, layer) != kErrorNone) {
409       return -EINVAL;
410     }
411 
412     if (pvt_handle->bufferType == BUFFER_TYPE_VIDEO) {
413       layer_stack_.flags.video_present = true;
414       layer_buffer->flags.video = true;
415     }
416     // TZ Protected Buffer - L1
417     if (pvt_handle->flags & private_handle_t::PRIV_FLAGS_SECURE_BUFFER) {
418       layer_stack_.flags.secure_present = true;
419       layer_buffer->flags.secure = true;
420     }
421     // Gralloc Usage Protected Buffer - L3 - which needs to be treated as Secure & avoid fallback
422     if (pvt_handle->flags & private_handle_t::PRIV_FLAGS_PROTECTED_BUFFER) {
423       layer_stack_.flags.secure_present = true;
424     }
425     if (pvt_handle->flags & private_handle_t::PRIV_FLAGS_SECURE_DISPLAY) {
426       layer_buffer->flags.secure_display = true;
427     }
428 
429     // check if this is special solid_fill layer without input_buffer.
430     if (solid_fill_enable_ && pvt_handle->fd == -1) {
431       layer->flags.solid_fill = true;
432       layer->solid_fill_color = solid_fill_color_;
433     }
434   } else {
435     // for FBT layer
436     if (hwc_layer->compositionType == HWC_FRAMEBUFFER_TARGET) {
437       uint32_t x_pixels;
438       uint32_t y_pixels;
439       int aligned_width;
440       int aligned_height;
441       int usage = GRALLOC_USAGE_HW_FB;
442       int format = HAL_PIXEL_FORMAT_RGBA_8888;
443       int ubwc_enabled = 0;
444       int flags = 0;
445       HWCDebugHandler::Get()->GetProperty("debug.gralloc.enable_fb_ubwc", &ubwc_enabled);
446       if (ubwc_enabled == 1) {
447         usage |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
448         flags |= private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
449       }
450 
451       GetFrameBufferResolution(&x_pixels, &y_pixels);
452 
453       AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(INT(x_pixels), INT(y_pixels), format,
454                                                             usage, aligned_width, aligned_height);
455       layer_buffer->width = UINT32(aligned_width);
456       layer_buffer->height = UINT32(aligned_height);
457       layer_buffer->format = GetSDMFormat(format, flags);
458     }
459   }
460 
461   return 0;
462 }
463 
CommitLayerParams(hwc_layer_1_t * hwc_layer,Layer * layer)464 void HWCDisplay::CommitLayerParams(hwc_layer_1_t *hwc_layer, Layer *layer) {
465   const private_handle_t *pvt_handle = static_cast<const private_handle_t *>(hwc_layer->handle);
466   LayerBuffer *layer_buffer = layer->input_buffer;
467 
468   if (pvt_handle) {
469     layer_buffer->planes[0].fd = pvt_handle->fd;
470     layer_buffer->planes[0].offset = pvt_handle->offset;
471     layer_buffer->planes[0].stride = UINT32(pvt_handle->width);
472     layer_buffer->size = pvt_handle->size;
473   }
474 
475   // if swapinterval property is set to 0 then close and reset the acquireFd
476   if (swap_interval_zero_ && hwc_layer->acquireFenceFd >= 0) {
477     close(hwc_layer->acquireFenceFd);
478     hwc_layer->acquireFenceFd = -1;
479   }
480   layer_buffer->acquire_fence_fd = hwc_layer->acquireFenceFd;
481 }
482 
PrePrepareLayerStack(hwc_display_contents_1_t * content_list)483 int HWCDisplay::PrePrepareLayerStack(hwc_display_contents_1_t *content_list) {
484   if (shutdown_pending_) {
485     return 0;
486   }
487 
488   size_t num_hw_layers = content_list->numHwLayers;
489 
490   use_blit_comp_ = false;
491   metadata_refresh_rate_ = 0;
492   display_rect_ = LayerRect();
493 
494   // Configure each layer
495   for (size_t i = 0; i < num_hw_layers; i++) {
496     hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
497 
498     Layer &layer = layer_stack_.layers[i];
499 
500     int ret = PrepareLayerParams(&content_list->hwLayers[i], &layer_stack_.layers[i]);
501 
502     if (ret != kErrorNone) {
503       return ret;
504     }
505 
506     layer.flags.skip = ((hwc_layer.flags & HWC_SKIP_LAYER) > 0);
507     layer.flags.solid_fill = (hwc_layer.flags & kDimLayer) || solid_fill_enable_;
508     if (layer.flags.skip || layer.flags.solid_fill) {
509       layer.dirty_regions.count = 0;
510     }
511 
512     hwc_rect_t scaled_display_frame = hwc_layer.displayFrame;
513     ScaleDisplayFrame(&scaled_display_frame);
514     ApplyScanAdjustment(&scaled_display_frame);
515 
516     SetRect(scaled_display_frame, &layer.dst_rect);
517     SetRect(hwc_layer.sourceCropf, &layer.src_rect);
518     ApplyDeInterlaceAdjustment(&layer);
519 
520     for (uint32_t j = 0; j < layer.visible_regions.count; j++) {
521       SetRect(hwc_layer.visibleRegionScreen.rects[j], &layer.visible_regions.rect[j]);
522     }
523     for (uint32_t j = 0; j < layer.dirty_regions.count; j++) {
524       SetRect(hwc_layer.surfaceDamage.rects[j], &layer.dirty_regions.rect[j]);
525     }
526     SetComposition(hwc_layer.compositionType, &layer.composition);
527 
528     if (hwc_layer.compositionType != HWC_FRAMEBUFFER_TARGET) {
529       display_rect_ = Union(display_rect_, layer.dst_rect);
530     }
531 
532 
533     // For dim layers, SurfaceFlinger
534     //    - converts planeAlpha to per pixel alpha,
535     //    - sets RGB color to 000,
536     //    - sets planeAlpha to 0xff,
537     //    - blending to Premultiplied.
538     // This can be achieved at hardware by
539     //    - solid fill ARGB to 0xff000000,
540     //    - incoming planeAlpha,
541     //    - blending to Coverage.
542     if (hwc_layer.flags & kDimLayer) {
543       layer.input_buffer->format = kFormatARGB8888;
544       layer.solid_fill_color = 0xff000000;
545       SetBlending(HWC_BLENDING_COVERAGE, &layer.blending);
546     } else {
547       SetBlending(hwc_layer.blending, &layer.blending);
548       LayerTransform &layer_transform = layer.transform;
549       uint32_t &hwc_transform = hwc_layer.transform;
550       layer_transform.flip_horizontal = ((hwc_transform & HWC_TRANSFORM_FLIP_H) > 0);
551       layer_transform.flip_vertical = ((hwc_transform & HWC_TRANSFORM_FLIP_V) > 0);
552       layer_transform.rotation = ((hwc_transform & HWC_TRANSFORM_ROT_90) ? 90.0f : 0.0f);
553     }
554 
555     // TODO(user): Remove below block.
556     // For solid fill, only dest rect need to be specified.
557     if (layer.flags.solid_fill) {
558       LayerBuffer *input_buffer = layer.input_buffer;
559       input_buffer->width = UINT32(layer.dst_rect.right - layer.dst_rect.left);
560       input_buffer->height = UINT32(layer.dst_rect.bottom - layer.dst_rect.top);
561       layer.src_rect.left = 0;
562       layer.src_rect.top = 0;
563       layer.src_rect.right = input_buffer->width;
564       layer.src_rect.bottom = input_buffer->height;
565     }
566 
567     layer.plane_alpha = hwc_layer.planeAlpha;
568     layer.flags.cursor = ((hwc_layer.flags & HWC_IS_CURSOR_LAYER) > 0);
569     layer.flags.updating = true;
570 
571     if (num_hw_layers <= kMaxLayerCount) {
572       layer.flags.updating = IsLayerUpdating(content_list, INT32(i));
573     }
574 #ifdef QTI_BSP
575     if (hwc_layer.flags & HWC_SCREENSHOT_ANIMATOR_LAYER) {
576       layer_stack_.flags.animating = true;
577     }
578 #endif
579     if (layer.flags.skip) {
580       layer_stack_.flags.skip_present = true;
581     }
582 
583     if (layer.flags.cursor) {
584       layer_stack_.flags.cursor_present = true;
585     }
586 
587     if (layer.frame_rate > metadata_refresh_rate_) {
588       metadata_refresh_rate_ = SanitizeRefreshRate(layer.frame_rate);
589     } else {
590       layer.frame_rate = current_refresh_rate_;
591     }
592 
593     layer.input_buffer->buffer_id = reinterpret_cast<uint64_t>(hwc_layer.handle);
594   }
595 
596   // Prepare the Blit Target
597   if (blit_engine_) {
598     int ret = blit_engine_->Prepare(&layer_stack_);
599     if (ret) {
600       // Blit engine cannot handle this layer stack, hence set the layer stack
601       // count to num_hw_layers
602       layer_stack_.layer_count -= kMaxBlitTargetLayers;
603     } else {
604       use_blit_comp_ = true;
605     }
606   }
607 
608   // Configure layer stack
609   layer_stack_.flags.geometry_changed = ((content_list->flags & HWC_GEOMETRY_CHANGED) > 0);
610 
611   return 0;
612 }
613 
PrepareLayerStack(hwc_display_contents_1_t * content_list)614 int HWCDisplay::PrepareLayerStack(hwc_display_contents_1_t *content_list) {
615   if (shutdown_pending_) {
616     return 0;
617   }
618 
619   size_t num_hw_layers = content_list->numHwLayers;
620 
621   if (!skip_prepare_) {
622     DisplayError error = display_intf_->Prepare(&layer_stack_);
623     if (error != kErrorNone) {
624       if (error == kErrorShutDown) {
625         shutdown_pending_ = true;
626       } else if (error != kErrorPermission) {
627         DLOGE("Prepare failed. Error = %d", error);
628         // To prevent surfaceflinger infinite wait, flush the previous frame during Commit()
629         // so that previous buffer and fences are released, and override the error.
630         flush_ = true;
631       }
632 
633       return 0;
634     }
635   } else {
636     // Skip is not set
637     MarkLayersForGPUBypass(content_list);
638     skip_prepare_ = false;
639     DLOGI("SecureDisplay %s, Skip Prepare/Commit and Flush", secure_display_active_ ? "Starting" :
640           "Stopping");
641     flush_ = true;
642   }
643 
644   // If current draw cycle has different set of layers updating in comparison to previous cycle,
645   // cache content using GPU again.
646   // If set of updating layers remains same, use cached buffer and replace layers marked for GPU
647   // composition with SDE so that SurfaceFlinger does not compose them. Set cache inuse here.
648   bool needs_fb_refresh = NeedsFrameBufferRefresh(content_list);
649   layer_stack_cache_.in_use = false;
650 
651   for (size_t i = 0; i < num_hw_layers; i++) {
652     hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
653     Layer &layer = layer_stack_.layers[i];
654     LayerComposition composition = layer.composition;
655 
656     if ((composition == kCompositionSDE) || (composition == kCompositionHybrid) ||
657         (composition == kCompositionBlit)) {
658       hwc_layer.hints |= HWC_HINT_CLEAR_FB;
659     }
660 
661     if (!needs_fb_refresh && composition == kCompositionGPU) {
662       composition = kCompositionSDE;
663       layer_stack_cache_.in_use = true;
664     }
665     SetComposition(composition, &hwc_layer.compositionType);
666   }
667 
668   CacheLayerStackInfo(content_list);
669 
670   return 0;
671 }
672 
CommitLayerStack(hwc_display_contents_1_t * content_list)673 int HWCDisplay::CommitLayerStack(hwc_display_contents_1_t *content_list) {
674   if (!content_list || !content_list->numHwLayers) {
675     DLOGW("Invalid content list");
676     return -EINVAL;
677   }
678 
679   if (shutdown_pending_) {
680     return 0;
681   }
682 
683   int status = 0;
684 
685   size_t num_hw_layers = content_list->numHwLayers;
686 
687   DumpInputBuffers(content_list);
688 
689   if (!flush_) {
690     for (size_t i = 0; i < num_hw_layers; i++) {
691       CommitLayerParams(&content_list->hwLayers[i], &layer_stack_.layers[i]);
692     }
693 
694     if (use_blit_comp_) {
695       status = blit_engine_->PreCommit(content_list, &layer_stack_);
696       if (status == 0) {
697         status = blit_engine_->Commit(content_list, &layer_stack_);
698         if (status != 0) {
699           DLOGE("Blit Comp Failed!");
700         }
701       }
702     }
703 
704     DisplayError error = kErrorUndefined;
705     if (status == 0) {
706       error = display_intf_->Commit(&layer_stack_);
707       status = 0;
708     }
709 
710     if (error == kErrorNone) {
711       // A commit is successfully submitted, start flushing on failure now onwards.
712       flush_on_error_ = true;
713     } else {
714       if (error == kErrorShutDown) {
715         shutdown_pending_ = true;
716         return status;
717       } else if (error != kErrorPermission) {
718         DLOGE("Commit failed. Error = %d", error);
719         // To prevent surfaceflinger infinite wait, flush the previous frame during Commit()
720         // so that previous buffer and fences are released, and override the error.
721         flush_ = true;
722       }
723     }
724   }
725 
726   return status;
727 }
728 
PostCommitLayerStack(hwc_display_contents_1_t * content_list)729 int HWCDisplay::PostCommitLayerStack(hwc_display_contents_1_t *content_list) {
730   size_t num_hw_layers = content_list->numHwLayers;
731   int status = 0;
732 
733   // Do no call flush on errors, if a successful buffer is never submitted.
734   if (flush_ && flush_on_error_) {
735     display_intf_->Flush();
736   }
737 
738   // Set the release fence fd to the blit engine
739   if (use_blit_comp_ && blit_engine_->BlitActive()) {
740     blit_engine_->PostCommit(&layer_stack_);
741   }
742 
743   for (size_t i = 0; i < num_hw_layers; i++) {
744     hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
745     Layer &layer = layer_stack_.layers[i];
746     LayerBuffer *layer_buffer = layer_stack_.layers[i].input_buffer;
747 
748     if (!flush_) {
749       // If swapinterval property is set to 0 or for single buffer layers, do not update f/w
750       // release fences and discard fences from driver
751       if (swap_interval_zero_ || layer.flags.single_buffer) {
752         hwc_layer.releaseFenceFd = -1;
753         close(layer_buffer->release_fence_fd);
754         layer_buffer->release_fence_fd = -1;
755       } else if (layer.composition != kCompositionGPU) {
756         hwc_layer.releaseFenceFd = layer_buffer->release_fence_fd;
757       }
758 
759       // During animation on external/virtual display, SDM will use the cached
760       // framebuffer layer throughout animation and do not allow framework to do eglswapbuffer on
761       // framebuffer target. So graphics doesn't close the release fence fd of framebuffer target,
762       // Hence close the release fencefd of framebuffer target here.
763       if (layer.composition == kCompositionGPUTarget && layer_stack_cache_.animating) {
764         close(hwc_layer.releaseFenceFd);
765         hwc_layer.releaseFenceFd = -1;
766       }
767     }
768 
769     if (hwc_layer.acquireFenceFd >= 0) {
770       close(hwc_layer.acquireFenceFd);
771       hwc_layer.acquireFenceFd = -1;
772     }
773   }
774 
775   if (!flush_) {
776     layer_stack_cache_.animating = layer_stack_.flags.animating;
777 
778     // if swapinterval property is set to 0 then close and reset the list retire fence
779     if (swap_interval_zero_) {
780       close(layer_stack_.retire_fence_fd);
781       layer_stack_.retire_fence_fd = -1;
782     }
783     content_list->retireFenceFd = layer_stack_.retire_fence_fd;
784 
785     if (dump_frame_count_) {
786       dump_frame_count_--;
787       dump_frame_index_++;
788     }
789   }
790 
791   flush_ = false;
792 
793   return status;
794 }
795 
796 
NeedsFrameBufferRefresh(hwc_display_contents_1_t * content_list)797 bool HWCDisplay::NeedsFrameBufferRefresh(hwc_display_contents_1_t *content_list) {
798   uint32_t layer_count = layer_stack_.layer_count;
799 
800   // Handle ongoing animation and end here, start is handled below
801   if (layer_stack_cache_.animating) {
802       if (!layer_stack_.flags.animating) {
803         // Animation is ending.
804         return true;
805       } else {
806         // Animation is going on.
807         return false;
808       }
809   }
810 
811   // Frame buffer needs to be refreshed for the following reasons:
812   // 1. Any layer is marked skip in the current layer stack.
813   // 2. Any layer is added/removed/layer properties changes in the current layer stack.
814   // 3. Any layer handle is changed and it is marked for GPU composition
815   // 4. Any layer's current composition is different from previous composition.
816   if (layer_stack_.flags.skip_present || layer_stack_.flags.geometry_changed) {
817     return true;
818   }
819 
820   for (uint32_t i = 0; i < layer_count; i++) {
821     Layer &layer = layer_stack_.layers[i];
822     LayerCache &layer_cache = layer_stack_cache_.layer_cache[i];
823 
824     // need FB refresh for s3d case
825     if (layer.input_buffer->s3d_format != kS3dFormatNone) {
826         return true;
827     }
828 
829     if (layer.composition == kCompositionGPUTarget) {
830       continue;
831     }
832 
833     if (layer_cache.composition != layer.composition) {
834       return true;
835     }
836 
837     if ((layer.composition == kCompositionGPU) && IsLayerUpdating(content_list, INT32(i))) {
838       return true;
839     }
840   }
841 
842   return false;
843 }
844 
IsLayerUpdating(hwc_display_contents_1_t * content_list,int layer_index)845 bool HWCDisplay::IsLayerUpdating(hwc_display_contents_1_t *content_list, int layer_index) {
846   hwc_layer_1_t &hwc_layer = content_list->hwLayers[layer_index];
847   LayerCache &layer_cache = layer_stack_cache_.layer_cache[layer_index];
848 
849   const private_handle_t *pvt_handle = static_cast<const private_handle_t *>(hwc_layer.handle);
850   const MetaData_t *meta_data = pvt_handle ?
851     reinterpret_cast<MetaData_t *>(pvt_handle->base_metadata) : NULL;
852 
853   // Layer should be considered updating if
854   //   a) layer is in single buffer mode, or
855   //   b) layer handle has changed, or
856   //   c) layer plane alpha has changed, or
857   //   d) layer stack geometry has changed
858   return ((meta_data && (meta_data->operation & SET_SINGLE_BUFFER_MODE) &&
859               meta_data->isSingleBufferMode) ||
860           (layer_cache.handle != hwc_layer.handle) ||
861           (layer_cache.plane_alpha != hwc_layer.planeAlpha) ||
862           (content_list->flags & HWC_GEOMETRY_CHANGED));
863 }
864 
CacheLayerStackInfo(hwc_display_contents_1_t * content_list)865 void HWCDisplay::CacheLayerStackInfo(hwc_display_contents_1_t *content_list) {
866   uint32_t layer_count = layer_stack_.layer_count;
867 
868   if (layer_count > kMaxLayerCount || layer_stack_.flags.animating) {
869     ResetLayerCacheStack();
870     return;
871   }
872 
873   for (uint32_t i = 0; i < layer_count; i++) {
874     Layer &layer = layer_stack_.layers[i];
875     if (layer.composition == kCompositionGPUTarget ||
876         layer.composition == kCompositionBlitTarget) {
877       continue;
878     }
879 
880     LayerCache &layer_cache = layer_stack_cache_.layer_cache[i];
881     layer_cache.handle = content_list->hwLayers[i].handle;
882     layer_cache.plane_alpha = content_list->hwLayers[i].planeAlpha;
883     layer_cache.composition = layer.composition;
884   }
885 
886   layer_stack_cache_.layer_count = layer_count;
887 }
888 
SetRect(const hwc_rect_t & source,LayerRect * target)889 void HWCDisplay::SetRect(const hwc_rect_t &source, LayerRect *target) {
890   target->left = FLOAT(source.left);
891   target->top = FLOAT(source.top);
892   target->right = FLOAT(source.right);
893   target->bottom = FLOAT(source.bottom);
894 }
895 
SetRect(const hwc_frect_t & source,LayerRect * target)896 void HWCDisplay::SetRect(const hwc_frect_t &source, LayerRect *target) {
897   target->left = floorf(source.left);
898   target->top = floorf(source.top);
899   target->right = ceilf(source.right);
900   target->bottom = ceilf(source.bottom);
901 }
902 
SetComposition(const int32_t & source,LayerComposition * target)903 void HWCDisplay::SetComposition(const int32_t &source, LayerComposition *target) {
904   switch (source) {
905   case HWC_FRAMEBUFFER_TARGET:  *target = kCompositionGPUTarget;  break;
906   default:                      *target = kCompositionGPU;        break;
907   }
908 }
909 
SetComposition(const LayerComposition & source,int32_t * target)910 void HWCDisplay::SetComposition(const LayerComposition &source, int32_t *target) {
911   switch (source) {
912   case kCompositionGPUTarget:   *target = HWC_FRAMEBUFFER_TARGET; break;
913   case kCompositionGPU:         *target = HWC_FRAMEBUFFER;        break;
914   case kCompositionHWCursor:    *target = HWC_CURSOR_OVERLAY;     break;
915   default:                      *target = HWC_OVERLAY;            break;
916   }
917 }
918 
SetBlending(const int32_t & source,LayerBlending * target)919 void HWCDisplay::SetBlending(const int32_t &source, LayerBlending *target) {
920   switch (source) {
921   case HWC_BLENDING_PREMULT:    *target = kBlendingPremultiplied;   break;
922   case HWC_BLENDING_COVERAGE:   *target = kBlendingCoverage;        break;
923   default:                      *target = kBlendingOpaque;          break;
924   }
925 }
926 
SetIdleTimeoutMs(uint32_t timeout_ms)927 void HWCDisplay::SetIdleTimeoutMs(uint32_t timeout_ms) {
928   return;
929 }
930 
SetMaxMixerStages(uint32_t max_mixer_stages)931 DisplayError HWCDisplay::SetMaxMixerStages(uint32_t max_mixer_stages) {
932   DisplayError error = kErrorNone;
933 
934   if (display_intf_) {
935     error = display_intf_->SetMaxMixerStages(max_mixer_stages);
936   }
937 
938   return error;
939 }
940 
ControlPartialUpdate(bool enable,uint32_t * pending)941 DisplayError HWCDisplay::ControlPartialUpdate(bool enable, uint32_t *pending) {
942   DisplayError error = kErrorNone;
943 
944   if (display_intf_) {
945     error = display_intf_->ControlPartialUpdate(enable, pending);
946   }
947 
948   return error;
949 }
950 
GetSDMFormat(const int32_t & source,const int flags)951 LayerBufferFormat HWCDisplay::GetSDMFormat(const int32_t &source, const int flags) {
952   LayerBufferFormat format = kFormatInvalid;
953   if (flags & private_handle_t::PRIV_FLAGS_UBWC_ALIGNED) {
954     switch (source) {
955     case HAL_PIXEL_FORMAT_RGBA_8888:           format = kFormatRGBA8888Ubwc;            break;
956     case HAL_PIXEL_FORMAT_RGBX_8888:           format = kFormatRGBX8888Ubwc;            break;
957     case HAL_PIXEL_FORMAT_BGR_565:             format = kFormatBGR565Ubwc;              break;
958     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
959     case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
960     case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:     format = kFormatYCbCr420SPVenusUbwc;     break;
961     case HAL_PIXEL_FORMAT_RGBA_1010102:        format = kFormatRGBA1010102Ubwc;         break;
962     case HAL_PIXEL_FORMAT_RGBX_1010102:        format = kFormatRGBX1010102Ubwc;         break;
963     case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC: format = kFormatYCbCr420TP10Ubwc;        break;
964     default:
965       DLOGE("Unsupported format type for UBWC %d", source);
966       return kFormatInvalid;
967     }
968     return format;
969   }
970 
971   switch (source) {
972   case HAL_PIXEL_FORMAT_RGBA_8888:                format = kFormatRGBA8888;                 break;
973   case HAL_PIXEL_FORMAT_RGBA_5551:                format = kFormatRGBA5551;                 break;
974   case HAL_PIXEL_FORMAT_RGBA_4444:                format = kFormatRGBA4444;                 break;
975   case HAL_PIXEL_FORMAT_BGRA_8888:                format = kFormatBGRA8888;                 break;
976   case HAL_PIXEL_FORMAT_RGBX_8888:                format = kFormatRGBX8888;                 break;
977   case HAL_PIXEL_FORMAT_BGRX_8888:                format = kFormatBGRX8888;                 break;
978   case HAL_PIXEL_FORMAT_RGB_888:                  format = kFormatRGB888;                   break;
979   case HAL_PIXEL_FORMAT_RGB_565:                  format = kFormatRGB565;                   break;
980   case HAL_PIXEL_FORMAT_BGR_565:                  format = kFormatBGR565;                   break;
981   case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
982   case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:       format = kFormatYCbCr420SemiPlanarVenus;  break;
983   case HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS:       format = kFormatYCrCb420SemiPlanarVenus;  break;
984   case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:  format = kFormatYCbCr420SPVenusUbwc;      break;
985   case HAL_PIXEL_FORMAT_YV12:                     format = kFormatYCrCb420PlanarStride16;   break;
986   case HAL_PIXEL_FORMAT_YCrCb_420_SP:             format = kFormatYCrCb420SemiPlanar;       break;
987   case HAL_PIXEL_FORMAT_YCbCr_420_SP:             format = kFormatYCbCr420SemiPlanar;       break;
988   case HAL_PIXEL_FORMAT_YCbCr_422_SP:             format = kFormatYCbCr422H2V1SemiPlanar;   break;
989   case HAL_PIXEL_FORMAT_YCbCr_422_I:              format = kFormatYCbCr422H2V1Packed;       break;
990   case HAL_PIXEL_FORMAT_RGBA_1010102:             format = kFormatRGBA1010102;              break;
991   case HAL_PIXEL_FORMAT_ARGB_2101010:             format = kFormatARGB2101010;              break;
992   case HAL_PIXEL_FORMAT_RGBX_1010102:             format = kFormatRGBX1010102;              break;
993   case HAL_PIXEL_FORMAT_XRGB_2101010:             format = kFormatXRGB2101010;              break;
994   case HAL_PIXEL_FORMAT_BGRA_1010102:             format = kFormatBGRA1010102;              break;
995   case HAL_PIXEL_FORMAT_ABGR_2101010:             format = kFormatABGR2101010;              break;
996   case HAL_PIXEL_FORMAT_BGRX_1010102:             format = kFormatBGRX1010102;              break;
997   case HAL_PIXEL_FORMAT_XBGR_2101010:             format = kFormatXBGR2101010;              break;
998   case HAL_PIXEL_FORMAT_YCbCr_420_P010:           format = kFormatYCbCr420P010;             break;
999   case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC:      format = kFormatYCbCr420TP10Ubwc;         break;
1000   default:
1001     DLOGW("Unsupported format type = %d", source);
1002     return kFormatInvalid;
1003   }
1004 
1005   return format;
1006 }
1007 
DumpInputBuffers(hwc_display_contents_1_t * content_list)1008 void HWCDisplay::DumpInputBuffers(hwc_display_contents_1_t *content_list) {
1009   size_t num_hw_layers = content_list->numHwLayers;
1010   char dir_path[PATH_MAX];
1011 
1012   if (!dump_frame_count_ || flush_ || !dump_input_layers_) {
1013     return;
1014   }
1015 
1016   snprintf(dir_path, sizeof(dir_path), "/data/misc/display/frame_dump_%s", GetDisplayString());
1017 
1018   if (mkdir(dir_path, 0777) != 0 && errno != EEXIST) {
1019     DLOGW("Failed to create %s directory errno = %d, desc = %s", dir_path, errno, strerror(errno));
1020     return;
1021   }
1022 
1023   // if directory exists already, need to explicitly change the permission.
1024   if (errno == EEXIST && chmod(dir_path, 0777) != 0) {
1025     DLOGW("Failed to change permissions on %s directory", dir_path);
1026     return;
1027   }
1028 
1029   for (uint32_t i = 0; i < num_hw_layers; i++) {
1030     hwc_layer_1_t &hwc_layer = content_list->hwLayers[i];
1031     const private_handle_t *pvt_handle = static_cast<const private_handle_t *>(hwc_layer.handle);
1032 
1033     if (hwc_layer.acquireFenceFd >= 0) {
1034       int error = sync_wait(hwc_layer.acquireFenceFd, 1000);
1035       if (error < 0) {
1036         DLOGW("sync_wait error errno = %d, desc = %s", errno, strerror(errno));
1037         return;
1038       }
1039     }
1040 
1041     if (pvt_handle && pvt_handle->base) {
1042       char dump_file_name[PATH_MAX];
1043       size_t result = 0;
1044 
1045       snprintf(dump_file_name, sizeof(dump_file_name), "%s/input_layer%d_%dx%d_%s_frame%d.raw",
1046                dir_path, i, pvt_handle->width, pvt_handle->height,
1047                GetHALPixelFormatString(pvt_handle->format), dump_frame_index_);
1048 
1049       FILE* fp = fopen(dump_file_name, "w+");
1050       if (fp) {
1051         result = fwrite(reinterpret_cast<void *>(pvt_handle->base), pvt_handle->size, 1, fp);
1052         fclose(fp);
1053       }
1054 
1055       DLOGI("Frame Dump %s: is %s", dump_file_name, result ? "Successful" : "Failed");
1056     }
1057   }
1058 }
1059 
GetHALPixelFormatString(int format)1060 const char *HWCDisplay::GetHALPixelFormatString(int format) {
1061   switch (format) {
1062   case HAL_PIXEL_FORMAT_RGBA_8888:
1063     return "RGBA_8888";
1064   case HAL_PIXEL_FORMAT_RGBX_8888:
1065     return "RGBX_8888";
1066   case HAL_PIXEL_FORMAT_RGB_888:
1067     return "RGB_888";
1068   case HAL_PIXEL_FORMAT_RGB_565:
1069     return "RGB_565";
1070   case HAL_PIXEL_FORMAT_BGR_565:
1071     return "BGR_565";
1072   case HAL_PIXEL_FORMAT_BGRA_8888:
1073     return "BGRA_8888";
1074   case HAL_PIXEL_FORMAT_RGBA_5551:
1075     return "RGBA_5551";
1076   case HAL_PIXEL_FORMAT_RGBA_4444:
1077     return "RGBA_4444";
1078   case HAL_PIXEL_FORMAT_YV12:
1079     return "YV12";
1080   case HAL_PIXEL_FORMAT_YCbCr_422_SP:
1081     return "YCbCr_422_SP_NV16";
1082   case HAL_PIXEL_FORMAT_YCrCb_420_SP:
1083     return "YCrCb_420_SP_NV21";
1084   case HAL_PIXEL_FORMAT_YCbCr_422_I:
1085     return "YCbCr_422_I_YUY2";
1086   case HAL_PIXEL_FORMAT_YCrCb_422_I:
1087     return "YCrCb_422_I_YVYU";
1088   case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
1089     return "NV12_ENCODEABLE";
1090   case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED:
1091     return "YCbCr_420_SP_TILED_TILE_4x2";
1092   case HAL_PIXEL_FORMAT_YCbCr_420_SP:
1093     return "YCbCr_420_SP";
1094   case HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO:
1095     return "YCrCb_420_SP_ADRENO";
1096   case HAL_PIXEL_FORMAT_YCrCb_422_SP:
1097     return "YCrCb_422_SP";
1098   case HAL_PIXEL_FORMAT_R_8:
1099     return "R_8";
1100   case HAL_PIXEL_FORMAT_RG_88:
1101     return "RG_88";
1102   case HAL_PIXEL_FORMAT_INTERLACE:
1103     return "INTERLACE";
1104   case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
1105     return "YCbCr_420_SP_VENUS";
1106   case HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS:
1107     return "YCrCb_420_SP_VENUS";
1108   case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC:
1109     return "YCbCr_420_SP_VENUS_UBWC";
1110   case HAL_PIXEL_FORMAT_RGBA_1010102:
1111     return "RGBA_1010102";
1112   case HAL_PIXEL_FORMAT_ARGB_2101010:
1113     return "ARGB_2101010";
1114   case HAL_PIXEL_FORMAT_RGBX_1010102:
1115     return "RGBX_1010102";
1116   case HAL_PIXEL_FORMAT_XRGB_2101010:
1117     return "XRGB_2101010";
1118   case HAL_PIXEL_FORMAT_BGRA_1010102:
1119     return "BGRA_1010102";
1120   case HAL_PIXEL_FORMAT_ABGR_2101010:
1121     return "ABGR_2101010";
1122   case HAL_PIXEL_FORMAT_BGRX_1010102:
1123     return "BGRX_1010102";
1124   case HAL_PIXEL_FORMAT_XBGR_2101010:
1125     return "XBGR_2101010";
1126   case HAL_PIXEL_FORMAT_YCbCr_420_P010:
1127     return "YCbCr_420_P010";
1128   case HAL_PIXEL_FORMAT_YCbCr_420_TP10_UBWC:
1129     return "YCbCr_420_TP10_UBWC";
1130   default:
1131     return "Unknown pixel format";
1132   }
1133 }
1134 
GetDisplayString()1135 const char *HWCDisplay::GetDisplayString() {
1136   switch (type_) {
1137   case kPrimary:
1138     return "primary";
1139   case kHDMI:
1140     return "hdmi";
1141   case kVirtual:
1142     return "virtual";
1143   default:
1144     return "invalid";
1145   }
1146 }
1147 
SetFrameBufferResolution(uint32_t x_pixels,uint32_t y_pixels)1148 int HWCDisplay::SetFrameBufferResolution(uint32_t x_pixels, uint32_t y_pixels) {
1149   if (x_pixels <= 0 || y_pixels <= 0) {
1150     DLOGV("Unsupported config: x_pixels=%d, y_pixels=%d", x_pixels, y_pixels);
1151     return -EINVAL;
1152   }
1153 
1154   if (framebuffer_config_->x_pixels == x_pixels && framebuffer_config_->y_pixels == y_pixels) {
1155     return 0;
1156   }
1157 
1158   DisplayConfigVariableInfo active_config;
1159   uint32_t active_config_index = 0;
1160   display_intf_->GetActiveConfig(&active_config_index);
1161   DisplayError error = display_intf_->GetConfig(active_config_index, &active_config);
1162   if (error != kErrorNone) {
1163     DLOGV("GetConfig variable info failed. Error = %d", error);
1164     return -EINVAL;
1165   }
1166 
1167   if (active_config.x_pixels <= 0 || active_config.y_pixels <= 0) {
1168     DLOGV("Invalid panel resolution (%dx%d)", active_config.x_pixels, active_config.y_pixels);
1169     return -EINVAL;
1170   }
1171 
1172   // Create rects to represent the new source and destination crops
1173   LayerRect crop = LayerRect(0, 0, FLOAT(x_pixels), FLOAT(y_pixels));
1174   LayerRect dst = LayerRect(0, 0, FLOAT(active_config.x_pixels), FLOAT(active_config.y_pixels));
1175   // Set rotate90 to false since this is taken care of during regular composition.
1176   bool rotate90 = false;
1177   error = display_intf_->IsScalingValid(crop, dst, rotate90);
1178   if (error != kErrorNone) {
1179     DLOGV("Unsupported resolution: (%dx%d)", x_pixels, y_pixels);
1180     return -EINVAL;
1181   }
1182 
1183   framebuffer_config_->x_pixels = x_pixels;
1184   framebuffer_config_->y_pixels = y_pixels;
1185   framebuffer_config_->vsync_period_ns = active_config.vsync_period_ns;
1186   framebuffer_config_->x_dpi = active_config.x_dpi;
1187   framebuffer_config_->y_dpi = active_config.y_dpi;
1188 
1189   DLOGI("New framebuffer resolution (%dx%d)", framebuffer_config_->x_pixels,
1190         framebuffer_config_->y_pixels);
1191 
1192   return 0;
1193 }
1194 
GetFrameBufferResolution(uint32_t * x_pixels,uint32_t * y_pixels)1195 void HWCDisplay::GetFrameBufferResolution(uint32_t *x_pixels, uint32_t *y_pixels) {
1196   *x_pixels = framebuffer_config_->x_pixels;
1197   *y_pixels = framebuffer_config_->y_pixels;
1198 }
1199 
ScaleDisplayFrame(hwc_rect_t * display_frame)1200 void HWCDisplay::ScaleDisplayFrame(hwc_rect_t *display_frame) {
1201   if (!IsFrameBufferScaled()) {
1202     return;
1203   }
1204 
1205   uint32_t active_config_index = 0;
1206   display_intf_->GetActiveConfig(&active_config_index);
1207   DisplayConfigVariableInfo active_config;
1208   DisplayError error = display_intf_->GetConfig(active_config_index, &active_config);
1209   if (error != kErrorNone) {
1210     DLOGE("GetConfig variable info failed. Error = %d", error);
1211     return;
1212   }
1213 
1214   float custom_x_pixels = FLOAT(framebuffer_config_->x_pixels);
1215   float custom_y_pixels = FLOAT(framebuffer_config_->y_pixels);
1216   float active_x_pixels = FLOAT(active_config.x_pixels);
1217   float active_y_pixels = FLOAT(active_config.y_pixels);
1218   float x_pixels_ratio = active_x_pixels / custom_x_pixels;
1219   float y_pixels_ratio = active_y_pixels / custom_y_pixels;
1220   float layer_width = FLOAT(display_frame->right - display_frame->left);
1221   float layer_height = FLOAT(display_frame->bottom - display_frame->top);
1222 
1223   display_frame->left = INT(x_pixels_ratio * FLOAT(display_frame->left));
1224   display_frame->top = INT(y_pixels_ratio * FLOAT(display_frame->top));
1225   display_frame->right = INT(FLOAT(display_frame->left) + layer_width * x_pixels_ratio);
1226   display_frame->bottom = INT(FLOAT(display_frame->top) + layer_height * y_pixels_ratio);
1227 }
1228 
IsFrameBufferScaled()1229 bool HWCDisplay::IsFrameBufferScaled() {
1230   if (framebuffer_config_->x_pixels == 0 || framebuffer_config_->y_pixels == 0) {
1231     return false;
1232   }
1233   uint32_t panel_x_pixels = 0;
1234   uint32_t panel_y_pixels = 0;
1235   GetPanelResolution(&panel_x_pixels, &panel_y_pixels);
1236   return (framebuffer_config_->x_pixels != panel_x_pixels) ||
1237           (framebuffer_config_->y_pixels != panel_y_pixels);
1238 }
1239 
GetPanelResolution(uint32_t * x_pixels,uint32_t * y_pixels)1240 void HWCDisplay::GetPanelResolution(uint32_t *x_pixels, uint32_t *y_pixels) {
1241   DisplayConfigVariableInfo active_config;
1242   uint32_t active_config_index = 0;
1243   display_intf_->GetActiveConfig(&active_config_index);
1244   DisplayError error = display_intf_->GetConfig(active_config_index, &active_config);
1245   if (error != kErrorNone) {
1246     DLOGE("GetConfig variable info failed. Error = %d", error);
1247     return;
1248   }
1249   *x_pixels = active_config.x_pixels;
1250   *y_pixels = active_config.y_pixels;
1251 }
1252 
SetDisplayStatus(uint32_t display_status)1253 int HWCDisplay::SetDisplayStatus(uint32_t display_status) {
1254   int status = 0;
1255   const hwc_procs_t *hwc_procs = *hwc_procs_;
1256 
1257   switch (display_status) {
1258   case kDisplayStatusResume:
1259     display_paused_ = false;
1260   case kDisplayStatusOnline:
1261     status = SetPowerMode(HWC_POWER_MODE_NORMAL);
1262     break;
1263   case kDisplayStatusPause:
1264     display_paused_ = true;
1265   case kDisplayStatusOffline:
1266     status = SetPowerMode(HWC_POWER_MODE_OFF);
1267     break;
1268   default:
1269     DLOGW("Invalid display status %d", display_status);
1270     return -EINVAL;
1271   }
1272 
1273   if (display_status == kDisplayStatusResume ||
1274       display_status == kDisplayStatusPause) {
1275     hwc_procs->invalidate(hwc_procs);
1276   }
1277 
1278   return status;
1279 }
1280 
SetCursorPosition(int x,int y)1281 int HWCDisplay::SetCursorPosition(int x, int y) {
1282   DisplayError error = kErrorNone;
1283 
1284   if (shutdown_pending_) {
1285     return 0;
1286   }
1287 
1288   error = display_intf_->SetCursorPosition(x, y);
1289   if (error != kErrorNone) {
1290     if (error == kErrorShutDown) {
1291       shutdown_pending_ = true;
1292       return 0;
1293     }
1294     DLOGE("Failed for x = %d y = %d, Error = %d", x, y, error);
1295     return -1;
1296   }
1297 
1298   return 0;
1299 }
1300 
OnMinHdcpEncryptionLevelChange(uint32_t min_enc_level)1301 int HWCDisplay::OnMinHdcpEncryptionLevelChange(uint32_t min_enc_level) {
1302   DisplayError error = display_intf_->OnMinHdcpEncryptionLevelChange(min_enc_level);
1303   if (error != kErrorNone) {
1304     DLOGE("Failed. Error = %d", error);
1305     return -1;
1306   }
1307 
1308   return 0;
1309 }
1310 
MarkLayersForGPUBypass(hwc_display_contents_1_t * content_list)1311 void HWCDisplay::MarkLayersForGPUBypass(hwc_display_contents_1_t *content_list) {
1312   for (size_t i = 0 ; i < (content_list->numHwLayers - 1); i++) {
1313     hwc_layer_1_t *layer = &content_list->hwLayers[i];
1314     layer->compositionType = HWC_OVERLAY;
1315   }
1316 }
1317 
RoundToStandardFPS(uint32_t fps)1318 uint32_t HWCDisplay::RoundToStandardFPS(uint32_t fps) {
1319   static const uint32_t standard_fps[4] = {30, 24, 48, 60};
1320 
1321   int count = INT(sizeof(standard_fps) / sizeof(standard_fps[0]));
1322   for (int i = 0; i < count; i++) {
1323     if ((standard_fps[i] - fps) < 2) {
1324       // Most likely used for video, the fps can fluctuate
1325       // Ex: b/w 29 and 30 for 30 fps clip
1326       return standard_fps[i];
1327     }
1328   }
1329 
1330   return fps;
1331 }
1332 
ApplyScanAdjustment(hwc_rect_t * display_frame)1333 void HWCDisplay::ApplyScanAdjustment(hwc_rect_t *display_frame) {
1334 }
1335 
SetCSC(ColorSpace_t source,LayerCSC * target)1336 DisplayError HWCDisplay::SetCSC(ColorSpace_t source, LayerCSC *target) {
1337   switch (source) {
1338   case ITU_R_601:       *target = kCSCLimitedRange601;   break;
1339   case ITU_R_601_FR:    *target = kCSCFullRange601;      break;
1340   case ITU_R_709:       *target = kCSCLimitedRange709;   break;
1341   default:
1342     DLOGE("Unsupported CSC: %d", source);
1343     return kErrorNotSupported;
1344   }
1345 
1346   return kErrorNone;
1347 }
1348 
SetIGC(IGC_t source,LayerIGC * target)1349 DisplayError HWCDisplay::SetIGC(IGC_t source, LayerIGC *target) {
1350   switch (source) {
1351   case IGC_NotSpecified:    *target = kIGCNotSpecified; break;
1352   case IGC_sRGB:            *target = kIGCsRGB;   break;
1353   default:
1354     DLOGE("Unsupported IGC: %d", source);
1355     return kErrorNotSupported;
1356   }
1357 
1358   return kErrorNone;
1359 }
1360 
SetMetaData(const private_handle_t * pvt_handle,Layer * layer)1361 DisplayError HWCDisplay::SetMetaData(const private_handle_t *pvt_handle, Layer *layer) {
1362   const MetaData_t *meta_data = reinterpret_cast<MetaData_t *>(pvt_handle->base_metadata);
1363   LayerBuffer *layer_buffer = layer->input_buffer;
1364 
1365   if (!meta_data) {
1366     return kErrorNone;
1367   }
1368 
1369   if (meta_data->operation & UPDATE_COLOR_SPACE) {
1370     if (SetCSC(meta_data->colorSpace, &layer->csc) != kErrorNone) {
1371       return kErrorNotSupported;
1372     }
1373   }
1374 
1375   if (meta_data->operation & SET_IGC) {
1376     if (SetIGC(meta_data->igc, &layer->igc) != kErrorNone) {
1377       return kErrorNotSupported;
1378     }
1379   }
1380 
1381   if (meta_data->operation & UPDATE_REFRESH_RATE) {
1382     layer->frame_rate = RoundToStandardFPS(meta_data->refreshrate);
1383   }
1384 
1385   if ((meta_data->operation & PP_PARAM_INTERLACED) && meta_data->interlaced) {
1386     layer_buffer->flags.interlace = true;
1387   }
1388 
1389   if (meta_data->operation & LINEAR_FORMAT) {
1390     layer_buffer->format = GetSDMFormat(INT32(meta_data->linearFormat), 0);
1391   }
1392 
1393   if (meta_data->operation & UPDATE_BUFFER_GEOMETRY) {
1394     int actual_width = pvt_handle->width;
1395     int actual_height = pvt_handle->height;
1396     AdrenoMemInfo::getInstance().getAlignedWidthAndHeight(pvt_handle, actual_width, actual_height);
1397     layer_buffer->width = UINT32(actual_width);
1398     layer_buffer->height = UINT32(actual_height);
1399   }
1400 
1401   if (meta_data->operation & SET_SINGLE_BUFFER_MODE) {
1402     layer->flags.single_buffer = meta_data->isSingleBufferMode;
1403     // Graphics can set this operation on all types of layers including FB and set the actual value
1404     // to 0. To protect against SET operations of 0 value, we need to do a logical OR.
1405     layer_stack_.flags.single_buffered_layer_present |= meta_data->isSingleBufferMode;
1406   }
1407 
1408   if (meta_data->operation & S3D_FORMAT) {
1409     std::map<int, LayerBufferS3DFormat>::iterator it =
1410         s3d_format_hwc_to_sdm_.find(INT32(meta_data->s3dFormat));
1411     if (it != s3d_format_hwc_to_sdm_.end()) {
1412       layer->input_buffer->s3d_format = it->second;
1413     } else {
1414       DLOGW("Invalid S3D format %d", meta_data->s3dFormat);
1415     }
1416   }
1417 
1418   return kErrorNone;
1419 }
1420 
SetPanelBrightness(int level)1421 int HWCDisplay::SetPanelBrightness(int level) {
1422   int ret = 0;
1423   if (display_intf_)
1424     ret = display_intf_->SetPanelBrightness(level);
1425   else
1426     ret = -EINVAL;
1427 
1428   return ret;
1429 }
1430 
GetPanelBrightness(int * level)1431 int HWCDisplay::GetPanelBrightness(int *level) {
1432   return display_intf_->GetPanelBrightness(level);
1433 }
1434 
ToggleScreenUpdates(bool enable)1435 int HWCDisplay::ToggleScreenUpdates(bool enable) {
1436   const hwc_procs_t *hwc_procs = *hwc_procs_;
1437   display_paused_ = enable ? false : true;
1438   hwc_procs->invalidate(hwc_procs);
1439   return 0;
1440 }
1441 
ColorSVCRequestRoute(const PPDisplayAPIPayload & in_payload,PPDisplayAPIPayload * out_payload,PPPendingParams * pending_action)1442 int HWCDisplay::ColorSVCRequestRoute(const PPDisplayAPIPayload &in_payload,
1443                                      PPDisplayAPIPayload *out_payload,
1444                                      PPPendingParams *pending_action) {
1445   int ret = 0;
1446 
1447   if (display_intf_)
1448     ret = display_intf_->ColorSVCRequestRoute(in_payload, out_payload, pending_action);
1449   else
1450     ret = -EINVAL;
1451 
1452   return ret;
1453 }
1454 
GetVisibleDisplayRect(hwc_rect_t * visible_rect)1455 int HWCDisplay::GetVisibleDisplayRect(hwc_rect_t* visible_rect) {
1456   if (!IsValid(display_rect_)) {
1457     return -EINVAL;
1458   }
1459 
1460   visible_rect->left = INT(display_rect_.left);
1461   visible_rect->top = INT(display_rect_.top);
1462   visible_rect->right = INT(display_rect_.right);
1463   visible_rect->bottom = INT(display_rect_.bottom);
1464   DLOGI("Dpy = %d Visible Display Rect(%d %d %d %d)", visible_rect->left, visible_rect->top,
1465         visible_rect->right, visible_rect->bottom);
1466 
1467   return 0;
1468 }
1469 
ResetLayerCacheStack()1470 void HWCDisplay::ResetLayerCacheStack() {
1471   uint32_t layer_count = layer_stack_cache_.layer_count;
1472   for (uint32_t i = 0; i < layer_count; i++) {
1473     layer_stack_cache_.layer_cache[i] = LayerCache();
1474   }
1475   layer_stack_cache_.layer_count = 0;
1476   layer_stack_cache_.animating = false;
1477   layer_stack_cache_.in_use = false;
1478 }
1479 
SetSecureDisplay(bool secure_display_active)1480 void HWCDisplay::SetSecureDisplay(bool secure_display_active) {
1481   secure_display_active_ = secure_display_active;
1482   return;
1483 }
1484 
SetActiveDisplayConfig(int config)1485 int HWCDisplay::SetActiveDisplayConfig(int config) {
1486   return display_intf_->SetActiveConfig(UINT32(config)) == kErrorNone ? 0 : -1;
1487 }
1488 
GetActiveDisplayConfig(uint32_t * config)1489 int HWCDisplay::GetActiveDisplayConfig(uint32_t *config) {
1490   return display_intf_->GetActiveConfig(config) == kErrorNone ? 0 : -1;
1491 }
1492 
GetDisplayConfigCount(uint32_t * count)1493 int HWCDisplay::GetDisplayConfigCount(uint32_t *count) {
1494   return display_intf_->GetNumVariableInfoConfigs(count) == kErrorNone ? 0 : -1;
1495 }
1496 
GetDisplayAttributesForConfig(int config,DisplayConfigVariableInfo * attributes)1497 int HWCDisplay::GetDisplayAttributesForConfig(int config, DisplayConfigVariableInfo *attributes) {
1498   return display_intf_->GetConfig(UINT32(config), attributes) == kErrorNone ? 0 : -1;
1499 }
1500 
SingleLayerUpdating(uint32_t app_layer_count)1501 bool HWCDisplay::SingleLayerUpdating(uint32_t app_layer_count) {
1502   uint32_t updating_count = 0;
1503 
1504   for (uint i = 0; i < app_layer_count; i++) {
1505     Layer &layer = layer_stack_.layers[i];
1506     if (layer.flags.updating) {
1507       updating_count++;
1508     }
1509   }
1510 
1511   return (updating_count == 1);
1512 }
1513 
SanitizeRefreshRate(uint32_t req_refresh_rate)1514 uint32_t HWCDisplay::SanitizeRefreshRate(uint32_t req_refresh_rate) {
1515   uint32_t refresh_rate = req_refresh_rate;
1516 
1517   if (refresh_rate < min_refresh_rate_) {
1518     // Pick the next multiple of request which is within the range
1519     refresh_rate = (((min_refresh_rate_ / refresh_rate) +
1520                      ((min_refresh_rate_ % refresh_rate) ? 1 : 0)) * refresh_rate);
1521   }
1522 
1523   if (refresh_rate > max_refresh_rate_) {
1524     refresh_rate = max_refresh_rate_;
1525   }
1526 
1527   return refresh_rate;
1528 }
1529 
1530 }  // namespace sdm
1531