1 #include "hardware_composer.h"
2
3 #include <cutils/properties.h>
4 #include <cutils/sched_policy.h>
5 #include <fcntl.h>
6 #include <log/log.h>
7 #include <poll.h>
8 #include <stdint.h>
9 #include <sync/sync.h>
10 #include <sys/eventfd.h>
11 #include <sys/prctl.h>
12 #include <sys/resource.h>
13 #include <sys/system_properties.h>
14 #include <sys/timerfd.h>
15 #include <sys/types.h>
16 #include <time.h>
17 #include <unistd.h>
18 #include <utils/Trace.h>
19
20 #include <algorithm>
21 #include <chrono>
22 #include <functional>
23 #include <map>
24 #include <sstream>
25 #include <string>
26 #include <tuple>
27
28 #include <dvr/dvr_display_types.h>
29 #include <dvr/performance_client_api.h>
30 #include <private/dvr/clock_ns.h>
31 #include <private/dvr/ion_buffer.h>
32
33 using android::hardware::Return;
34 using android::hardware::Void;
35 using android::pdx::ErrorStatus;
36 using android::pdx::LocalHandle;
37 using android::pdx::Status;
38 using android::pdx::rpc::EmptyVariant;
39 using android::pdx::rpc::IfAnyOf;
40
41 using namespace std::chrono_literals;
42
43 namespace android {
44 namespace dvr {
45
46 namespace {
47
48 const char kBacklightBrightnessSysFile[] =
49 "/sys/class/leds/lcd-backlight/brightness";
50
51 const char kDvrPerformanceProperty[] = "sys.dvr.performance";
52 const char kDvrStandaloneProperty[] = "ro.boot.vr";
53
54 const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
55
56 // Get time offset from a vsync to when the pose for that vsync should be
57 // predicted out to. For example, if scanout gets halfway through the frame
58 // at the halfway point between vsyncs, then this could be half the period.
59 // With global shutter displays, this should be changed to the offset to when
60 // illumination begins. Low persistence adds a frame of latency, so we predict
61 // to the center of the next frame.
GetPosePredictionTimeOffset(int64_t vsync_period_ns)62 inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
63 return (vsync_period_ns * 150) / 100;
64 }
65
66 // Attempts to set the scheduler class and partiton for the current thread.
67 // Returns true on success or false on failure.
SetThreadPolicy(const std::string & scheduler_class,const std::string & partition)68 bool SetThreadPolicy(const std::string& scheduler_class,
69 const std::string& partition) {
70 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
71 if (error < 0) {
72 ALOGE(
73 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
74 "thread_id=%d: %s",
75 scheduler_class.c_str(), gettid(), strerror(-error));
76 return false;
77 }
78 error = dvrSetCpuPartition(0, partition.c_str());
79 if (error < 0) {
80 ALOGE(
81 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
82 "%s",
83 partition.c_str(), gettid(), strerror(-error));
84 return false;
85 }
86 return true;
87 }
88
89 // Utility to generate scoped tracers with arguments.
90 // TODO(eieio): Move/merge this into utils/Trace.h?
91 class TraceArgs {
92 public:
93 template <typename... Args>
TraceArgs(const char * format,Args &&...args)94 TraceArgs(const char* format, Args&&... args) {
95 std::array<char, 1024> buffer;
96 snprintf(buffer.data(), buffer.size(), format, std::forward<Args>(args)...);
97 atrace_begin(ATRACE_TAG, buffer.data());
98 }
99
~TraceArgs()100 ~TraceArgs() { atrace_end(ATRACE_TAG); }
101
102 private:
103 TraceArgs(const TraceArgs&) = delete;
104 void operator=(const TraceArgs&) = delete;
105 };
106
107 // Macro to define a scoped tracer with arguments. Uses PASTE(x, y) macro
108 // defined in utils/Trace.h.
109 #define TRACE_FORMAT(format, ...) \
110 TraceArgs PASTE(__tracer, __LINE__) { format, ##__VA_ARGS__ }
111
112 } // anonymous namespace
113
HardwareComposer()114 HardwareComposer::HardwareComposer()
115 : initialized_(false), request_display_callback_(nullptr) {}
116
~HardwareComposer(void)117 HardwareComposer::~HardwareComposer(void) {
118 UpdatePostThreadState(PostThreadState::Quit, true);
119 if (post_thread_.joinable())
120 post_thread_.join();
121 }
122
Initialize(Hwc2::Composer * composer,RequestDisplayCallback request_display_callback)123 bool HardwareComposer::Initialize(
124 Hwc2::Composer* composer, RequestDisplayCallback request_display_callback) {
125 if (initialized_) {
126 ALOGE("HardwareComposer::Initialize: already initialized.");
127 return false;
128 }
129
130 is_standalone_device_ = property_get_bool(kDvrStandaloneProperty, false);
131
132 request_display_callback_ = request_display_callback;
133
134 HWC::Error error = HWC::Error::None;
135
136 Hwc2::Config config;
137 error = composer->getActiveConfig(HWC_DISPLAY_PRIMARY, &config);
138
139 if (error != HWC::Error::None) {
140 ALOGE("HardwareComposer: Failed to get current display config : %d",
141 config);
142 return false;
143 }
144
145 error = GetDisplayMetrics(composer, HWC_DISPLAY_PRIMARY, config,
146 &native_display_metrics_);
147
148 if (error != HWC::Error::None) {
149 ALOGE(
150 "HardwareComposer: Failed to get display attributes for current "
151 "configuration : %d",
152 error.value);
153 return false;
154 }
155
156 ALOGI(
157 "HardwareComposer: primary display attributes: width=%d height=%d "
158 "vsync_period_ns=%d DPI=%dx%d",
159 native_display_metrics_.width, native_display_metrics_.height,
160 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x,
161 native_display_metrics_.dpi.y);
162
163 // Set the display metrics but never use rotation to avoid the long latency of
164 // rotation processing in hwc.
165 display_transform_ = HWC_TRANSFORM_NONE;
166 display_metrics_ = native_display_metrics_;
167
168 // Setup the display metrics used by all Layer instances.
169 Layer::SetDisplayMetrics(native_display_metrics_);
170
171 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
172 LOG_ALWAYS_FATAL_IF(
173 !post_thread_event_fd_,
174 "HardwareComposer: Failed to create interrupt event fd : %s",
175 strerror(errno));
176
177 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
178
179 initialized_ = true;
180
181 return initialized_;
182 }
183
Enable()184 void HardwareComposer::Enable() {
185 UpdatePostThreadState(PostThreadState::Suspended, false);
186 }
187
Disable()188 void HardwareComposer::Disable() {
189 UpdatePostThreadState(PostThreadState::Suspended, true);
190 }
191
192 // Update the post thread quiescent state based on idle and suspended inputs.
UpdatePostThreadState(PostThreadStateType state,bool suspend)193 void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
194 bool suspend) {
195 std::unique_lock<std::mutex> lock(post_thread_mutex_);
196
197 // Update the votes in the state variable before evaluating the effective
198 // quiescent state. Any bits set in post_thread_state_ indicate that the post
199 // thread should be suspended.
200 if (suspend) {
201 post_thread_state_ |= state;
202 } else {
203 post_thread_state_ &= ~state;
204 }
205
206 const bool quit = post_thread_state_ & PostThreadState::Quit;
207 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
208 if (quit) {
209 post_thread_quiescent_ = true;
210 eventfd_write(post_thread_event_fd_.Get(), 1);
211 post_thread_wait_.notify_one();
212 } else if (effective_suspend && !post_thread_quiescent_) {
213 post_thread_quiescent_ = true;
214 eventfd_write(post_thread_event_fd_.Get(), 1);
215 } else if (!effective_suspend && post_thread_quiescent_) {
216 post_thread_quiescent_ = false;
217 eventfd_t value;
218 eventfd_read(post_thread_event_fd_.Get(), &value);
219 post_thread_wait_.notify_one();
220 }
221
222 // Wait until the post thread is in the requested state.
223 post_thread_ready_.wait(lock, [this, effective_suspend] {
224 return effective_suspend != post_thread_resumed_;
225 });
226 }
227
OnPostThreadResumed()228 void HardwareComposer::OnPostThreadResumed() {
229 // Phones create a new composer client on resume and destroy it on pause.
230 // Standalones only create the composer client once and then use SetPowerMode
231 // to control the screen on pause/resume.
232 if (!is_standalone_device_ || !composer_) {
233 composer_.reset(new Hwc2::Composer(false));
234 composer_callback_ = new ComposerCallback;
235 composer_->registerCallback(composer_callback_);
236 Layer::SetComposer(composer_.get());
237 } else {
238 SetPowerMode(true);
239 }
240
241 EnableVsync(true);
242
243 // TODO(skiazyk): We need to do something about accessing this directly,
244 // supposedly there is a backlight service on the way.
245 // TODO(steventhomas): When we change the backlight setting, will surface
246 // flinger (or something else) set it back to its original value once we give
247 // control of the display back to surface flinger?
248 SetBacklightBrightness(255);
249
250 // Trigger target-specific performance mode change.
251 property_set(kDvrPerformanceProperty, "performance");
252 }
253
OnPostThreadPaused()254 void HardwareComposer::OnPostThreadPaused() {
255 retire_fence_fds_.clear();
256 layers_.clear();
257
258 if (composer_) {
259 EnableVsync(false);
260 }
261
262 if (!is_standalone_device_) {
263 composer_callback_ = nullptr;
264 composer_.reset(nullptr);
265 Layer::SetComposer(nullptr);
266 } else {
267 SetPowerMode(false);
268 }
269
270 // Trigger target-specific performance mode change.
271 property_set(kDvrPerformanceProperty, "idle");
272 }
273
Validate(hwc2_display_t display)274 HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
275 uint32_t num_types;
276 uint32_t num_requests;
277 HWC::Error error =
278 composer_->validateDisplay(display, &num_types, &num_requests);
279
280 if (error == HWC2_ERROR_HAS_CHANGES) {
281 // TODO(skiazyk): We might need to inspect the requested changes first, but
282 // so far it seems like we shouldn't ever hit a bad state.
283 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
284 // display);
285 error = composer_->acceptDisplayChanges(display);
286 }
287
288 return error;
289 }
290
EnableVsync(bool enabled)291 HWC::Error HardwareComposer::EnableVsync(bool enabled) {
292 return composer_->setVsyncEnabled(
293 HWC_DISPLAY_PRIMARY,
294 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
295 : HWC2_VSYNC_DISABLE));
296 }
297
SetPowerMode(bool active)298 HWC::Error HardwareComposer::SetPowerMode(bool active) {
299 HWC::PowerMode power_mode = active ? HWC::PowerMode::On : HWC::PowerMode::Off;
300 return composer_->setPowerMode(
301 HWC_DISPLAY_PRIMARY, power_mode.cast<Hwc2::IComposerClient::PowerMode>());
302 }
303
Present(hwc2_display_t display)304 HWC::Error HardwareComposer::Present(hwc2_display_t display) {
305 int32_t present_fence;
306 HWC::Error error = composer_->presentDisplay(display, &present_fence);
307
308 // According to the documentation, this fence is signaled at the time of
309 // vsync/DMA for physical displays.
310 if (error == HWC::Error::None) {
311 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
312 retire_fence_fds_.emplace_back(present_fence);
313 } else {
314 ATRACE_INT("HardwareComposer: PresentResult", error);
315 }
316
317 return error;
318 }
319
GetDisplayAttribute(Hwc2::Composer * composer,hwc2_display_t display,hwc2_config_t config,hwc2_attribute_t attribute,int32_t * out_value) const320 HWC::Error HardwareComposer::GetDisplayAttribute(Hwc2::Composer* composer,
321 hwc2_display_t display,
322 hwc2_config_t config,
323 hwc2_attribute_t attribute,
324 int32_t* out_value) const {
325 return composer->getDisplayAttribute(
326 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
327 }
328
GetDisplayMetrics(Hwc2::Composer * composer,hwc2_display_t display,hwc2_config_t config,HWCDisplayMetrics * out_metrics) const329 HWC::Error HardwareComposer::GetDisplayMetrics(
330 Hwc2::Composer* composer, hwc2_display_t display, hwc2_config_t config,
331 HWCDisplayMetrics* out_metrics) const {
332 HWC::Error error;
333
334 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_WIDTH,
335 &out_metrics->width);
336 if (error != HWC::Error::None) {
337 ALOGE(
338 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
339 error.to_string().c_str());
340 return error;
341 }
342
343 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_HEIGHT,
344 &out_metrics->height);
345 if (error != HWC::Error::None) {
346 ALOGE(
347 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
348 error.to_string().c_str());
349 return error;
350 }
351
352 error = GetDisplayAttribute(composer, display, config,
353 HWC2_ATTRIBUTE_VSYNC_PERIOD,
354 &out_metrics->vsync_period_ns);
355 if (error != HWC::Error::None) {
356 ALOGE(
357 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
358 error.to_string().c_str());
359 return error;
360 }
361
362 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_X,
363 &out_metrics->dpi.x);
364 if (error != HWC::Error::None) {
365 ALOGE(
366 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
367 error.to_string().c_str());
368 return error;
369 }
370
371 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_Y,
372 &out_metrics->dpi.y);
373 if (error != HWC::Error::None) {
374 ALOGE(
375 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
376 error.to_string().c_str());
377 return error;
378 }
379
380 return HWC::Error::None;
381 }
382
Dump()383 std::string HardwareComposer::Dump() {
384 std::unique_lock<std::mutex> lock(post_thread_mutex_);
385 std::ostringstream stream;
386
387 stream << "Display metrics: " << display_metrics_.width << "x"
388 << display_metrics_.height << " " << (display_metrics_.dpi.x / 1000.0)
389 << "x" << (display_metrics_.dpi.y / 1000.0) << " dpi @ "
390 << (1000000000.0 / display_metrics_.vsync_period_ns) << " Hz"
391 << std::endl;
392
393 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
394 stream << "Active layers: " << layers_.size() << std::endl;
395 stream << std::endl;
396
397 for (size_t i = 0; i < layers_.size(); i++) {
398 stream << "Layer " << i << ":";
399 stream << " type=" << layers_[i].GetCompositionType().to_string();
400 stream << " surface_id=" << layers_[i].GetSurfaceId();
401 stream << " buffer_id=" << layers_[i].GetBufferId();
402 stream << std::endl;
403 }
404 stream << std::endl;
405
406 if (post_thread_resumed_) {
407 stream << "Hardware Composer Debug Info:" << std::endl;
408 stream << composer_->dumpDebugInfo();
409 }
410
411 return stream.str();
412 }
413
PostLayers()414 void HardwareComposer::PostLayers() {
415 ATRACE_NAME("HardwareComposer::PostLayers");
416
417 // Setup the hardware composer layers with current buffers.
418 for (auto& layer : layers_) {
419 layer.Prepare();
420 }
421
422 HWC::Error error = Validate(HWC_DISPLAY_PRIMARY);
423 if (error != HWC::Error::None) {
424 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
425 error.to_string().c_str());
426 return;
427 }
428
429 // Now that we have taken in a frame from the application, we have a chance
430 // to drop the frame before passing the frame along to HWC.
431 // If the display driver has become backed up, we detect it here and then
432 // react by skipping this frame to catch up latency.
433 while (!retire_fence_fds_.empty() &&
434 (!retire_fence_fds_.front() ||
435 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
436 // There are only 2 fences in here, no performance problem to shift the
437 // array of ints.
438 retire_fence_fds_.erase(retire_fence_fds_.begin());
439 }
440
441 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
442 post_thread_config_.allowed_pending_fence_count;
443
444 if (is_fence_pending) {
445 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
446
447 ALOGW_IF(is_fence_pending,
448 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
449 retire_fence_fds_.size());
450
451 for (auto& layer : layers_) {
452 layer.Drop();
453 }
454 return;
455 } else {
456 // Make the transition more obvious in systrace when the frame skip happens
457 // above.
458 ATRACE_INT("frame_skip_count", 0);
459 }
460
461 #if TRACE > 1
462 for (size_t i = 0; i < layers_.size(); i++) {
463 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
464 i, layers_[i].GetBufferId(),
465 layers_[i].GetCompositionType().to_string().c_str());
466 }
467 #endif
468
469 error = Present(HWC_DISPLAY_PRIMARY);
470 if (error != HWC::Error::None) {
471 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
472 error.to_string().c_str());
473 return;
474 }
475
476 std::vector<Hwc2::Layer> out_layers;
477 std::vector<int> out_fences;
478 error = composer_->getReleaseFences(HWC_DISPLAY_PRIMARY, &out_layers,
479 &out_fences);
480 ALOGE_IF(error != HWC::Error::None,
481 "HardwareComposer::PostLayers: Failed to get release fences: %s",
482 error.to_string().c_str());
483
484 // Perform post-frame bookkeeping.
485 uint32_t num_elements = out_layers.size();
486 for (size_t i = 0; i < num_elements; ++i) {
487 for (auto& layer : layers_) {
488 if (layer.GetLayerHandle() == out_layers[i]) {
489 layer.Finish(out_fences[i]);
490 }
491 }
492 }
493 }
494
SetDisplaySurfaces(std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces)495 void HardwareComposer::SetDisplaySurfaces(
496 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
497 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
498 surfaces.size());
499 const bool display_idle = surfaces.size() == 0;
500 {
501 std::unique_lock<std::mutex> lock(post_thread_mutex_);
502 pending_surfaces_ = std::move(surfaces);
503 }
504
505 if (request_display_callback_ && (!is_standalone_device_ || !composer_))
506 request_display_callback_(!display_idle);
507
508 // Set idle state based on whether there are any surfaces to handle.
509 UpdatePostThreadState(PostThreadState::Idle, display_idle);
510 }
511
OnNewGlobalBuffer(DvrGlobalBufferKey key,IonBuffer & ion_buffer)512 int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
513 IonBuffer& ion_buffer) {
514 if (key == DvrGlobalBuffers::kVsyncBuffer) {
515 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
516 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
517
518 if (vsync_ring_->IsMapped() == false) {
519 return -EPERM;
520 }
521 }
522
523 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
524 return MapConfigBuffer(ion_buffer);
525 }
526
527 return 0;
528 }
529
OnDeletedGlobalBuffer(DvrGlobalBufferKey key)530 void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
531 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
532 ConfigBufferDeleted();
533 }
534 }
535
MapConfigBuffer(IonBuffer & ion_buffer)536 int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
537 std::lock_guard<std::mutex> lock(shared_config_mutex_);
538 shared_config_ring_ = DvrConfigRing();
539
540 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
541 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
542 return -EINVAL;
543 }
544
545 void* buffer_base = 0;
546 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
547 ion_buffer.height(), &buffer_base);
548 if (result != 0) {
549 ALOGE(
550 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
551 "buffer.");
552 return -EPERM;
553 }
554
555 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
556 ion_buffer.Unlock();
557
558 return 0;
559 }
560
ConfigBufferDeleted()561 void HardwareComposer::ConfigBufferDeleted() {
562 std::lock_guard<std::mutex> lock(shared_config_mutex_);
563 shared_config_ring_ = DvrConfigRing();
564 }
565
UpdateConfigBuffer()566 void HardwareComposer::UpdateConfigBuffer() {
567 std::lock_guard<std::mutex> lock(shared_config_mutex_);
568 if (!shared_config_ring_.is_valid())
569 return;
570 // Copy from latest record in shared_config_ring_ to local copy.
571 DvrConfig record;
572 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
573 post_thread_config_ = record;
574 }
575 }
576
PostThreadPollInterruptible(const pdx::LocalHandle & event_fd,int requested_events,int timeout_ms)577 int HardwareComposer::PostThreadPollInterruptible(
578 const pdx::LocalHandle& event_fd, int requested_events, int timeout_ms) {
579 pollfd pfd[2] = {
580 {
581 .fd = event_fd.Get(),
582 .events = static_cast<short>(requested_events),
583 .revents = 0,
584 },
585 {
586 .fd = post_thread_event_fd_.Get(),
587 .events = POLLPRI | POLLIN,
588 .revents = 0,
589 },
590 };
591 int ret, error;
592 do {
593 ret = poll(pfd, 2, timeout_ms);
594 error = errno;
595 ALOGW_IF(ret < 0,
596 "HardwareComposer::PostThreadPollInterruptible: Error during "
597 "poll(): %s (%d)",
598 strerror(error), error);
599 } while (ret < 0 && error == EINTR);
600
601 if (ret < 0) {
602 return -error;
603 } else if (ret == 0) {
604 return -ETIMEDOUT;
605 } else if (pfd[0].revents != 0) {
606 return 0;
607 } else if (pfd[1].revents != 0) {
608 ALOGI("VrHwcPost thread interrupted: revents=%x", pfd[1].revents);
609 return kPostThreadInterrupted;
610 } else {
611 return 0;
612 }
613 }
614
GetVSyncTime()615 Status<int64_t> HardwareComposer::GetVSyncTime() {
616 auto status = composer_callback_->GetVsyncTime(HWC_DISPLAY_PRIMARY);
617 ALOGE_IF(!status,
618 "HardwareComposer::GetVSyncTime: Failed to get vsync timestamp: %s",
619 status.GetErrorMessage().c_str());
620 return status;
621 }
622
623 // Waits for the next vsync and returns the timestamp of the vsync event. If
624 // vsync already passed since the last call, returns the latest vsync timestamp
625 // instead of blocking.
WaitForVSync()626 Status<int64_t> HardwareComposer::WaitForVSync() {
627 const int64_t predicted_vsync_time =
628 last_vsync_timestamp_ +
629 display_metrics_.vsync_period_ns * vsync_prediction_interval_;
630 const int error = SleepUntil(predicted_vsync_time);
631 if (error < 0) {
632 ALOGE("HardwareComposer::WaifForVSync:: Failed to sleep: %s",
633 strerror(-error));
634 return error;
635 }
636 return {predicted_vsync_time};
637 }
638
SleepUntil(int64_t wakeup_timestamp)639 int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
640 const int timer_fd = vsync_sleep_timer_fd_.Get();
641 const itimerspec wakeup_itimerspec = {
642 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
643 .it_value = NsToTimespec(wakeup_timestamp),
644 };
645 int ret =
646 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
647 int error = errno;
648 if (ret < 0) {
649 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
650 strerror(error));
651 return -error;
652 }
653
654 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN,
655 /*timeout_ms*/ -1);
656 }
657
PostThread()658 void HardwareComposer::PostThread() {
659 // NOLINTNEXTLINE(runtime/int)
660 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
661
662 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
663 // there may have been a startup timing issue between this thread and
664 // performanced. Try again later when this thread becomes active.
665 bool thread_policy_setup =
666 SetThreadPolicy("graphics:high", "/system/performance");
667
668 #if ENABLE_BACKLIGHT_BRIGHTNESS
669 // TODO(hendrikw): This isn't required at the moment. It's possible that there
670 // is another method to access this when needed.
671 // Open the backlight brightness control sysfs node.
672 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
673 ALOGW_IF(!backlight_brightness_fd_,
674 "HardwareComposer: Failed to open backlight brightness control: %s",
675 strerror(errno));
676 #endif // ENABLE_BACKLIGHT_BRIGHTNESS
677
678 // Create a timerfd based on CLOCK_MONOTINIC.
679 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
680 LOG_ALWAYS_FATAL_IF(
681 !vsync_sleep_timer_fd_,
682 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
683 strerror(errno));
684
685 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
686 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
687
688 // TODO(jbates) Query vblank time from device, when such an API is available.
689 // This value (6.3%) was measured on A00 in low persistence mode.
690 int64_t vblank_ns = ns_per_frame * 63 / 1000;
691 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
692
693 // Check property for overriding right eye offset value.
694 right_eye_photon_offset_ns =
695 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
696
697 bool was_running = false;
698
699 while (1) {
700 ATRACE_NAME("HardwareComposer::PostThread");
701
702 // Check for updated config once per vsync.
703 UpdateConfigBuffer();
704
705 while (post_thread_quiescent_) {
706 std::unique_lock<std::mutex> lock(post_thread_mutex_);
707 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
708
709 // Tear down resources if necessary.
710 if (was_running)
711 OnPostThreadPaused();
712
713 was_running = false;
714 post_thread_resumed_ = false;
715 post_thread_ready_.notify_all();
716
717 if (post_thread_state_ & PostThreadState::Quit) {
718 ALOGI("HardwareComposer::PostThread: Quitting.");
719 return;
720 }
721
722 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
723
724 post_thread_resumed_ = true;
725 post_thread_ready_.notify_all();
726
727 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
728 }
729
730 if (!was_running) {
731 // Setup resources.
732 OnPostThreadResumed();
733 was_running = true;
734
735 // Try to setup the scheduler policy if it failed during startup. Only
736 // attempt to do this on transitions from inactive to active to avoid
737 // spamming the system with RPCs and log messages.
738 if (!thread_policy_setup) {
739 thread_policy_setup =
740 SetThreadPolicy("graphics:high", "/system/performance");
741 }
742
743 // Initialize the last vsync timestamp with the current time. The
744 // predictor below uses this time + the vsync interval in absolute time
745 // units for the initial delay. Once the driver starts reporting vsync the
746 // predictor will sync up with the real vsync.
747 last_vsync_timestamp_ = GetSystemClockNs();
748 }
749
750 int64_t vsync_timestamp = 0;
751 {
752 TRACE_FORMAT("wait_vsync|vsync=%u;last_timestamp=%" PRId64
753 ";prediction_interval=%d|",
754 vsync_count_ + 1, last_vsync_timestamp_,
755 vsync_prediction_interval_);
756
757 auto status = WaitForVSync();
758 ALOGE_IF(
759 !status,
760 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
761 status.GetErrorMessage().c_str());
762
763 // If there was an error either sleeping was interrupted due to pausing or
764 // there was an error getting the latest timestamp.
765 if (!status)
766 continue;
767
768 // Predicted vsync timestamp for this interval. This is stable because we
769 // use absolute time for the wakeup timer.
770 vsync_timestamp = status.get();
771 }
772
773 // Advance the vsync counter only if the system is keeping up with hardware
774 // vsync to give clients an indication of the delays.
775 if (vsync_prediction_interval_ == 1)
776 ++vsync_count_;
777
778 const bool layer_config_changed = UpdateLayerConfig();
779
780 // Publish the vsync event.
781 if (vsync_ring_) {
782 DvrVsync vsync;
783 vsync.vsync_count = vsync_count_;
784 vsync.vsync_timestamp_ns = vsync_timestamp;
785 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
786 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
787 vsync.vsync_period_ns = ns_per_frame;
788
789 vsync_ring_->Publish(vsync);
790 }
791
792 // Signal all of the vsync clients. Because absolute time is used for the
793 // wakeup time below, this can take a little time if necessary.
794 if (vsync_callback_)
795 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp,
796 /*frame_time_estimate*/ 0, vsync_count_);
797
798 {
799 // Sleep until shortly before vsync.
800 ATRACE_NAME("sleep");
801
802 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
803 const int64_t now_ns = GetSystemClockNs();
804 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
805 post_thread_config_.frame_post_offset_ns;
806 const int64_t wakeup_time_ns =
807 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
808
809 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
810 if (sleep_time_ns > 0) {
811 int error = SleepUntil(wakeup_time_ns);
812 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
813 strerror(-error));
814 if (error == kPostThreadInterrupted) {
815 if (layer_config_changed) {
816 // If the layer config changed we need to validateDisplay() even if
817 // we're going to drop the frame, to flush the Composer object's
818 // internal command buffer and apply our layer changes.
819 Validate(HWC_DISPLAY_PRIMARY);
820 }
821 continue;
822 }
823 }
824 }
825
826 {
827 auto status = GetVSyncTime();
828 if (!status) {
829 ALOGE("HardwareComposer::PostThread: Failed to get VSYNC time: %s",
830 status.GetErrorMessage().c_str());
831 }
832
833 // If we failed to read vsync there might be a problem with the driver.
834 // Since there's nothing we can do just behave as though we didn't get an
835 // updated vsync time and let the prediction continue.
836 const int64_t current_vsync_timestamp =
837 status ? status.get() : last_vsync_timestamp_;
838
839 const bool vsync_delayed =
840 last_vsync_timestamp_ == current_vsync_timestamp;
841 ATRACE_INT("vsync_delayed", vsync_delayed);
842
843 // If vsync was delayed advance the prediction interval and allow the
844 // fence logic in PostLayers() to skip the frame.
845 if (vsync_delayed) {
846 ALOGW(
847 "HardwareComposer::PostThread: VSYNC timestamp did not advance "
848 "since last frame: timestamp=%" PRId64 " prediction_interval=%d",
849 current_vsync_timestamp, vsync_prediction_interval_);
850 vsync_prediction_interval_++;
851 } else {
852 // We have an updated vsync timestamp, reset the prediction interval.
853 last_vsync_timestamp_ = current_vsync_timestamp;
854 vsync_prediction_interval_ = 1;
855 }
856 }
857
858 PostLayers();
859 }
860 }
861
862 // Checks for changes in the surface stack and updates the layer config to
863 // accomodate the new stack.
UpdateLayerConfig()864 bool HardwareComposer::UpdateLayerConfig() {
865 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
866 {
867 std::unique_lock<std::mutex> lock(post_thread_mutex_);
868 if (pending_surfaces_.empty())
869 return false;
870
871 surfaces = std::move(pending_surfaces_);
872 }
873
874 ATRACE_NAME("UpdateLayerConfig_HwLayers");
875
876 // Sort the new direct surface list by z-order to determine the relative order
877 // of the surfaces. This relative order is used for the HWC z-order value to
878 // insulate VrFlinger and HWC z-order semantics from each other.
879 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
880 return a->z_order() < b->z_order();
881 });
882
883 // Prepare a new layer stack, pulling in layers from the previous
884 // layer stack that are still active and updating their attributes.
885 std::vector<Layer> layers;
886 size_t layer_index = 0;
887 for (const auto& surface : surfaces) {
888 // The bottom layer is opaque, other layers blend.
889 HWC::BlendMode blending =
890 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
891
892 // Try to find a layer for this surface in the set of active layers.
893 auto search =
894 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
895 const bool found = search != layers_.end() &&
896 search->GetSurfaceId() == surface->surface_id();
897 if (found) {
898 // Update the attributes of the layer that may have changed.
899 search->SetBlending(blending);
900 search->SetZOrder(layer_index); // Relative z-order.
901
902 // Move the existing layer to the new layer set and remove the empty layer
903 // object from the current set.
904 layers.push_back(std::move(*search));
905 layers_.erase(search);
906 } else {
907 // Insert a layer for the new surface.
908 layers.emplace_back(surface, blending, display_transform_,
909 HWC::Composition::Device, layer_index);
910 }
911
912 ALOGI_IF(
913 TRACE,
914 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
915 layer_index, layers[layer_index].GetSurfaceId());
916
917 layer_index++;
918 }
919
920 // Sort the new layer stack by ascending surface id.
921 std::sort(layers.begin(), layers.end());
922
923 // Replace the previous layer set with the new layer set. The destructor of
924 // the previous set will clean up the remaining Layers that are not moved to
925 // the new layer set.
926 layers_ = std::move(layers);
927
928 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
929 layers_.size());
930 return true;
931 }
932
SetVSyncCallback(VSyncCallback callback)933 void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
934 vsync_callback_ = callback;
935 }
936
SetBacklightBrightness(int brightness)937 void HardwareComposer::SetBacklightBrightness(int brightness) {
938 if (backlight_brightness_fd_) {
939 std::array<char, 32> text;
940 const int length = snprintf(text.data(), text.size(), "%d", brightness);
941 write(backlight_brightness_fd_.Get(), text.data(), length);
942 }
943 }
944
onHotplug(Hwc2::Display display,IComposerCallback::Connection)945 Return<void> HardwareComposer::ComposerCallback::onHotplug(
946 Hwc2::Display display, IComposerCallback::Connection /*conn*/) {
947 // See if the driver supports the vsync_event node in sysfs.
948 if (display < HWC_NUM_PHYSICAL_DISPLAY_TYPES &&
949 !displays_[display].driver_vsync_event_fd) {
950 std::array<char, 1024> buffer;
951 snprintf(buffer.data(), buffer.size(),
952 "/sys/class/graphics/fb%" PRIu64 "/vsync_event", display);
953 if (LocalHandle handle{buffer.data(), O_RDONLY}) {
954 ALOGI(
955 "HardwareComposer::ComposerCallback::onHotplug: Driver supports "
956 "vsync_event node for display %" PRIu64,
957 display);
958 displays_[display].driver_vsync_event_fd = std::move(handle);
959 } else {
960 ALOGI(
961 "HardwareComposer::ComposerCallback::onHotplug: Driver does not "
962 "support vsync_event node for display %" PRIu64,
963 display);
964 }
965 }
966
967 return Void();
968 }
969
onRefresh(Hwc2::Display)970 Return<void> HardwareComposer::ComposerCallback::onRefresh(
971 Hwc2::Display /*display*/) {
972 return hardware::Void();
973 }
974
onVsync(Hwc2::Display display,int64_t timestamp)975 Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
976 int64_t timestamp) {
977 TRACE_FORMAT("vsync_callback|display=%" PRIu64 ";timestamp=%" PRId64 "|",
978 display, timestamp);
979 if (display < HWC_NUM_PHYSICAL_DISPLAY_TYPES) {
980 displays_[display].callback_vsync_timestamp = timestamp;
981 } else {
982 ALOGW(
983 "HardwareComposer::ComposerCallback::onVsync: Received vsync on "
984 "non-physical display: display=%" PRId64,
985 display);
986 }
987 return Void();
988 }
989
GetVsyncTime(Hwc2::Display display)990 Status<int64_t> HardwareComposer::ComposerCallback::GetVsyncTime(
991 Hwc2::Display display) {
992 if (display >= HWC_NUM_PHYSICAL_DISPLAY_TYPES) {
993 ALOGE(
994 "HardwareComposer::ComposerCallback::GetVsyncTime: Invalid physical "
995 "display requested: display=%" PRIu64,
996 display);
997 return ErrorStatus(EINVAL);
998 }
999
1000 // See if the driver supports direct vsync events.
1001 LocalHandle& event_fd = displays_[display].driver_vsync_event_fd;
1002 if (!event_fd) {
1003 // Fall back to returning the last timestamp returned by the vsync
1004 // callback.
1005 std::lock_guard<std::mutex> autolock(vsync_mutex_);
1006 return displays_[display].callback_vsync_timestamp;
1007 }
1008
1009 // When the driver supports the vsync_event sysfs node we can use it to
1010 // determine the latest vsync timestamp, even if the HWC callback has been
1011 // delayed.
1012
1013 // The driver returns data in the form "VSYNC=<timestamp ns>".
1014 std::array<char, 32> data;
1015 data.fill('\0');
1016
1017 // Seek back to the beginning of the event file.
1018 int ret = lseek(event_fd.Get(), 0, SEEK_SET);
1019 if (ret < 0) {
1020 const int error = errno;
1021 ALOGE(
1022 "HardwareComposer::ComposerCallback::GetVsyncTime: Failed to seek "
1023 "vsync event fd: %s",
1024 strerror(error));
1025 return ErrorStatus(error);
1026 }
1027
1028 // Read the vsync event timestamp.
1029 ret = read(event_fd.Get(), data.data(), data.size());
1030 if (ret < 0) {
1031 const int error = errno;
1032 ALOGE_IF(error != EAGAIN,
1033 "HardwareComposer::ComposerCallback::GetVsyncTime: Error "
1034 "while reading timestamp: %s",
1035 strerror(error));
1036 return ErrorStatus(error);
1037 }
1038
1039 int64_t timestamp;
1040 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
1041 reinterpret_cast<uint64_t*>(×tamp));
1042 if (ret < 0) {
1043 const int error = errno;
1044 ALOGE(
1045 "HardwareComposer::ComposerCallback::GetVsyncTime: Error while "
1046 "parsing timestamp: %s",
1047 strerror(error));
1048 return ErrorStatus(error);
1049 }
1050
1051 return {timestamp};
1052 }
1053
1054 Hwc2::Composer* Layer::composer_{nullptr};
1055 HWCDisplayMetrics Layer::display_metrics_{0, 0, {0, 0}, 0};
1056
Reset()1057 void Layer::Reset() {
1058 if (hardware_composer_layer_) {
1059 composer_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_);
1060 hardware_composer_layer_ = 0;
1061 }
1062
1063 z_order_ = 0;
1064 blending_ = HWC::BlendMode::None;
1065 transform_ = HWC::Transform::None;
1066 composition_type_ = HWC::Composition::Invalid;
1067 target_composition_type_ = composition_type_;
1068 source_ = EmptyVariant{};
1069 acquire_fence_.Close();
1070 surface_rect_functions_applied_ = false;
1071 pending_visibility_settings_ = true;
1072 cached_buffer_map_.clear();
1073 }
1074
Layer(const std::shared_ptr<DirectDisplaySurface> & surface,HWC::BlendMode blending,HWC::Transform transform,HWC::Composition composition_type,size_t z_order)1075 Layer::Layer(const std::shared_ptr<DirectDisplaySurface>& surface,
1076 HWC::BlendMode blending, HWC::Transform transform,
1077 HWC::Composition composition_type, size_t z_order)
1078 : z_order_{z_order},
1079 blending_{blending},
1080 transform_{transform},
1081 target_composition_type_{composition_type},
1082 source_{SourceSurface{surface}} {
1083 CommonLayerSetup();
1084 }
1085
Layer(const std::shared_ptr<IonBuffer> & buffer,HWC::BlendMode blending,HWC::Transform transform,HWC::Composition composition_type,size_t z_order)1086 Layer::Layer(const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
1087 HWC::Transform transform, HWC::Composition composition_type,
1088 size_t z_order)
1089 : z_order_{z_order},
1090 blending_{blending},
1091 transform_{transform},
1092 target_composition_type_{composition_type},
1093 source_{SourceBuffer{buffer}} {
1094 CommonLayerSetup();
1095 }
1096
~Layer()1097 Layer::~Layer() { Reset(); }
1098
Layer(Layer && other)1099 Layer::Layer(Layer&& other) { *this = std::move(other); }
1100
operator =(Layer && other)1101 Layer& Layer::operator=(Layer&& other) {
1102 if (this != &other) {
1103 Reset();
1104 using std::swap;
1105 swap(hardware_composer_layer_, other.hardware_composer_layer_);
1106 swap(z_order_, other.z_order_);
1107 swap(blending_, other.blending_);
1108 swap(transform_, other.transform_);
1109 swap(composition_type_, other.composition_type_);
1110 swap(target_composition_type_, other.target_composition_type_);
1111 swap(source_, other.source_);
1112 swap(acquire_fence_, other.acquire_fence_);
1113 swap(surface_rect_functions_applied_,
1114 other.surface_rect_functions_applied_);
1115 swap(pending_visibility_settings_, other.pending_visibility_settings_);
1116 swap(cached_buffer_map_, other.cached_buffer_map_);
1117 }
1118 return *this;
1119 }
1120
UpdateBuffer(const std::shared_ptr<IonBuffer> & buffer)1121 void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1122 if (source_.is<SourceBuffer>())
1123 std::get<SourceBuffer>(source_) = {buffer};
1124 }
1125
SetBlending(HWC::BlendMode blending)1126 void Layer::SetBlending(HWC::BlendMode blending) {
1127 if (blending_ != blending) {
1128 blending_ = blending;
1129 pending_visibility_settings_ = true;
1130 }
1131 }
1132
SetZOrder(size_t z_order)1133 void Layer::SetZOrder(size_t z_order) {
1134 if (z_order_ != z_order) {
1135 z_order_ = z_order;
1136 pending_visibility_settings_ = true;
1137 }
1138 }
1139
GetBuffer()1140 IonBuffer* Layer::GetBuffer() {
1141 struct Visitor {
1142 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1143 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1144 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1145 };
1146 return source_.Visit(Visitor{});
1147 }
1148
UpdateVisibilitySettings()1149 void Layer::UpdateVisibilitySettings() {
1150 if (pending_visibility_settings_) {
1151 pending_visibility_settings_ = false;
1152
1153 HWC::Error error;
1154 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1155
1156 error = composer_->setLayerBlendMode(
1157 display, hardware_composer_layer_,
1158 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1159 ALOGE_IF(error != HWC::Error::None,
1160 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1161 error.to_string().c_str());
1162
1163 error =
1164 composer_->setLayerZOrder(display, hardware_composer_layer_, z_order_);
1165 ALOGE_IF(error != HWC::Error::None,
1166 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1167 error.to_string().c_str());
1168 }
1169 }
1170
UpdateLayerSettings()1171 void Layer::UpdateLayerSettings() {
1172 HWC::Error error;
1173 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1174
1175 UpdateVisibilitySettings();
1176
1177 // TODO(eieio): Use surface attributes or some other mechanism to control
1178 // the layer display frame.
1179 error = composer_->setLayerDisplayFrame(
1180 display, hardware_composer_layer_,
1181 {0, 0, display_metrics_.width, display_metrics_.height});
1182 ALOGE_IF(error != HWC::Error::None,
1183 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1184 error.to_string().c_str());
1185
1186 error = composer_->setLayerVisibleRegion(
1187 display, hardware_composer_layer_,
1188 {{0, 0, display_metrics_.width, display_metrics_.height}});
1189 ALOGE_IF(error != HWC::Error::None,
1190 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1191 error.to_string().c_str());
1192
1193 error =
1194 composer_->setLayerPlaneAlpha(display, hardware_composer_layer_, 1.0f);
1195 ALOGE_IF(error != HWC::Error::None,
1196 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1197 error.to_string().c_str());
1198 }
1199
CommonLayerSetup()1200 void Layer::CommonLayerSetup() {
1201 HWC::Error error =
1202 composer_->createLayer(HWC_DISPLAY_PRIMARY, &hardware_composer_layer_);
1203 ALOGE_IF(error != HWC::Error::None,
1204 "Layer::CommonLayerSetup: Failed to create layer on primary "
1205 "display: %s",
1206 error.to_string().c_str());
1207 UpdateLayerSettings();
1208 }
1209
CheckAndUpdateCachedBuffer(std::size_t slot,int buffer_id)1210 bool Layer::CheckAndUpdateCachedBuffer(std::size_t slot, int buffer_id) {
1211 auto search = cached_buffer_map_.find(slot);
1212 if (search != cached_buffer_map_.end() && search->second == buffer_id)
1213 return true;
1214
1215 // Assign or update the buffer slot.
1216 if (buffer_id >= 0)
1217 cached_buffer_map_[slot] = buffer_id;
1218 return false;
1219 }
1220
Prepare()1221 void Layer::Prepare() {
1222 int right, bottom, id;
1223 sp<GraphicBuffer> handle;
1224 std::size_t slot;
1225
1226 // Acquire the next buffer according to the type of source.
1227 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
1228 std::tie(right, bottom, id, handle, acquire_fence_, slot) =
1229 source.Acquire();
1230 });
1231
1232 TRACE_FORMAT("Layer::Prepare|buffer_id=%d;slot=%zu|", id, slot);
1233
1234 // Update any visibility (blending, z-order) changes that occurred since
1235 // last prepare.
1236 UpdateVisibilitySettings();
1237
1238 // When a layer is first setup there may be some time before the first
1239 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1240 // until the first buffer arrives. Once the first buffer arrives there will
1241 // always be a buffer for the frame even if it is old.
1242 if (!handle.get()) {
1243 if (composition_type_ == HWC::Composition::Invalid) {
1244 composition_type_ = HWC::Composition::SolidColor;
1245 composer_->setLayerCompositionType(
1246 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1247 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1248 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
1249 composer_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1250 layer_color);
1251 } else {
1252 // The composition type is already set. Nothing else to do until a
1253 // buffer arrives.
1254 }
1255 } else {
1256 if (composition_type_ != target_composition_type_) {
1257 composition_type_ = target_composition_type_;
1258 composer_->setLayerCompositionType(
1259 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1260 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1261 }
1262
1263 // See if the HWC cache already has this buffer.
1264 const bool cached = CheckAndUpdateCachedBuffer(slot, id);
1265 if (cached)
1266 handle = nullptr;
1267
1268 HWC::Error error{HWC::Error::None};
1269 error =
1270 composer_->setLayerBuffer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1271 slot, handle, acquire_fence_.Get());
1272
1273 ALOGE_IF(error != HWC::Error::None,
1274 "Layer::Prepare: Error setting layer buffer: %s",
1275 error.to_string().c_str());
1276
1277 if (!surface_rect_functions_applied_) {
1278 const float float_right = right;
1279 const float float_bottom = bottom;
1280 error = composer_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY,
1281 hardware_composer_layer_,
1282 {0, 0, float_right, float_bottom});
1283
1284 ALOGE_IF(error != HWC::Error::None,
1285 "Layer::Prepare: Error setting layer source crop: %s",
1286 error.to_string().c_str());
1287
1288 surface_rect_functions_applied_ = true;
1289 }
1290 }
1291 }
1292
Finish(int release_fence_fd)1293 void Layer::Finish(int release_fence_fd) {
1294 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1295 &source_, [release_fence_fd](auto& source) {
1296 source.Finish(LocalHandle(release_fence_fd));
1297 });
1298 }
1299
Drop()1300 void Layer::Drop() { acquire_fence_.Close(); }
1301
1302 } // namespace dvr
1303 } // namespace android
1304