blob: 2d235331a672c2587a76bfe7d5f20b7b750f8d85 [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>
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070023
24#include <linux/fb.h>
25#include <sys/ioctl.h>
26#include <sys/mman.h>
Dichen Zhangd31f2192020-03-12 12:25:09 -070027#include <sys/wait.h>
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070028
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040029#include <android/bitmap.h>
30
Mathias Agopian0678a8c2013-03-19 20:56:00 -070031#include <binder/ProcessState.h>
32
Dominik Laskowski622c4ae2023-05-26 12:10:16 -040033#include <ftl/concat.h>
34#include <ftl/optional.h>
Chavi Weingarten797bdc92020-09-10 20:55:11 +000035#include <gui/ISurfaceComposer.h>
chaviwbc100492020-08-18 16:06:40 -070036#include <gui/SurfaceComposerClient.h>
37#include <gui/SyncScreenCaptureListener.h>
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070038
Peiyong Lin10a34d12018-09-19 13:56:12 -070039#include <ui/GraphicTypes.h>
Mathias Agopian0137fb82013-03-20 15:38:07 -070040#include <ui/PixelFormat.h>
41
Romain Guy26a2b972017-04-17 09:39:51 -070042#include <system/graphics.h>
43
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070044using namespace android;
45
Romain Guy26a2b972017-04-17 09:39:51 -070046#define COLORSPACE_UNKNOWN 0
47#define COLORSPACE_SRGB 1
48#define COLORSPACE_DISPLAY_P3 2
49
Dominik Laskowski622c4ae2023-05-26 12:10:16 -040050void usage(const char* pname, ftl::Optional<DisplayId> displayIdOpt) {
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070051 fprintf(stderr,
52 "usage: %s [-hp] [-d display-id] [FILENAME]\n"
53 " -h: this message\n"
54 " -p: save the file as a png.\n"
Huihong Luo41ea7d12022-09-26 11:32:52 -070055 " -d: specify the display ID to capture%s\n"
Dominik Laskowski3316a0a2019-01-25 02:56:41 -080056 " see \"dumpsys SurfaceFlinger --display-id\" for valid display IDs.\n"
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070057 "If FILENAME ends with .png it will be saved as a png.\n"
58 "If FILENAME is not given, the results will be printed to stdout.\n",
Dominik Laskowski622c4ae2023-05-26 12:10:16 -040059 pname,
60 displayIdOpt
61 .transform([](DisplayId id) {
62 return std::string(ftl::Concat(" (default: ", id.value, ')').str());
63 })
64 .value_or(std::string())
65 .c_str());
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070066}
67
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040068static int32_t flinger2bitmapFormat(PixelFormat f)
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070069{
70 switch (f) {
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070071 case PIXEL_FORMAT_RGB_565:
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040072 return ANDROID_BITMAP_FORMAT_RGB_565;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070073 default:
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040074 return ANDROID_BITMAP_FORMAT_RGBA_8888;
Romain Guy26a2b972017-04-17 09:39:51 -070075 }
76}
77
Peiyong Lin10a34d12018-09-19 13:56:12 -070078static uint32_t dataSpaceToInt(ui::Dataspace d)
Romain Guy26a2b972017-04-17 09:39:51 -070079{
80 switch (d) {
Peiyong Lin10a34d12018-09-19 13:56:12 -070081 case ui::Dataspace::V0_SRGB:
Romain Guy26a2b972017-04-17 09:39:51 -070082 return COLORSPACE_SRGB;
Peiyong Lin10a34d12018-09-19 13:56:12 -070083 case ui::Dataspace::DISPLAY_P3:
Romain Guy26a2b972017-04-17 09:39:51 -070084 return COLORSPACE_DISPLAY_P3;
85 default:
86 return COLORSPACE_UNKNOWN;
87 }
88}
89
Umair Khancfed2322014-01-15 08:08:50 -050090static status_t notifyMediaScanner(const char* fileName) {
Dichen Zhangd31f2192020-03-12 12:25:09 -070091 std::string filePath("file://");
92 filePath.append(fileName);
Dichen Zhangd31f2192020-03-12 12:25:09 -070093 char *cmd[] = {
94 (char*) "am",
95 (char*) "broadcast",
Dichen Zhange361a262020-04-17 10:05:49 -070096 (char*) "-a",
Dichen Zhangd31f2192020-03-12 12:25:09 -070097 (char*) "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
98 (char*) "-d",
George Burgess IV5c46fb62020-03-16 12:07:30 -070099 &filePath[0],
Dichen Zhangd31f2192020-03-12 12:25:09 -0700100 nullptr
101 };
102
103 int status;
104 int pid = fork();
105 if (pid < 0){
106 fprintf(stderr, "Unable to fork in order to send intent for media scanner.\n");
107 return UNKNOWN_ERROR;
108 }
109 if (pid == 0){
110 int fd = open("/dev/null", O_WRONLY);
111 if (fd < 0){
112 fprintf(stderr, "Unable to open /dev/null for media scanner stdout redirection.\n");
113 exit(1);
114 }
115 dup2(fd, 1);
116 int result = execvp(cmd[0], cmd);
117 close(fd);
118 exit(result);
119 }
120 wait(&status);
121
122 if (status < 0) {
Umair Khancfed2322014-01-15 08:08:50 -0500123 fprintf(stderr, "Unable to broadcast intent for media scanner.\n");
124 return UNKNOWN_ERROR;
125 }
126 return NO_ERROR;
127}
128
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700129int main(int argc, char** argv)
130{
Huihong Luo41ea7d12022-09-26 11:32:52 -0700131 const std::vector<PhysicalDisplayId> ids = SurfaceComposerClient::getPhysicalDisplayIds();
132 if (ids.empty()) {
133 fprintf(stderr, "Failed to get ID for any displays.\n");
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800134 return 1;
135 }
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400136 std::optional<DisplayId> displayIdOpt;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700137 const char* pname = argv[0];
138 bool png = false;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700139 int c;
140 while ((c = getopt(argc, argv, "phd:")) != -1) {
141 switch (c) {
142 case 'p':
143 png = true;
144 break;
Dominik Laskowskid8dc5b32023-09-28 17:10:47 -0400145 case 'd': {
146 errno = 0;
147 char* end = nullptr;
148 const uint64_t id = strtoull(optarg, &end, 10);
149 if (!end || *end != '\0' || errno == ERANGE) {
150 fprintf(stderr, "Invalid display ID: Out of range [0, 2^64).\n");
151 return 1;
152 }
153
154 displayIdOpt = DisplayId::fromValue(id);
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400155 if (!displayIdOpt) {
Dominik Laskowskid8dc5b32023-09-28 17:10:47 -0400156 fprintf(stderr, "Invalid display ID: Incorrect encoding.\n");
Dominik Laskowski0bda2e32021-03-23 16:24:01 -0700157 return 1;
158 }
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700159 break;
Dominik Laskowskid8dc5b32023-09-28 17:10:47 -0400160 }
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700161 case '?':
162 case 'h':
Huihong Luo41ea7d12022-09-26 11:32:52 -0700163 if (ids.size() == 1) {
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400164 displayIdOpt = ids.front();
165 }
166 usage(pname, displayIdOpt);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700167 return 1;
168 }
169 }
Huihong Luo41ea7d12022-09-26 11:32:52 -0700170
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400171 if (!displayIdOpt) {
172 displayIdOpt = ids.front();
Huihong Luo6f645f72022-10-07 19:24:00 -0700173 if (ids.size() > 1) {
174 fprintf(stderr,
175 "[Warning] Multiple displays were found, but no display id was specified! "
176 "Defaulting to the first display found, however this default is not guaranteed "
177 "to be consistent across captures. A display id should be specified.\n");
178 fprintf(stderr, "A display ID can be specified with the [-d display-id] option.\n");
Huihong Luo41ea7d12022-09-26 11:32:52 -0700179 fprintf(stderr, "See \"dumpsys SurfaceFlinger --display-id\" for valid display IDs.\n");
Huihong Luo41ea7d12022-09-26 11:32:52 -0700180 }
181 }
182
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700183 argc -= optind;
184 argv += optind;
185
186 int fd = -1;
Andreas Gampecfedceb2014-09-30 21:48:18 -0700187 const char* fn = NULL;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700188 if (argc == 0) {
189 fd = dup(STDOUT_FILENO);
190 } else if (argc == 1) {
Umair Khancfed2322014-01-15 08:08:50 -0500191 fn = argv[0];
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700192 fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0664);
193 if (fd == -1) {
194 fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
195 return 1;
196 }
197 const int len = strlen(fn);
198 if (len >= 4 && 0 == strcmp(fn+len-4, ".png")) {
199 png = true;
200 }
201 }
Prathmesh Prabhubf89ae52016-03-10 15:23:34 -0800202
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700203 if (fd == -1) {
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400204 usage(pname, displayIdOpt);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700205 return 1;
206 }
207
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000208 void* base = NULL;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700209
Martijn Coenen48b74082017-07-24 09:19:26 +0200210 // setThreadPoolMaxThreadCount(0) actually tells the kernel it's
211 // not allowed to spawn any additional threads, but we still spawn
212 // a binder thread from userspace when we call startThreadPool().
213 // See b/36066697 for rationale
214 ProcessState::self()->setThreadPoolMaxThreadCount(0);
215 ProcessState::self()->startThreadPool();
216
chaviwbc100492020-08-18 16:06:40 -0700217 sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
jeimysantiago8ee92d12023-07-21 15:40:13 +0000218 ScreenshotClient::captureDisplay(*displayIdOpt, captureListener);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700219
chaviwbc100492020-08-18 16:06:40 -0700220 ScreenCaptureResults captureResults = captureListener->waitForResults();
Patrick Williams8d455722022-08-19 14:31:26 +0000221 if (!captureResults.fenceResult.ok()) {
chaviwbc100492020-08-18 16:06:40 -0700222 close(fd);
jeimysantiago8ee92d12023-07-21 15:40:13 +0000223 fprintf(stderr, "Failed to take screenshot. Status: %d\n",
224 fenceStatus(captureResults.fenceResult));
chaviwbc100492020-08-18 16:06:40 -0700225 return 1;
226 }
chaviwbc27bc72020-07-27 16:44:35 -0700227 ui::Dataspace dataspace = captureResults.capturedDataspace;
228 sp<GraphicBuffer> buffer = captureResults.buffer;
229
jeimysantiago8ee92d12023-07-21 15:40:13 +0000230 status_t result = buffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN, &base);
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000231
chaviw7f4dc7e2018-09-11 13:59:30 -0700232 if (base == nullptr || result != NO_ERROR) {
233 String8 reason;
chaviwa69a1b82019-04-30 16:53:33 -0700234 if (result != NO_ERROR) {
235 reason.appendFormat(" Error Code: %d", result);
chaviw7f4dc7e2018-09-11 13:59:30 -0700236 } else {
chaviwa69a1b82019-04-30 16:53:33 -0700237 reason = "Failed to write to buffer";
chaviw7f4dc7e2018-09-11 13:59:30 -0700238 }
239 fprintf(stderr, "Failed to take screenshot (%s)\n", reason.c_str());
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000240 close(fd);
Steven Morelanda89ae862018-05-24 17:48:28 -0700241 return 1;
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000242 }
243
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000244 if (png) {
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400245 AndroidBitmapInfo info;
chaviwbc27bc72020-07-27 16:44:35 -0700246 info.format = flinger2bitmapFormat(buffer->getPixelFormat());
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400247 info.flags = ANDROID_BITMAP_FLAGS_ALPHA_PREMUL;
chaviwbc27bc72020-07-27 16:44:35 -0700248 info.width = buffer->getWidth();
249 info.height = buffer->getHeight();
250 info.stride = buffer->getStride() * bytesPerPixel(buffer->getPixelFormat());
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400251
chaviwbc27bc72020-07-27 16:44:35 -0700252 int result = AndroidBitmap_compress(&info, static_cast<int32_t>(dataspace), base,
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400253 ANDROID_BITMAP_COMPRESS_FORMAT_PNG, 100, &fd,
254 [](void* fdPtr, const void* data, size_t size) -> bool {
255 int bytesWritten = write(*static_cast<int*>(fdPtr),
256 data, size);
257 return bytesWritten == size;
258 });
259
260 if (result != ANDROID_BITMAP_RESULT_SUCCESS) {
261 fprintf(stderr, "Failed to compress PNG (error code: %d)\n", result);
262 }
263
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000264 if (fn != NULL) {
265 notifyMediaScanner(fn);
266 }
267 } else {
chaviwbc27bc72020-07-27 16:44:35 -0700268 uint32_t w = buffer->getWidth();
269 uint32_t h = buffer->getHeight();
270 uint32_t s = buffer->getStride();
271 uint32_t f = buffer->getPixelFormat();
272 uint32_t c = dataSpaceToInt(dataspace);
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400273
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000274 write(fd, &w, 4);
275 write(fd, &h, 4);
276 write(fd, &f, 4);
277 write(fd, &c, 4);
278 size_t Bpp = bytesPerPixel(f);
279 for (size_t y=0 ; y<h ; y++) {
280 write(fd, base, w*Bpp);
281 base = (void *)((char *)base + s*Bpp);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700282 }
283 }
284 close(fd);
Josh Gao90982582017-06-19 13:38:20 -0700285
Steven Morelanda89ae862018-05-24 17:48:28 -0700286 return 0;
Peiyong Lin10a34d12018-09-19 13:56:12 -0700287}