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 
24 #include <linux/fb.h>
25 #include <sys/ioctl.h>
26 #include <sys/mman.h>
27 #include <sys/wait.h>
28 
29 #include <binder/ProcessState.h>
30 
31 #include <gui/SurfaceComposerClient.h>
32 #include <gui/ISurfaceComposer.h>
33 
34 #include <ui/DisplayInfo.h>
35 #include <ui/GraphicTypes.h>
36 #include <ui/PixelFormat.h>
37 
38 #include <system/graphics.h>
39 
40 // TODO: Fix Skia.
41 #pragma GCC diagnostic push
42 #pragma GCC diagnostic ignored "-Wunused-parameter"
43 #include <SkImageEncoder.h>
44 #include <SkData.h>
45 #include <SkColorSpace.h>
46 #pragma GCC diagnostic pop
47 
48 using namespace android;
49 
50 #define COLORSPACE_UNKNOWN    0
51 #define COLORSPACE_SRGB       1
52 #define COLORSPACE_DISPLAY_P3 2
53 
usage(const char * pname,PhysicalDisplayId displayId)54 static void usage(const char* pname, PhysicalDisplayId displayId)
55 {
56     fprintf(stderr,
57             "usage: %s [-hp] [-d display-id] [FILENAME]\n"
58             "   -h: this message\n"
59             "   -p: save the file as a png.\n"
60             "   -d: specify the physical display ID to capture (default: %"
61                     ANDROID_PHYSICAL_DISPLAY_ID_FORMAT ")\n"
62             "       see \"dumpsys SurfaceFlinger --display-id\" for valid display IDs.\n"
63             "If FILENAME ends with .png it will be saved as a png.\n"
64             "If FILENAME is not given, the results will be printed to stdout.\n",
65             pname, displayId);
66 }
67 
flinger2skia(PixelFormat f)68 static SkColorType flinger2skia(PixelFormat f)
69 {
70     switch (f) {
71         case PIXEL_FORMAT_RGB_565:
72             return kRGB_565_SkColorType;
73         default:
74             return kN32_SkColorType;
75     }
76 }
77 
dataSpaceToColorSpace(ui::Dataspace d)78 static sk_sp<SkColorSpace> dataSpaceToColorSpace(ui::Dataspace d)
79 {
80     switch (d) {
81         case ui::Dataspace::V0_SRGB:
82             return SkColorSpace::MakeSRGB();
83         case ui::Dataspace::DISPLAY_P3:
84             return SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDCIP3);
85         default:
86             return nullptr;
87     }
88 }
89 
dataSpaceToInt(ui::Dataspace d)90 static uint32_t dataSpaceToInt(ui::Dataspace d)
91 {
92     switch (d) {
93         case ui::Dataspace::V0_SRGB:
94             return COLORSPACE_SRGB;
95         case ui::Dataspace::DISPLAY_P3:
96             return COLORSPACE_DISPLAY_P3;
97         default:
98             return COLORSPACE_UNKNOWN;
99     }
100 }
101 
notifyMediaScanner(const char * fileName)102 static status_t notifyMediaScanner(const char* fileName) {
103     std::string filePath("file://");
104     filePath.append(fileName);
105     char *cmd[] = {
106         (char*) "am",
107         (char*) "broadcast",
108         (char*) "am",
109         (char*) "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
110         (char*) "-d",
111         &filePath[0],
112         nullptr
113     };
114 
115     int status;
116     int pid = fork();
117     if (pid < 0){
118        fprintf(stderr, "Unable to fork in order to send intent for media scanner.\n");
119        return UNKNOWN_ERROR;
120     }
121     if (pid == 0){
122         int fd = open("/dev/null", O_WRONLY);
123         if (fd < 0){
124             fprintf(stderr, "Unable to open /dev/null for media scanner stdout redirection.\n");
125             exit(1);
126         }
127         dup2(fd, 1);
128         int result = execvp(cmd[0], cmd);
129         close(fd);
130         exit(result);
131     }
132     wait(&status);
133 
134     if (status < 0) {
135         fprintf(stderr, "Unable to broadcast intent for media scanner.\n");
136         return UNKNOWN_ERROR;
137     }
138     return NO_ERROR;
139 }
140 
main(int argc,char ** argv)141 int main(int argc, char** argv)
142 {
143     std::optional<PhysicalDisplayId> displayId = SurfaceComposerClient::getInternalDisplayId();
144     if (!displayId) {
145         fprintf(stderr, "Failed to get token for internal display\n");
146         return 1;
147     }
148 
149     const char* pname = argv[0];
150     bool png = false;
151     int c;
152     while ((c = getopt(argc, argv, "phd:")) != -1) {
153         switch (c) {
154             case 'p':
155                 png = true;
156                 break;
157             case 'd':
158                 displayId = atoll(optarg);
159                 break;
160             case '?':
161             case 'h':
162                 usage(pname, *displayId);
163                 return 1;
164         }
165     }
166     argc -= optind;
167     argv += optind;
168 
169     int fd = -1;
170     const char* fn = NULL;
171     if (argc == 0) {
172         fd = dup(STDOUT_FILENO);
173     } else if (argc == 1) {
174         fn = argv[0];
175         fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0664);
176         if (fd == -1) {
177             fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
178             return 1;
179         }
180         const int len = strlen(fn);
181         if (len >= 4 && 0 == strcmp(fn+len-4, ".png")) {
182             png = true;
183         }
184     }
185 
186     if (fd == -1) {
187         usage(pname, *displayId);
188         return 1;
189     }
190 
191     void const* mapbase = MAP_FAILED;
192     ssize_t mapsize = -1;
193 
194     void* base = NULL;
195     uint32_t w, s, h, f;
196     size_t size = 0;
197 
198     // setThreadPoolMaxThreadCount(0) actually tells the kernel it's
199     // not allowed to spawn any additional threads, but we still spawn
200     // a binder thread from userspace when we call startThreadPool().
201     // See b/36066697 for rationale
202     ProcessState::self()->setThreadPoolMaxThreadCount(0);
203     ProcessState::self()->startThreadPool();
204 
205     ui::Dataspace outDataspace;
206     sp<GraphicBuffer> outBuffer;
207 
208     status_t result = ScreenshotClient::capture(*displayId, &outDataspace, &outBuffer);
209     if (result != NO_ERROR) {
210         close(fd);
211         return 1;
212     }
213 
214     result = outBuffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN, &base);
215 
216     if (base == nullptr || result != NO_ERROR) {
217         String8 reason;
218         if (result != NO_ERROR) {
219             reason.appendFormat(" Error Code: %d", result);
220         } else {
221             reason = "Failed to write to buffer";
222         }
223         fprintf(stderr, "Failed to take screenshot (%s)\n", reason.c_str());
224         close(fd);
225         return 1;
226     }
227 
228     w = outBuffer->getWidth();
229     h = outBuffer->getHeight();
230     s = outBuffer->getStride();
231     f = outBuffer->getPixelFormat();
232     size = s * h * bytesPerPixel(f);
233 
234     if (png) {
235         const SkImageInfo info =
236             SkImageInfo::Make(w, h, flinger2skia(f), kPremul_SkAlphaType,
237                               dataSpaceToColorSpace(outDataspace));
238         SkPixmap pixmap(info, base, s * bytesPerPixel(f));
239         struct FDWStream final : public SkWStream {
240           size_t fBytesWritten = 0;
241           int fFd;
242           FDWStream(int f) : fFd(f) {}
243           size_t bytesWritten() const override { return fBytesWritten; }
244           bool write(const void* buffer, size_t size) override {
245             fBytesWritten += size;
246             return size == 0 || ::write(fFd, buffer, size) > 0;
247           }
248         } fdStream(fd);
249         (void)SkEncodeImage(&fdStream, pixmap, SkEncodedImageFormat::kPNG, 100);
250         if (fn != NULL) {
251             notifyMediaScanner(fn);
252         }
253     } else {
254         uint32_t c = dataSpaceToInt(outDataspace);
255         write(fd, &w, 4);
256         write(fd, &h, 4);
257         write(fd, &f, 4);
258         write(fd, &c, 4);
259         size_t Bpp = bytesPerPixel(f);
260         for (size_t y=0 ; y<h ; y++) {
261             write(fd, base, w*Bpp);
262             base = (void *)((char *)base + s*Bpp);
263         }
264     }
265     close(fd);
266     if (mapbase != MAP_FAILED) {
267         munmap((void *)mapbase, mapsize);
268     }
269 
270     return 0;
271 }
272