1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "host/libs/wayland/wayland_surface.h"
18 
19 #include <android-base/logging.h>
20 #include <wayland-server-protocol.h>
21 
22 namespace wayland {
23 
SetRegion(const Region & region)24 void Surface::SetRegion(const Region& region) {
25   std::unique_lock<std::mutex> lock(state_mutex_);
26   state_.region = region;
27 }
28 
Attach(struct wl_resource * buffer)29 void Surface::Attach(struct wl_resource* buffer) {
30   std::unique_lock<std::mutex> lock(state_mutex_);
31   state_.pending_buffer = buffer;
32 }
33 
Commit()34 void Surface::Commit() {
35   std::unique_lock<std::mutex> lock(state_mutex_);
36   state_.current_buffer = state_.pending_buffer;
37   state_.pending_buffer = nullptr;
38 
39   {
40     std::unique_lock<std::mutex> lock(callback_mutex_);
41     if (callback_ && callback_->frame_number < state_.current_frame_number) {
42       struct wl_shm_buffer* shm_buffer =
43           wl_shm_buffer_get(state_.current_buffer);
44       CHECK(shm_buffer != nullptr);
45 
46       wl_shm_buffer_begin_access(shm_buffer);
47 
48       const int32_t buffer_w = wl_shm_buffer_get_width(shm_buffer);
49       CHECK(buffer_w == state_.region.w);
50       const int32_t buffer_h = wl_shm_buffer_get_height(shm_buffer);
51       CHECK(buffer_h == state_.region.h);
52 
53       uint8_t* buffer_pixels =
54           reinterpret_cast<uint8_t*>(wl_shm_buffer_get_data(shm_buffer));
55 
56       callback_->frame_callback(state_.current_frame_number, buffer_pixels);
57       callback_.reset();
58 
59       wl_shm_buffer_end_access(shm_buffer);
60     }
61   }
62 
63   wl_buffer_send_release(state_.current_buffer);
64   wl_client_flush(wl_resource_get_client(state_.current_buffer));
65 
66   state_.current_buffer = nullptr;
67   state_.current_frame_number++;
68 }
69 
OnFrameAfter(uint32_t frame_number,FrameCallbackPackaged frame_callback)70 void Surface::OnFrameAfter(uint32_t frame_number,
71                            FrameCallbackPackaged frame_callback) {
72   std::unique_lock<std::mutex> lock(callback_mutex_);
73   callback_.emplace(PendingFrameCallback{frame_number,
74                                          std::move(frame_callback)});
75 }
76 
77 }  // namespace wayland