blob: 917529ec1dcfa5aa4bddddf6d192e55fbc28cddb [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"(
54usage: %s [-hp] [-d display-id] [FILENAME]
55 -h: this message
56 -p: save the file as a png.
57 -d: specify the display ID to capture%s
58 see "dumpsys SurfaceFlinger --display-id" for valid display IDs.
59 --hint-for-seamless If set will use the hintForSeamless path in SF
60
61If FILENAME ends with .png it will be saved as a png.
62If FILENAME is not given, the results will be printed to stdout.
63)",
Dominik Laskowski622c4ae2023-05-26 12:10:16 -040064 pname,
65 displayIdOpt
66 .transform([](DisplayId id) {
67 return std::string(ftl::Concat(" (default: ", id.value, ')').str());
68 })
69 .value_or(std::string())
70 .c_str());
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070071}
72
John Reck4de6e742023-11-14 18:32:32 -050073// For options that only exist in long-form. Anything in the
74// 0-255 range is reserved for short options (which just use their ASCII value)
75namespace LongOpts {
76enum {
77 Reserved = 255,
78 HintForSeamless,
79};
80}
81
82static const struct option LONG_OPTIONS[] = {
83 {"png", no_argument, nullptr, 'p'},
84 {"help", no_argument, nullptr, 'h'},
85 {"hint-for-seamless", no_argument, nullptr, LongOpts::HintForSeamless},
86 {0, 0, 0, 0}};
87
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040088static int32_t flinger2bitmapFormat(PixelFormat f)
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070089{
90 switch (f) {
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070091 case PIXEL_FORMAT_RGB_565:
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040092 return ANDROID_BITMAP_FORMAT_RGB_565;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -070093 default:
Derek Sollenbergera3ef0942020-04-08 15:47:55 -040094 return ANDROID_BITMAP_FORMAT_RGBA_8888;
Romain Guy26a2b972017-04-17 09:39:51 -070095 }
96}
97
Peiyong Lin10a34d12018-09-19 13:56:12 -070098static uint32_t dataSpaceToInt(ui::Dataspace d)
Romain Guy26a2b972017-04-17 09:39:51 -070099{
100 switch (d) {
Peiyong Lin10a34d12018-09-19 13:56:12 -0700101 case ui::Dataspace::V0_SRGB:
Romain Guy26a2b972017-04-17 09:39:51 -0700102 return COLORSPACE_SRGB;
Peiyong Lin10a34d12018-09-19 13:56:12 -0700103 case ui::Dataspace::DISPLAY_P3:
Romain Guy26a2b972017-04-17 09:39:51 -0700104 return COLORSPACE_DISPLAY_P3;
105 default:
106 return COLORSPACE_UNKNOWN;
107 }
108}
109
Umair Khancfed2322014-01-15 08:08:50 -0500110static status_t notifyMediaScanner(const char* fileName) {
Dichen Zhangd31f2192020-03-12 12:25:09 -0700111 std::string filePath("file://");
112 filePath.append(fileName);
Dichen Zhangd31f2192020-03-12 12:25:09 -0700113 char *cmd[] = {
114 (char*) "am",
115 (char*) "broadcast",
Dichen Zhange361a262020-04-17 10:05:49 -0700116 (char*) "-a",
Dichen Zhangd31f2192020-03-12 12:25:09 -0700117 (char*) "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
118 (char*) "-d",
George Burgess IV5c46fb62020-03-16 12:07:30 -0700119 &filePath[0],
Dichen Zhangd31f2192020-03-12 12:25:09 -0700120 nullptr
121 };
122
123 int status;
124 int pid = fork();
125 if (pid < 0){
126 fprintf(stderr, "Unable to fork in order to send intent for media scanner.\n");
127 return UNKNOWN_ERROR;
128 }
129 if (pid == 0){
130 int fd = open("/dev/null", O_WRONLY);
131 if (fd < 0){
132 fprintf(stderr, "Unable to open /dev/null for media scanner stdout redirection.\n");
133 exit(1);
134 }
135 dup2(fd, 1);
136 int result = execvp(cmd[0], cmd);
137 close(fd);
138 exit(result);
139 }
140 wait(&status);
141
142 if (status < 0) {
Umair Khancfed2322014-01-15 08:08:50 -0500143 fprintf(stderr, "Unable to broadcast intent for media scanner.\n");
144 return UNKNOWN_ERROR;
145 }
146 return NO_ERROR;
147}
148
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700149int main(int argc, char** argv)
150{
Huihong Luo41ea7d12022-09-26 11:32:52 -0700151 const std::vector<PhysicalDisplayId> ids = SurfaceComposerClient::getPhysicalDisplayIds();
152 if (ids.empty()) {
153 fprintf(stderr, "Failed to get ID for any displays.\n");
Dominik Laskowski3316a0a2019-01-25 02:56:41 -0800154 return 1;
155 }
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400156 std::optional<DisplayId> displayIdOpt;
John Reck4de6e742023-11-14 18:32:32 -0500157 gui::CaptureArgs captureArgs;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700158 const char* pname = argv[0];
159 bool png = false;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700160 int c;
John Reck4de6e742023-11-14 18:32:32 -0500161 while ((c = getopt_long(argc, argv, "phd:", LONG_OPTIONS, nullptr)) != -1) {
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700162 switch (c) {
163 case 'p':
164 png = true;
165 break;
Dominik Laskowskid8dc5b32023-09-28 17:10:47 -0400166 case 'd': {
167 errno = 0;
168 char* end = nullptr;
169 const uint64_t id = strtoull(optarg, &end, 10);
170 if (!end || *end != '\0' || errno == ERANGE) {
171 fprintf(stderr, "Invalid display ID: Out of range [0, 2^64).\n");
172 return 1;
173 }
174
175 displayIdOpt = DisplayId::fromValue(id);
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400176 if (!displayIdOpt) {
Dominik Laskowskid8dc5b32023-09-28 17:10:47 -0400177 fprintf(stderr, "Invalid display ID: Incorrect encoding.\n");
Dominik Laskowski0bda2e32021-03-23 16:24:01 -0700178 return 1;
179 }
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700180 break;
Dominik Laskowskid8dc5b32023-09-28 17:10:47 -0400181 }
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700182 case '?':
183 case 'h':
Huihong Luo41ea7d12022-09-26 11:32:52 -0700184 if (ids.size() == 1) {
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400185 displayIdOpt = ids.front();
186 }
187 usage(pname, displayIdOpt);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700188 return 1;
John Reck4de6e742023-11-14 18:32:32 -0500189 case LongOpts::HintForSeamless:
190 captureArgs.hintForSeamlessTransition = true;
191 break;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700192 }
193 }
Huihong Luo41ea7d12022-09-26 11:32:52 -0700194
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400195 if (!displayIdOpt) {
196 displayIdOpt = ids.front();
Huihong Luo6f645f72022-10-07 19:24:00 -0700197 if (ids.size() > 1) {
198 fprintf(stderr,
199 "[Warning] Multiple displays were found, but no display id was specified! "
200 "Defaulting to the first display found, however this default is not guaranteed "
201 "to be consistent across captures. A display id should be specified.\n");
202 fprintf(stderr, "A display ID can be specified with the [-d display-id] option.\n");
Huihong Luo41ea7d12022-09-26 11:32:52 -0700203 fprintf(stderr, "See \"dumpsys SurfaceFlinger --display-id\" for valid display IDs.\n");
Huihong Luo41ea7d12022-09-26 11:32:52 -0700204 }
205 }
206
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700207 argc -= optind;
208 argv += optind;
209
210 int fd = -1;
Andreas Gampecfedceb2014-09-30 21:48:18 -0700211 const char* fn = NULL;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700212 if (argc == 0) {
213 fd = dup(STDOUT_FILENO);
214 } else if (argc == 1) {
Umair Khancfed2322014-01-15 08:08:50 -0500215 fn = argv[0];
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700216 fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0664);
217 if (fd == -1) {
218 fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
219 return 1;
220 }
221 const int len = strlen(fn);
222 if (len >= 4 && 0 == strcmp(fn+len-4, ".png")) {
223 png = true;
224 }
225 }
Prathmesh Prabhubf89ae52016-03-10 15:23:34 -0800226
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700227 if (fd == -1) {
Dominik Laskowski622c4ae2023-05-26 12:10:16 -0400228 usage(pname, displayIdOpt);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700229 return 1;
230 }
231
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000232 void* base = NULL;
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700233
Martijn Coenen48b74082017-07-24 09:19:26 +0200234 // setThreadPoolMaxThreadCount(0) actually tells the kernel it's
235 // not allowed to spawn any additional threads, but we still spawn
236 // a binder thread from userspace when we call startThreadPool().
237 // See b/36066697 for rationale
238 ProcessState::self()->setThreadPoolMaxThreadCount(0);
239 ProcessState::self()->startThreadPool();
240
chaviwbc100492020-08-18 16:06:40 -0700241 sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
John Reck4de6e742023-11-14 18:32:32 -0500242 ScreenshotClient::captureDisplay(*displayIdOpt, captureArgs, captureListener);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700243
chaviwbc100492020-08-18 16:06:40 -0700244 ScreenCaptureResults captureResults = captureListener->waitForResults();
Patrick Williams8d455722022-08-19 14:31:26 +0000245 if (!captureResults.fenceResult.ok()) {
chaviwbc100492020-08-18 16:06:40 -0700246 close(fd);
jeimysantiago8ee92d12023-07-21 15:40:13 +0000247 fprintf(stderr, "Failed to take screenshot. Status: %d\n",
248 fenceStatus(captureResults.fenceResult));
chaviwbc100492020-08-18 16:06:40 -0700249 return 1;
250 }
chaviwbc27bc72020-07-27 16:44:35 -0700251 ui::Dataspace dataspace = captureResults.capturedDataspace;
252 sp<GraphicBuffer> buffer = captureResults.buffer;
253
jeimysantiago8ee92d12023-07-21 15:40:13 +0000254 status_t result = buffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN, &base);
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000255
chaviw7f4dc7e2018-09-11 13:59:30 -0700256 if (base == nullptr || result != NO_ERROR) {
257 String8 reason;
chaviwa69a1b82019-04-30 16:53:33 -0700258 if (result != NO_ERROR) {
259 reason.appendFormat(" Error Code: %d", result);
chaviw7f4dc7e2018-09-11 13:59:30 -0700260 } else {
chaviwa69a1b82019-04-30 16:53:33 -0700261 reason = "Failed to write to buffer";
chaviw7f4dc7e2018-09-11 13:59:30 -0700262 }
263 fprintf(stderr, "Failed to take screenshot (%s)\n", reason.c_str());
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000264 close(fd);
Steven Morelanda89ae862018-05-24 17:48:28 -0700265 return 1;
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000266 }
267
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000268 if (png) {
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400269 AndroidBitmapInfo info;
chaviwbc27bc72020-07-27 16:44:35 -0700270 info.format = flinger2bitmapFormat(buffer->getPixelFormat());
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400271 info.flags = ANDROID_BITMAP_FLAGS_ALPHA_PREMUL;
chaviwbc27bc72020-07-27 16:44:35 -0700272 info.width = buffer->getWidth();
273 info.height = buffer->getHeight();
274 info.stride = buffer->getStride() * bytesPerPixel(buffer->getPixelFormat());
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400275
chaviwbc27bc72020-07-27 16:44:35 -0700276 int result = AndroidBitmap_compress(&info, static_cast<int32_t>(dataspace), base,
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400277 ANDROID_BITMAP_COMPRESS_FORMAT_PNG, 100, &fd,
278 [](void* fdPtr, const void* data, size_t size) -> bool {
279 int bytesWritten = write(*static_cast<int*>(fdPtr),
280 data, size);
281 return bytesWritten == size;
282 });
283
284 if (result != ANDROID_BITMAP_RESULT_SUCCESS) {
285 fprintf(stderr, "Failed to compress PNG (error code: %d)\n", result);
286 }
287
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000288 if (fn != NULL) {
289 notifyMediaScanner(fn);
290 }
291 } else {
chaviwbc27bc72020-07-27 16:44:35 -0700292 uint32_t w = buffer->getWidth();
293 uint32_t h = buffer->getHeight();
294 uint32_t s = buffer->getStride();
295 uint32_t f = buffer->getPixelFormat();
296 uint32_t c = dataSpaceToInt(dataspace);
Derek Sollenbergera3ef0942020-04-08 15:47:55 -0400297
Chavi Weingartend7ec64c2017-11-30 01:52:01 +0000298 write(fd, &w, 4);
299 write(fd, &h, 4);
300 write(fd, &f, 4);
301 write(fd, &c, 4);
302 size_t Bpp = bytesPerPixel(f);
303 for (size_t y=0 ; y<h ; y++) {
304 write(fd, base, w*Bpp);
305 base = (void *)((char *)base + s*Bpp);
Mike Lockwoodc59b2f92012-10-24 12:31:10 -0700306 }
307 }
308 close(fd);
Josh Gao90982582017-06-19 13:38:20 -0700309
Steven Morelanda89ae862018-05-24 17:48:28 -0700310 return 0;
Peiyong Lin10a34d12018-09-19 13:56:12 -0700311}