blob: 7e4f95bc92747cdf2e15a230bfcc9756c3ac9b52 [file] [log] [blame]
Mike Lockwoodc59b2f92012-10-24 12:31:10 -07001/*
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>
Umair Khancfed2322014-01-15 08:08:50 -050021#include <stdlib.h>
22#include <string.h>
John Reck4de6e742023-11-14 18:32:32 -050023#include <getopt.h>
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070024
25#include <linux/fb.h>
26#include <sys/ioctl.h>
27#include <sys/mman.h>
Dichen Zhangd31f2192020-03-12 12:25:09 -070028#include <sys/wait.h>
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070029
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040030#include <android/bitmap.h>
31
Mathias Agopian0678a8c2013-03-19 20:56:00 -070032#include <binder/ProcessState.h>
33
Dominik Laskowski622c4ae2023-05-26 12:10:16 -040034#include <ftl/concat.h>
35#include <ftl/optional.h>
John Reck4de6e742023-11-14 18:32:32 -050036#include <gui/DisplayCaptureArgs.h>
Chavi Weingarten797bdc92020-09-10 20:55:11 +000037#include <gui/ISurfaceComposer.h>
chaviwbc100492020-08-18 16:06:40 -070038#include <gui/SurfaceComposerClient.h>
39#include <gui/SyncScreenCaptureListener.h>
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070040
Peiyong Lin10a34d12018-09-19 13:56:12 -070041#include <ui/GraphicTypes.h>
Mathias Agopian0137fb82013-03-20 15:38:07 -070042#include <ui/PixelFormat.h>
43
Romain Guy26a2b972017-04-17 09:39:51 -070044#include <system/graphics.h>
45
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070046using namespace android;
47
Romain Guy26a2b972017-04-17 09:39:51 -070048#define COLORSPACE_UNKNOWN 0
49#define COLORSPACE_SRGB 1
50#define COLORSPACE_DISPLAY_P3 2
51
Dominik Laskowski622c4ae2023-05-26 12:10:16 -040052void usage(const char* pname, ftl::Optional<DisplayId> displayIdOpt) {
John Reck4de6e742023-11-14 18:32:32 -050053 fprintf(stderr, R"(
Yein Joe644f582024-02-15 17:55:15 +000054usage: %s [-ahp] [-d display-id] [FILENAME]
John Reck4de6e742023-11-14 18:32:32 -050055 -h: this message
Yein Joe644f582024-02-15 17:55:15 +000056 -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.
John Reck4de6e742023-11-14 18:32:32 -050058 -d: specify the display ID to capture%s
59 see "dumpsys SurfaceFlinger --display-id" for valid display IDs.
Yein Joe644f582024-02-15 17:55:15 +000060 -p: outputs in png format.
John Reck4de6e742023-11-14 18:32:32 -050061 --hint-for-seamless If set will use the hintForSeamless path in SF
62
63If FILENAME ends with .png it will be saved as a png.
64If FILENAME is not given, the results will be printed to stdout.
65)",
Dominik Laskowski622c4ae2023-05-26 12:10:16 -040066 pname,
67 displayIdOpt
Yein Joe644f582024-02-15 17:55:15 +000068 .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());
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070075}
76
John Reck4de6e742023-11-14 18:32:32 -050077// 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)
79namespace LongOpts {
80enum {
81 Reserved = 255,
82 HintForSeamless,
83};
84}
85
86static 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
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040092static int32_t flinger2bitmapFormat(PixelFormat f)
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070093{
94 switch (f) {
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070095 case PIXEL_FORMAT_RGB_565:
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040096 return ANDROID_BITMAP_FORMAT_RGB_565;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070097 default:
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040098 return ANDROID_BITMAP_FORMAT_RGBA_8888;
Romain Guy26a2b972017-04-17 09:39:51 -070099 }
100}
101
Peiyong Lin10a34d12018-09-19 13:56:12 -0700102static uint32_t dataSpaceToInt(ui::Dataspace d)
Romain Guy26a2b972017-04-17 09:39:51 -0700103{
104 switch (d) {
Peiyong Lin10a34d12018-09-19 13:56:12 -0700105 case ui::Dataspace::V0_SRGB:
Romain Guy26a2b972017-04-17 09:39:51 -0700106 return COLORSPACE_SRGB;
Peiyong Lin10a34d12018-09-19 13:56:12 -0700107 case ui::Dataspace::DISPLAY_P3:
Romain Guy26a2b972017-04-17 09:39:51 -0700108 return COLORSPACE_DISPLAY_P3;
109 default:
110 return COLORSPACE_UNKNOWN;
111 }
112}
113
Umair Khancfed2322014-01-15 08:08:50 -0500114static status_t notifyMediaScanner(const char* fileName) {
Dichen Zhangd31f2192020-03-12 12:25:09 -0700115 std::string filePath("file://");
116 filePath.append(fileName);
Dichen Zhangd31f2192020-03-12 12:25:09 -0700117 char *cmd[] = {
118 (char*) "am",
119 (char*) "broadcast",
Dichen Zhange361a262020-04-17 10:05:49 -0700120 (char*) "-a",
Dichen Zhangd31f2192020-03-12 12:25:09 -0700121 (char*) "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
122 (char*) "-d",
George Burgess IV5c46fb62020-03-16 12:07:30 -0700123 &filePath[0],
Dichen Zhangd31f2192020-03-12 12:25:09 -0700124 nullptr
125 };
126
127 int status;
128 int pid = fork();
129 if (pid < 0){
Yein Joe644f582024-02-15 17:55:15 +0000130 fprintf(stderr, "Unable to fork in order to send intent for media scanner.\n");
131 return UNKNOWN_ERROR;
Dichen Zhangd31f2192020-03-12 12:25:09 -0700132 }
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) {
Umair Khancfed2322014-01-15 08:08:50 -0500147 fprintf(stderr, "Unable to broadcast intent for media scanner.\n");
148 return UNKNOWN_ERROR;
149 }
150 return NO_ERROR;
151}
152
Yein Joe644f582024-02-15 17:55:15 +0000153status_t capture(const DisplayId displayId,
154 const gui::CaptureArgs& captureArgs,
155 ScreenCaptureResults& outResult) {
chaviwbc100492020-08-18 16:06:40 -0700156 sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
Yein Joe644f582024-02-15 17:55:15 +0000157 ScreenshotClient::captureDisplay(displayId, captureArgs, captureListener);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700158
chaviwbc100492020-08-18 16:06:40 -0700159 ScreenCaptureResults captureResults = captureListener->waitForResults();
Patrick Williams8d455722022-08-19 14:31:26 +0000160 if (!captureResults.fenceResult.ok()) {
jeimysantiago8ee92d12023-07-21 15:40:13 +0000161 fprintf(stderr, "Failed to take screenshot. Status: %d\n",
Yein Joe644f582024-02-15 17:55:15 +0000162 fenceStatus(captureResults.fenceResult));
chaviwbc100492020-08-18 16:06:40 -0700163 return 1;
164 }
Yein Joe644f582024-02-15 17:55:15 +0000165
166 outResult = captureResults;
167
168 return 0;
169}
170
171status_t saveImage(const char* fn, bool png, const ScreenCaptureResults& captureResults) {
172 void* base = nullptr;
chaviwbc27bc72020-07-27 16:44:35 -0700173 ui::Dataspace dataspace = captureResults.capturedDataspace;
174 sp<GraphicBuffer> buffer = captureResults.buffer;
175
jeimysantiago8ee92d12023-07-21 15:40:13 +0000176 status_t result = buffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN, &base);
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000177
chaviw7f4dc7e2018-09-11 13:59:30 -0700178 if (base == nullptr || result != NO_ERROR) {
179 String8 reason;
chaviwa69a1b82019-04-30 16:53:33 -0700180 if (result != NO_ERROR) {
181 reason.appendFormat(" Error Code: %d", result);
chaviw7f4dc7e2018-09-11 13:59:30 -0700182 } else {
chaviwa69a1b82019-04-30 16:53:33 -0700183 reason = "Failed to write to buffer";
chaviw7f4dc7e2018-09-11 13:59:30 -0700184 }
185 fprintf(stderr, "Failed to take screenshot (%s)\n", reason.c_str());
Steven Morelanda89ae862018-05-24 17:48:28 -0700186 return 1;
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000187 }
188
Yein Joe644f582024-02-15 17:55:15 +0000189 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
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000204 if (png) {
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400205 AndroidBitmapInfo info;
chaviwbc27bc72020-07-27 16:44:35 -0700206 info.format = flinger2bitmapFormat(buffer->getPixelFormat());
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400207 info.flags = ANDROID_BITMAP_FLAGS_ALPHA_PREMUL;
chaviwbc27bc72020-07-27 16:44:35 -0700208 info.width = buffer->getWidth();
209 info.height = buffer->getHeight();
210 info.stride = buffer->getStride() * bytesPerPixel(buffer->getPixelFormat());
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400211
chaviwbc27bc72020-07-27 16:44:35 -0700212 int result = AndroidBitmap_compress(&info, static_cast<int32_t>(dataspace), base,
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400213 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
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000224 if (fn != NULL) {
225 notifyMediaScanner(fn);
226 }
227 } else {
chaviwbc27bc72020-07-27 16:44:35 -0700228 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);
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400233
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000234 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);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700242 }
243 }
244 close(fd);
Josh Gao90982582017-06-19 13:38:20 -0700245
Steven Morelanda89ae862018-05-24 17:48:28 -0700246 return 0;
Peiyong Lin10a34d12018-09-19 13:56:12 -0700247}
Yein Joe644f582024-02-15 17:55:15 +0000248
249int 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}