1 /*
2  * Copyright (C) 2018 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 <pthread.h>
18 #include <chrono>
19 #include <ctime>
20 #include <iomanip>
21 #include <fcntl.h>
22 #include <fstream>
23 #include <log/log.h>
24 #include <memory>
25 #include <sstream>
26 #include <sys/epoll.h>
27 #include <sys/prctl.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <tuple>
31 #include <unistd.h>
32 #include <unordered_map>
33 #include <vector>
34 
35 #include <drm/msm_drm.h>
36 #include <drm/msm_drm_pp.h>
37 #include <xf86drm.h>
38 #include <xf86drmMode.h>
39 
40 #include "histogram_collector.h"
41 #include "ringbuffer.h"
42 
43 constexpr static auto implementation_defined_max_frame_ringbuffer = 300;
44 
HistogramCollector()45 histogram::HistogramCollector::HistogramCollector() :
46     histogram(histogram::Ringbuffer::create(
47         implementation_defined_max_frame_ringbuffer, std::make_unique<histogram::DefaultTimeKeeper>())) {
48 }
49 
~HistogramCollector()50 histogram::HistogramCollector::~HistogramCollector() {
51     stop();
52 }
53 
54 namespace {
55 static constexpr size_t numBuckets = 8;
56 static_assert((HIST_V_SIZE % numBuckets) == 0,
57            "histogram cannot be rebucketed to smaller number of buckets");
58 static constexpr int bucket_compression = HIST_V_SIZE / numBuckets;
59 
rebucketTo8Buckets(std::array<uint64_t,HIST_V_SIZE> const & frame)60 std::array<uint64_t, numBuckets> rebucketTo8Buckets(std::array<uint64_t, HIST_V_SIZE> const& frame) {
61     std::array<uint64_t, numBuckets> bins;
62     bins.fill(0);
63     for (auto i = 0u; i < HIST_V_SIZE; i++)
64         bins[i / bucket_compression] += frame[i];
65     return bins;
66 }
67 }
68 
Dump() const69 std::string histogram::HistogramCollector::Dump() const {
70     uint64_t num_frames;
71     std::array<uint64_t, HIST_V_SIZE> all_sample_buckets;
72     std::tie(num_frames, all_sample_buckets) = histogram->collect_cumulative();
73     std::array<uint64_t, numBuckets> samples = rebucketTo8Buckets(all_sample_buckets);
74 
75     std::stringstream ss;
76     ss << "Color Sampling, dark (0.0) to light (1.0): sampled frames: " << num_frames << '\n';
77     if (num_frames == 0) {
78         ss << "\tno color statistics collected\n";
79         return ss.str();
80     }
81 
82     ss << std::fixed << std::setprecision(3);
83     ss << "\tbucket\t\t: # of displayed pixels at bucket value\n";
84     for (auto i = 0u; i < samples.size(); i++) {
85         ss << "\t" << i / static_cast<float>(samples.size()) <<
86               " to " << ( i + 1 ) / static_cast<float>(samples.size()) << "\t: " <<
87               samples[i] << '\n';
88     }
89 
90     return ss.str();
91 }
92 
collect(uint64_t max_frames,uint64_t timestamp,int32_t out_samples_size[NUM_HISTOGRAM_COLOR_COMPONENTS],uint64_t * out_samples[NUM_HISTOGRAM_COLOR_COMPONENTS],uint64_t * out_num_frames) const93 HWC2::Error histogram::HistogramCollector::collect(
94     uint64_t max_frames,
95     uint64_t timestamp,
96     int32_t out_samples_size[NUM_HISTOGRAM_COLOR_COMPONENTS],
97     uint64_t* out_samples[NUM_HISTOGRAM_COLOR_COMPONENTS],
98     uint64_t* out_num_frames) const {
99 
100     if (!out_samples_size || !out_num_frames)
101         return HWC2::Error::BadParameter;
102 
103     out_samples_size[0] = 0;
104     out_samples_size[1] = 0;
105     out_samples_size[2] = numBuckets;
106     out_samples_size[3] = 0;
107 
108     uint64_t num_frames;
109     std::array<uint64_t, HIST_V_SIZE> samples;
110 
111     if (max_frames == 0 && timestamp == 0) {
112         std::tie(num_frames, samples) = histogram->collect_cumulative();
113     } else if (max_frames == 0) {
114         std::tie(num_frames, samples) = histogram->collect_after(timestamp);
115     } else if (timestamp == 0) {
116         std::tie(num_frames, samples) = histogram->collect_max(max_frames);
117     } else {
118         std::tie(num_frames, samples) = histogram->collect_max_after(timestamp, max_frames);
119     }
120 
121     auto samples_rebucketed = rebucketTo8Buckets(samples);
122     *out_num_frames = num_frames;
123     if (out_samples && out_samples[2])
124         memcpy(out_samples[2], samples_rebucketed.data(), sizeof(uint64_t) * samples_rebucketed.size());
125 
126     return HWC2::Error::None;
127 }
128 
getAttributes(int32_t * format,int32_t * dataspace,uint8_t * supported_components) const129 HWC2::Error histogram::HistogramCollector::getAttributes(int32_t* format,
130                                                          int32_t* dataspace,
131                                                          uint8_t* supported_components) const {
132     if (!format || !dataspace || !supported_components)
133         return HWC2::Error::BadParameter;
134 
135     *format = HAL_PIXEL_FORMAT_HSV_888;
136     *dataspace = HAL_DATASPACE_UNKNOWN;
137     *supported_components = HWC2_FORMAT_COMPONENT_2;
138     return HWC2::Error::None;
139 }
140 
start()141 void histogram::HistogramCollector::start() {
142     start(implementation_defined_max_frame_ringbuffer);
143 }
144 
start(uint64_t max_frames)145 void histogram::HistogramCollector::start(uint64_t max_frames) {
146     std::unique_lock<decltype(mutex)> lk(mutex);
147     if (started) {
148         return;
149     }
150 
151     started = true;
152     histogram = histogram::Ringbuffer::create(max_frames, std::make_unique<histogram::DefaultTimeKeeper>());
153     monitoring_thread = std::thread(&HistogramCollector::blob_processing_thread, this);
154 }
155 
stop()156 void histogram::HistogramCollector::stop() {
157     std::unique_lock<decltype(mutex)> lk(mutex);
158     if (!started) {
159         return;
160     }
161 
162     started = false;
163     cv.notify_all();
164     lk.unlock();
165 
166     if (monitoring_thread.joinable())
167         monitoring_thread.join();
168 }
169 
notify_histogram_event(int blob_source_fd,BlobId id)170 void histogram::HistogramCollector::notify_histogram_event(int blob_source_fd, BlobId id) {
171     std::unique_lock<decltype(mutex)> lk(mutex);
172     if (!started) {
173       ALOGW("Discarding event blob-id: %X", id);
174       return;
175     }
176     if (work_available) {
177       ALOGI("notified of histogram event before consuming last one. prior event discarded");
178     }
179 
180     work_available = true;
181     blobwork = HistogramCollector::BlobWork{blob_source_fd, id};
182     cv.notify_all();
183 }
184 
blob_processing_thread()185 void histogram::HistogramCollector::blob_processing_thread() {
186     pthread_setname_np(pthread_self(), "histogram_blob");
187 
188     std::unique_lock<decltype(mutex)> lk(mutex);
189 
190     while (true) {
191         cv.wait(lk, [this] { return !started || work_available; });
192         if (!started) {
193             return;
194         }
195 
196         auto work = blobwork;
197         work_available = false;
198         lk.unlock();
199 
200         drmModePropertyBlobPtr blob = drmModeGetPropertyBlob(work.fd, work.id);
201         if (!blob) {
202             lk.lock();
203             continue;
204         }
205         histogram->insert(*static_cast<struct drm_msm_hist*>(blob->data));
206         drmModeFreePropertyBlob(blob);
207 
208         lk.lock();
209     }
210 }
211