1 /*
2 * Copyright (c) 2016 - 2017, 2020 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 <gralloc_priv.h>
31 #include <sync/sync.h>
32
33 #include <TonemapFactory.h>
34
35 #include <core/buffer_allocator.h>
36
37 #include <utils/constants.h>
38 #include <utils/debug.h>
39 #include <utils/formats.h>
40 #include <utils/rect.h>
41 #include <utils/utils.h>
42
43 #include <vector>
44
45 #include "hwc_debugger.h"
46 #include "hwc_tonemapper.h"
47
48 #define __CLASS__ "HWCToneMapper"
49
50 namespace sdm {
51
ToneMapSession(HWCBufferAllocator * buffer_allocator)52 ToneMapSession::ToneMapSession(HWCBufferAllocator *buffer_allocator)
53 : tone_map_task_(*this), buffer_allocator_(buffer_allocator) {
54 buffer_info_.resize(kNumIntermediateBuffers);
55 }
56
~ToneMapSession()57 ToneMapSession::~ToneMapSession() {
58 tone_map_task_.PerformTask(ToneMapTaskCode::kCodeDestroy, nullptr);
59 FreeIntermediateBuffers();
60 buffer_info_.clear();
61 }
62
OnTask(const ToneMapTaskCode & task_code,SyncTask<ToneMapTaskCode>::TaskContext * task_context)63 void ToneMapSession::OnTask(const ToneMapTaskCode &task_code,
64 SyncTask<ToneMapTaskCode>::TaskContext *task_context) {
65 switch (task_code) {
66 #ifndef TARGET_HEADLESS
67 case ToneMapTaskCode::kCodeGetInstance: {
68 ToneMapGetInstanceContext *ctx = static_cast<ToneMapGetInstanceContext *>(task_context);
69 Lut3d &lut_3d = ctx->layer->lut_3d;
70 Color10Bit *grid_entries = NULL;
71 int grid_size = 0;
72 if (lut_3d.validGridEntries) {
73 grid_entries = lut_3d.gridEntries;
74 grid_size = INT(lut_3d.gridSize);
75 }
76 gpu_tone_mapper_ = TonemapperFactory_GetInstance(tone_map_config_.type,
77 lut_3d.lutEntries, lut_3d.dim,
78 grid_entries, grid_size,
79 tone_map_config_.secure);
80 }
81 break;
82
83 case ToneMapTaskCode::kCodeBlit: {
84 ToneMapBlitContext *ctx = static_cast<ToneMapBlitContext *>(task_context);
85 uint8_t buffer_index = current_buffer_index_;
86 const void *dst_hnd = reinterpret_cast<const void *>
87 (buffer_info_[buffer_index].private_data);
88 const void *src_hnd = reinterpret_cast<const void *>
89 (ctx->layer->input_buffer.buffer_id);
90 int fence = gpu_tone_mapper_->blit(dst_hnd, src_hnd, Fence::Dup(ctx->merged));
91 ctx->fence = Fence::Create(fence, "tonemap");
92 }
93 break;
94
95 case ToneMapTaskCode::kCodeDestroy: {
96 delete gpu_tone_mapper_;
97 }
98 break;
99
100 #endif
101 default:
102 break;
103 }
104 }
105
AllocateIntermediateBuffers(const Layer * layer)106 DisplayError ToneMapSession::AllocateIntermediateBuffers(const Layer *layer) {
107 DisplayError error = kErrorNone;
108 for (uint8_t i = 0; i < kNumIntermediateBuffers; i++) {
109 BufferInfo &buffer_info = buffer_info_[i];
110 buffer_info.buffer_config.width = layer->request.width;
111 buffer_info.buffer_config.height = layer->request.height;
112 buffer_info.buffer_config.format = layer->request.format;
113 buffer_info.buffer_config.secure = layer->request.flags.secure;
114 buffer_info.buffer_config.gfx_client = true;
115 error = buffer_allocator_->AllocateBuffer(&buffer_info);
116 if (error != kErrorNone) {
117 FreeIntermediateBuffers();
118 return error;
119 }
120 }
121
122 return kErrorNone;
123 }
124
FreeIntermediateBuffers()125 void ToneMapSession::FreeIntermediateBuffers() {
126 for (uint8_t i = 0; i < kNumIntermediateBuffers; i++) {
127 BufferInfo &buffer_info = buffer_info_[i];
128 if (buffer_info.private_data) {
129 buffer_allocator_->FreeBuffer(&buffer_info);
130 }
131 }
132 }
133
UpdateBuffer(const shared_ptr<Fence> & acquire_fence,LayerBuffer * buffer)134 void ToneMapSession::UpdateBuffer(const shared_ptr<Fence> &acquire_fence, LayerBuffer *buffer) {
135 // Acquire fence will be closed by HWC Display.
136 // Fence returned by GPU will be closed in PostCommit.
137 buffer->acquire_fence = acquire_fence;
138 buffer->size = buffer_info_[current_buffer_index_].alloc_buffer_info.size;
139 buffer->planes[0].fd = buffer_info_[current_buffer_index_].alloc_buffer_info.fd;
140 buffer->handle_id = buffer_info_[current_buffer_index_].alloc_buffer_info.id;
141 }
142
SetReleaseFence(const shared_ptr<Fence> & fd)143 void ToneMapSession::SetReleaseFence(const shared_ptr<Fence> &fd) {
144 release_fence_[current_buffer_index_] = fd;
145 }
146
SetToneMapConfig(Layer * layer,PrimariesTransfer blend_cs)147 void ToneMapSession::SetToneMapConfig(Layer *layer, PrimariesTransfer blend_cs) {
148 // HDR -> SDR is FORWARD and SDR - > HDR is INVERSE
149 tone_map_config_.type = layer->input_buffer.flags.hdr ? TONEMAP_FORWARD : TONEMAP_INVERSE;
150 tone_map_config_.blend_cs = blend_cs;
151 tone_map_config_.transfer = layer->input_buffer.color_metadata.transfer;
152 tone_map_config_.secure = layer->request.flags.secure;
153 tone_map_config_.format = layer->request.format;
154 }
155
IsSameToneMapConfig(Layer * layer,PrimariesTransfer blend_cs)156 bool ToneMapSession::IsSameToneMapConfig(Layer *layer, PrimariesTransfer blend_cs) {
157 LayerBuffer& buffer = layer->input_buffer;
158 private_handle_t *handle = static_cast<private_handle_t *>(buffer_info_[0].private_data);
159 int tonemap_type = buffer.flags.hdr ? TONEMAP_FORWARD : TONEMAP_INVERSE;
160
161 return ((tonemap_type == tone_map_config_.type) &&
162 (blend_cs == tone_map_config_.blend_cs) &&
163 (buffer.color_metadata.transfer == tone_map_config_.transfer) &&
164 (layer->request.flags.secure == tone_map_config_.secure) &&
165 (layer->request.format == tone_map_config_.format) &&
166 (layer->request.width == UINT32(handle->unaligned_width)) &&
167 (layer->request.height == UINT32(handle->unaligned_height)));
168 }
169
HandleToneMap(LayerStack * layer_stack)170 int HWCToneMapper::HandleToneMap(LayerStack *layer_stack) {
171 uint32_t gpu_count = 0;
172 DisplayError error = kErrorNone;
173
174 for (uint32_t i = 0; i < layer_stack->layers.size(); i++) {
175 uint32_t session_index = 0;
176 Layer *layer = layer_stack->layers.at(i);
177 if (layer->composition == kCompositionGPU) {
178 gpu_count++;
179 }
180
181 if (layer->request.flags.tone_map) {
182 DLOGV_IF(kTagClient, "Tonemapping for layer at index %d", i);
183 switch (layer->composition) {
184 case kCompositionGPUTarget:
185 if (!gpu_count) {
186 // When all layers are on FrameBuffer and if they do not update in the next draw cycle,
187 // then SDM marks them for SDE Composition because the cached FB layer gets displayed.
188 // GPU count will be 0 in this case. Try to use the existing tone-mapped frame buffer.
189 // No ToneMap/Blit is required. Just update the buffer & acquire fence fd of FB layer.
190 if (!tone_map_sessions_.empty() && (fb_session_index_ >= 0)) {
191 ToneMapSession *fb_tone_map_session = tone_map_sessions_.at(UINT32(fb_session_index_));
192 fb_tone_map_session->UpdateBuffer(nullptr /* acquire_fence */, &layer->input_buffer);
193 fb_tone_map_session->layer_index_ = INT(i);
194 fb_tone_map_session->acquired_ = true;
195 return 0;
196 }
197 }
198 error = AcquireToneMapSession(layer, &session_index, layer_stack->blend_cs);
199 fb_session_index_ = INT(session_index);
200 break;
201 default:
202 error = AcquireToneMapSession(layer, &session_index, layer_stack->blend_cs);
203 break;
204 }
205
206 if (error != kErrorNone) {
207 Terminate();
208 return -1;
209 }
210
211 ToneMapSession *session = tone_map_sessions_.at(session_index);
212 ToneMap(layer, session);
213 DLOGI_IF(kTagClient, "Layer %d associated with session index %d", i, session_index);
214 session->layer_index_ = INT(i);
215 }
216 }
217
218 return 0;
219 }
220
ToneMap(Layer * layer,ToneMapSession * session)221 void HWCToneMapper::ToneMap(Layer* layer, ToneMapSession *session) {
222 ToneMapBlitContext ctx = {};
223 ctx.layer = layer;
224
225 uint8_t buffer_index = session->current_buffer_index_;
226
227 // use and close the layer->input_buffer acquire fence fd.
228 // remove create when rf made it as a shared_ptr
229 ctx.merged = Fence::Merge(session->release_fence_[buffer_index],
230 layer->input_buffer.acquire_fence);
231
232 DTRACE_BEGIN("GPU_TM_BLIT");
233 session->tone_map_task_.PerformTask(ToneMapTaskCode::kCodeBlit, &ctx);
234 DTRACE_END();
235
236 DumpToneMapOutput(session, ctx.fence);
237 session->UpdateBuffer(ctx.fence, &layer->input_buffer);
238 }
239
PostCommit(LayerStack * layer_stack)240 void HWCToneMapper::PostCommit(LayerStack *layer_stack) {
241 auto it = tone_map_sessions_.begin();
242 while (it != tone_map_sessions_.end()) {
243 uint32_t session_index = UINT32(std::distance(tone_map_sessions_.begin(), it));
244 ToneMapSession *session = tone_map_sessions_.at(session_index);
245 if (session->acquired_) {
246 Layer *layer = layer_stack->layers.at(UINT32(session->layer_index_));
247 // Close the fd returned by GPU ToneMapper and set release fence.
248 LayerBuffer &layer_buffer = layer->input_buffer;
249 session->SetReleaseFence(layer_buffer.release_fence);
250 session->acquired_ = false;
251 it++;
252 } else {
253 DLOGI_IF(kTagClient, "Tone map session %d closed.", session_index);
254 delete session;
255 it = tone_map_sessions_.erase(it);
256 int deleted_session = INT(session_index);
257 // If FB tonemap session gets deleted, reset fb_session_index_, else update it.
258 if (deleted_session == fb_session_index_) {
259 fb_session_index_ = -1;
260 } else if (deleted_session < fb_session_index_) {
261 fb_session_index_--;
262 }
263 }
264 }
265 }
266
Terminate()267 void HWCToneMapper::Terminate() {
268 if (tone_map_sessions_.size()) {
269 while (!tone_map_sessions_.empty()) {
270 delete tone_map_sessions_.back();
271 tone_map_sessions_.pop_back();
272 }
273 fb_session_index_ = -1;
274 }
275 }
276
SetFrameDumpConfig(uint32_t count)277 void HWCToneMapper::SetFrameDumpConfig(uint32_t count) {
278 DLOGI("Dump FrameConfig count = %d", count);
279 dump_frame_count_ = count;
280 dump_frame_index_ = 0;
281 }
282
DumpToneMapOutput(ToneMapSession * session,shared_ptr<Fence> acquire_fd)283 void HWCToneMapper::DumpToneMapOutput(ToneMapSession *session, shared_ptr<Fence> acquire_fd) {
284 DisplayError error = kErrorNone;
285 if (!dump_frame_count_) {
286 return;
287 }
288
289 BufferInfo &buffer_info = session->buffer_info_[session->current_buffer_index_];
290 private_handle_t *target_buffer = static_cast<private_handle_t *>(buffer_info.private_data);
291 Fence::Wait(acquire_fd);
292
293 error = buffer_allocator_->MapBuffer(target_buffer, acquire_fd);
294 if (error != kErrorNone) {
295 DLOGE("MapBuffer failed, base addr = %" PRIx64, target_buffer->base);
296 return;
297 }
298
299 size_t result = 0;
300 char dump_file_name[PATH_MAX];
301 snprintf(dump_file_name, sizeof(dump_file_name), "%s/frame_dump_primary"
302 "/tonemap_%dx%d_frame%d.raw", HWCDebugHandler::DumpDir(), target_buffer->width,
303 target_buffer->height, dump_frame_index_);
304
305 FILE* fp = fopen(dump_file_name, "w+");
306 if (fp) {
307 DLOGI("base addr = %" PRIx64, target_buffer->base);
308 result = fwrite(reinterpret_cast<void *>(target_buffer->base), target_buffer->size, 1, fp);
309 fclose(fp);
310 }
311 dump_frame_count_--;
312 dump_frame_index_++;
313 }
314
AcquireToneMapSession(Layer * layer,uint32_t * session_index,PrimariesTransfer blend_cs)315 DisplayError HWCToneMapper::AcquireToneMapSession(Layer *layer, uint32_t *session_index,
316 PrimariesTransfer blend_cs) {
317 // When the property vendor.display.disable_hdr_lut_gen is set, the lutEntries and gridEntries in
318 // the Lut3d will be NULL, clients needs to allocate the memory and set correct 3D Lut
319 // for Tonemapping.
320 if (!layer->lut_3d.lutEntries || !layer->lut_3d.dim) {
321 // Atleast lutEntries must be valid for GPU Tonemapper.
322 DLOGE("Invalid Lut Entries or lut dimension = %d", layer->lut_3d.dim);
323 return kErrorParameters;
324 }
325
326 // Check if we can re-use an existing tone map session.
327 for (uint32_t i = 0; i < tone_map_sessions_.size(); i++) {
328 ToneMapSession *tonemap_session = tone_map_sessions_.at(i);
329 if (!tonemap_session->acquired_ && tonemap_session->IsSameToneMapConfig(layer, blend_cs)) {
330 tonemap_session->current_buffer_index_ = (tonemap_session->current_buffer_index_ + 1) %
331 ToneMapSession::kNumIntermediateBuffers;
332 tonemap_session->acquired_ = true;
333 *session_index = i;
334 return kErrorNone;
335 }
336 }
337
338 ToneMapSession *session = new ToneMapSession(buffer_allocator_);
339 if (!session) {
340 return kErrorMemory;
341 }
342
343 session->SetToneMapConfig(layer, blend_cs);
344
345 ToneMapGetInstanceContext ctx;
346 ctx.layer = layer;
347 session->tone_map_task_.PerformTask(ToneMapTaskCode::kCodeGetInstance, &ctx);
348
349 if (session->gpu_tone_mapper_ == NULL) {
350 DLOGE("Get Tonemapper failed!");
351 delete session;
352 return kErrorNotSupported;
353 }
354 DisplayError error = session->AllocateIntermediateBuffers(layer);
355 if (error != kErrorNone) {
356 DLOGE("Allocation of Intermediate Buffers failed!");
357 delete session;
358 return error;
359 }
360
361 session->acquired_ = true;
362 tone_map_sessions_.push_back(session);
363 *session_index = UINT32(tone_map_sessions_.size() - 1);
364
365 return kErrorNone;
366 }
367
368 } // namespace sdm
369