1 /*
2 * Copyright (C) 2010 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 <errno.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <getopt.h>
24
25 #include <linux/fb.h>
26 #include <sys/ioctl.h>
27 #include <sys/mman.h>
28 #include <sys/wait.h>
29
30 #include <android/bitmap.h>
31
32 #include <binder/ProcessState.h>
33
34 #include <ftl/concat.h>
35 #include <ftl/optional.h>
36 #include <gui/DisplayCaptureArgs.h>
37 #include <gui/ISurfaceComposer.h>
38 #include <gui/SurfaceComposerClient.h>
39 #include <gui/SyncScreenCaptureListener.h>
40
41 #include <ui/GraphicTypes.h>
42 #include <ui/PixelFormat.h>
43
44 #include <system/graphics.h>
45
46 using namespace android;
47
48 #define COLORSPACE_UNKNOWN 0
49 #define COLORSPACE_SRGB 1
50 #define COLORSPACE_DISPLAY_P3 2
51
usage(const char * pname,ftl::Optional<DisplayId> displayIdOpt)52 void usage(const char* pname, ftl::Optional<DisplayId> displayIdOpt) {
53 fprintf(stderr, R"(
54 usage: %s [-ahp] [-d display-id] [FILENAME]
55 -h: this message
56 -a: captures all the active displays. This appends an integer postfix to the FILENAME.
57 e.g., FILENAME_0.png, FILENAME_1.png. If both -a and -d are given, it ignores -d.
58 -d: specify the display ID to capture%s
59 see "dumpsys SurfaceFlinger --display-id" for valid display IDs.
60 -p: outputs in png format.
61 --hint-for-seamless If set will use the hintForSeamless path in SF
62
63 If FILENAME ends with .png it will be saved as a png.
64 If FILENAME is not given, the results will be printed to stdout.
65 )",
66 pname,
67 displayIdOpt
68 .transform([](DisplayId id) {
69 return std::string(ftl::Concat(
70 " (If the id is not given, it defaults to ", id.value,')'
71 ).str());
72 })
73 .value_or(std::string())
74 .c_str());
75 }
76
77 // For options that only exist in long-form. Anything in the
78 // 0-255 range is reserved for short options (which just use their ASCII value)
79 namespace LongOpts {
80 enum {
81 Reserved = 255,
82 HintForSeamless,
83 };
84 }
85
86 static const struct option LONG_OPTIONS[] = {
87 {"png", no_argument, nullptr, 'p'},
88 {"help", no_argument, nullptr, 'h'},
89 {"hint-for-seamless", no_argument, nullptr, LongOpts::HintForSeamless},
90 {0, 0, 0, 0}};
91
flinger2bitmapFormat(PixelFormat f)92 static int32_t flinger2bitmapFormat(PixelFormat f)
93 {
94 switch (f) {
95 case PIXEL_FORMAT_RGB_565:
96 return ANDROID_BITMAP_FORMAT_RGB_565;
97 default:
98 return ANDROID_BITMAP_FORMAT_RGBA_8888;
99 }
100 }
101
dataSpaceToInt(ui::Dataspace d)102 static uint32_t dataSpaceToInt(ui::Dataspace d)
103 {
104 switch (d) {
105 case ui::Dataspace::V0_SRGB:
106 return COLORSPACE_SRGB;
107 case ui::Dataspace::DISPLAY_P3:
108 return COLORSPACE_DISPLAY_P3;
109 default:
110 return COLORSPACE_UNKNOWN;
111 }
112 }
113
notifyMediaScanner(const char * fileName)114 static status_t notifyMediaScanner(const char* fileName) {
115 std::string filePath("file://");
116 filePath.append(fileName);
117 char *cmd[] = {
118 (char*) "am",
119 (char*) "broadcast",
120 (char*) "-a",
121 (char*) "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
122 (char*) "-d",
123 &filePath[0],
124 nullptr
125 };
126
127 int status;
128 int pid = fork();
129 if (pid < 0){
130 fprintf(stderr, "Unable to fork in order to send intent for media scanner.\n");
131 return UNKNOWN_ERROR;
132 }
133 if (pid == 0){
134 int fd = open("/dev/null", O_WRONLY);
135 if (fd < 0){
136 fprintf(stderr, "Unable to open /dev/null for media scanner stdout redirection.\n");
137 exit(1);
138 }
139 dup2(fd, 1);
140 int result = execvp(cmd[0], cmd);
141 close(fd);
142 exit(result);
143 }
144 wait(&status);
145
146 if (status < 0) {
147 fprintf(stderr, "Unable to broadcast intent for media scanner.\n");
148 return UNKNOWN_ERROR;
149 }
150 return NO_ERROR;
151 }
152
capture(const DisplayId displayId,const gui::CaptureArgs & captureArgs,ScreenCaptureResults & outResult)153 status_t capture(const DisplayId displayId,
154 const gui::CaptureArgs& captureArgs,
155 ScreenCaptureResults& outResult) {
156 sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
157 ScreenshotClient::captureDisplay(displayId, captureArgs, captureListener);
158
159 ScreenCaptureResults captureResults = captureListener->waitForResults();
160 if (!captureResults.fenceResult.ok()) {
161 fprintf(stderr, "Failed to take screenshot. Status: %d\n",
162 fenceStatus(captureResults.fenceResult));
163 return 1;
164 }
165
166 outResult = captureResults;
167
168 return 0;
169 }
170
saveImage(const char * fn,bool png,const ScreenCaptureResults & captureResults)171 status_t saveImage(const char* fn, bool png, const ScreenCaptureResults& captureResults) {
172 void* base = nullptr;
173 ui::Dataspace dataspace = captureResults.capturedDataspace;
174 sp<GraphicBuffer> buffer = captureResults.buffer;
175
176 status_t result = buffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN, &base);
177
178 if (base == nullptr || result != NO_ERROR) {
179 String8 reason;
180 if (result != NO_ERROR) {
181 reason.appendFormat(" Error Code: %d", result);
182 } else {
183 reason = "Failed to write to buffer";
184 }
185 fprintf(stderr, "Failed to take screenshot (%s)\n", reason.c_str());
186 return 1;
187 }
188
189 int fd = -1;
190 if (fn == nullptr) {
191 fd = dup(STDOUT_FILENO);
192 if (fd == -1) {
193 fprintf(stderr, "Error writing to stdout. (%s)\n", strerror(errno));
194 return 1;
195 }
196 } else {
197 fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0664);
198 if (fd == -1) {
199 fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
200 return 1;
201 }
202 }
203
204 if (png) {
205 AndroidBitmapInfo info;
206 info.format = flinger2bitmapFormat(buffer->getPixelFormat());
207 info.flags = ANDROID_BITMAP_FLAGS_ALPHA_PREMUL;
208 info.width = buffer->getWidth();
209 info.height = buffer->getHeight();
210 info.stride = buffer->getStride() * bytesPerPixel(buffer->getPixelFormat());
211
212 int result = AndroidBitmap_compress(&info, static_cast<int32_t>(dataspace), base,
213 ANDROID_BITMAP_COMPRESS_FORMAT_PNG, 100, &fd,
214 [](void* fdPtr, const void* data, size_t size) -> bool {
215 int bytesWritten = write(*static_cast<int*>(fdPtr),
216 data, size);
217 return bytesWritten == size;
218 });
219
220 if (result != ANDROID_BITMAP_RESULT_SUCCESS) {
221 fprintf(stderr, "Failed to compress PNG (error code: %d)\n", result);
222 }
223
224 if (fn != NULL) {
225 notifyMediaScanner(fn);
226 }
227 } else {
228 uint32_t w = buffer->getWidth();
229 uint32_t h = buffer->getHeight();
230 uint32_t s = buffer->getStride();
231 uint32_t f = buffer->getPixelFormat();
232 uint32_t c = dataSpaceToInt(dataspace);
233
234 write(fd, &w, 4);
235 write(fd, &h, 4);
236 write(fd, &f, 4);
237 write(fd, &c, 4);
238 size_t Bpp = bytesPerPixel(f);
239 for (size_t y=0 ; y<h ; y++) {
240 write(fd, base, w*Bpp);
241 base = (void *)((char *)base + s*Bpp);
242 }
243 }
244 close(fd);
245
246 return 0;
247 }
248
main(int argc,char ** argv)249 int main(int argc, char** argv)
250 {
251 const std::vector<PhysicalDisplayId> physicalDisplays =
252 SurfaceComposerClient::getPhysicalDisplayIds();
253
254 if (physicalDisplays.empty()) {
255 fprintf(stderr, "Failed to get ID for any displays.\n");
256 return 1;
257 }
258 std::optional<DisplayId> displayIdOpt;
259 std::vector<DisplayId> displaysToCapture;
260 gui::CaptureArgs captureArgs;
261 const char* pname = argv[0];
262 bool png = false;
263 bool all = false;
264 int c;
265 while ((c = getopt_long(argc, argv, "aphd:", LONG_OPTIONS, nullptr)) != -1) {
266 switch (c) {
267 case 'p':
268 png = true;
269 break;
270 case 'd': {
271 errno = 0;
272 char* end = nullptr;
273 const uint64_t id = strtoull(optarg, &end, 10);
274 if (!end || *end != '\0' || errno == ERANGE) {
275 fprintf(stderr, "Invalid display ID: Out of range [0, 2^64).\n");
276 return 1;
277 }
278
279 displayIdOpt = DisplayId::fromValue(id);
280 if (!displayIdOpt) {
281 fprintf(stderr, "Invalid display ID: Incorrect encoding.\n");
282 return 1;
283 }
284 displaysToCapture.push_back(displayIdOpt.value());
285 break;
286 }
287 case 'a': {
288 all = true;
289 break;
290 }
291 case '?':
292 case 'h':
293 if (physicalDisplays.size() >= 1) {
294 displayIdOpt = physicalDisplays.front();
295 }
296 usage(pname, displayIdOpt);
297 return 1;
298 case LongOpts::HintForSeamless:
299 captureArgs.hintForSeamlessTransition = true;
300 break;
301 }
302 }
303
304 argc -= optind;
305 argv += optind;
306
307 // We don't expect more than 2 arguments.
308 if (argc >= 2) {
309 if (physicalDisplays.size() >= 1) {
310 usage(pname, physicalDisplays.front());
311 } else {
312 usage(pname, std::nullopt);
313 }
314 return 1;
315 }
316
317 std::string baseName;
318 std::string suffix;
319
320 if (argc == 1) {
321 std::string_view filename = { argv[0] };
322 if (filename.ends_with(".png")) {
323 baseName = filename.substr(0, filename.size()-4);
324 suffix = ".png";
325 png = true;
326 } else {
327 baseName = filename;
328 }
329 }
330
331 if (all) {
332 // Ignores -d if -a is given.
333 displaysToCapture.clear();
334 for (int i = 0; i < physicalDisplays.size(); i++) {
335 displaysToCapture.push_back(physicalDisplays[i]);
336 }
337 }
338
339 if (displaysToCapture.empty()) {
340 displaysToCapture.push_back(physicalDisplays.front());
341 if (physicalDisplays.size() > 1) {
342 fprintf(stderr,
343 "[Warning] Multiple displays were found, but no display id was specified! "
344 "Defaulting to the first display found, however this default is not guaranteed "
345 "to be consistent across captures. A display id should be specified.\n");
346 fprintf(stderr, "A display ID can be specified with the [-d display-id] option.\n");
347 fprintf(stderr, "See \"dumpsys SurfaceFlinger --display-id\" for valid display IDs.\n");
348 }
349 }
350
351 // setThreadPoolMaxThreadCount(0) actually tells the kernel it's
352 // not allowed to spawn any additional threads, but we still spawn
353 // a binder thread from userspace when we call startThreadPool().
354 // See b/36066697 for rationale
355 ProcessState::self()->setThreadPoolMaxThreadCount(0);
356 ProcessState::self()->startThreadPool();
357
358 std::vector<ScreenCaptureResults> results;
359 const size_t numDisplays = displaysToCapture.size();
360 for (int i=0; i<numDisplays; i++) {
361 ScreenCaptureResults result;
362
363 // 1. Capture the screen
364 if (const status_t captureStatus =
365 capture(displaysToCapture[i], captureArgs, result) != 0) {
366
367 fprintf(stderr, "Capturing failed.\n");
368 return captureStatus;
369 }
370
371 // 2. Save the capture result as an image.
372 // When there's more than one file to capture, add the index as postfix.
373 std::string filename;
374 if (!baseName.empty()) {
375 filename = baseName;
376 if (numDisplays > 1) {
377 filename += "_";
378 filename += std::to_string(i);
379 }
380 filename += suffix;
381 }
382 const char* fn = nullptr;
383 if (!filename.empty()) {
384 fn = filename.c_str();
385 }
386 if (const status_t saveImageStatus = saveImage(fn, png, result) != 0) {
387 fprintf(stderr, "Saving image failed.\n");
388 return saveImageStatus;
389 }
390 }
391
392 return 0;
393 }
394