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
28#include <binder/ProcessState.h>
29
30#include <gui/SurfaceComposerClient.h>
31#include <gui/ISurfaceComposer.h>
32
33#include <ui/DisplayInfo.h>
34#include <ui/PixelFormat.h>
35
36// TODO: Fix Skia.
37#pragma GCC diagnostic push
38#pragma GCC diagnostic ignored "-Wunused-parameter"
39#include <SkImageEncoder.h>
40#include <SkData.h>
41#pragma GCC diagnostic pop
42
43using namespace android;
44
45static uint32_t DEFAULT_DISPLAY_ID = ISurfaceComposer::eDisplayIdMain;
46
47static void usage(const char* pname)
48{
49    fprintf(stderr,
50            "usage: %s [-hp] [-d display-id] [FILENAME]\n"
51            "   -h: this message\n"
52            "   -p: save the file as a png.\n"
53            "   -d: specify the display id to capture, default %d.\n"
54            "If FILENAME ends with .png it will be saved as a png.\n"
55            "If FILENAME is not given, the results will be printed to stdout.\n",
56            pname, DEFAULT_DISPLAY_ID
57    );
58}
59
60static SkColorType flinger2skia(PixelFormat f)
61{
62    switch (f) {
63        case PIXEL_FORMAT_RGB_565:
64            return kRGB_565_SkColorType;
65        default:
66            return kN32_SkColorType;
67    }
68}
69
70static status_t notifyMediaScanner(const char* fileName) {
71    String8 cmd("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://");
72    String8 fileUrl("\"");
73    fileUrl.append(fileName);
74    fileUrl.append("\"");
75    cmd.append(fileName);
76    cmd.append(" > /dev/null");
77    int result = system(cmd.string());
78    if (result < 0) {
79        fprintf(stderr, "Unable to broadcast intent for media scanner.\n");
80        return UNKNOWN_ERROR;
81    }
82    return NO_ERROR;
83}
84
85int main(int argc, char** argv)
86{
87    // setThreadPoolMaxThreadCount(0) actually tells the kernel it's
88    // not allowed to spawn any additional threads, but we still spawn
89    // a binder thread from userspace when we call startThreadPool().
90    // See b/36066697 for rationale
91    ProcessState::self()->setThreadPoolMaxThreadCount(0);
92    ProcessState::self()->startThreadPool();
93
94    const char* pname = argv[0];
95    bool png = false;
96    int32_t displayId = DEFAULT_DISPLAY_ID;
97    int c;
98    while ((c = getopt(argc, argv, "phd:")) != -1) {
99        switch (c) {
100            case 'p':
101                png = true;
102                break;
103            case 'd':
104                displayId = atoi(optarg);
105                break;
106            case '?':
107            case 'h':
108                usage(pname);
109                return 1;
110        }
111    }
112    argc -= optind;
113    argv += optind;
114
115    int fd = -1;
116    const char* fn = NULL;
117    if (argc == 0) {
118        fd = dup(STDOUT_FILENO);
119    } else if (argc == 1) {
120        fn = argv[0];
121        fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0664);
122        if (fd == -1) {
123            fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
124            return 1;
125        }
126        const int len = strlen(fn);
127        if (len >= 4 && 0 == strcmp(fn+len-4, ".png")) {
128            png = true;
129        }
130    }
131
132    if (fd == -1) {
133        usage(pname);
134        return 1;
135    }
136
137    void const* mapbase = MAP_FAILED;
138    ssize_t mapsize = -1;
139
140    void const* base = NULL;
141    uint32_t w, s, h, f;
142    size_t size = 0;
143
144    // Maps orientations from DisplayInfo to ISurfaceComposer
145    static const uint32_t ORIENTATION_MAP[] = {
146        ISurfaceComposer::eRotateNone, // 0 == DISPLAY_ORIENTATION_0
147        ISurfaceComposer::eRotate270, // 1 == DISPLAY_ORIENTATION_90
148        ISurfaceComposer::eRotate180, // 2 == DISPLAY_ORIENTATION_180
149        ISurfaceComposer::eRotate90, // 3 == DISPLAY_ORIENTATION_270
150    };
151
152    ScreenshotClient screenshot;
153    sp<IBinder> display = SurfaceComposerClient::getBuiltInDisplay(displayId);
154    if (display == NULL) {
155        fprintf(stderr, "Unable to get handle for display %d\n", displayId);
156        return 1;
157    }
158
159    Vector<DisplayInfo> configs;
160    SurfaceComposerClient::getDisplayConfigs(display, &configs);
161    int activeConfig = SurfaceComposerClient::getActiveConfig(display);
162    if (static_cast<size_t>(activeConfig) >= configs.size()) {
163        fprintf(stderr, "Active config %d not inside configs (size %zu)\n",
164                activeConfig, configs.size());
165        return 1;
166    }
167    uint8_t displayOrientation = configs[activeConfig].orientation;
168    uint32_t captureOrientation = ORIENTATION_MAP[displayOrientation];
169
170    status_t result = screenshot.update(display, Rect(),
171            0 /* reqWidth */, 0 /* reqHeight */,
172            INT32_MIN, INT32_MAX, /* all layers */
173            false, captureOrientation);
174    if (result == NO_ERROR) {
175        base = screenshot.getPixels();
176        w = screenshot.getWidth();
177        h = screenshot.getHeight();
178        s = screenshot.getStride();
179        f = screenshot.getFormat();
180        size = screenshot.getSize();
181    }
182
183    if (base != NULL) {
184        if (png) {
185            const SkImageInfo info =
186                SkImageInfo::Make(w, h, flinger2skia(f), kPremul_SkAlphaType);
187            SkPixmap pixmap(info, base, s * bytesPerPixel(f));
188            struct FDWStream final : public SkWStream {
189              size_t fBytesWritten = 0;
190              int fFd;
191              FDWStream(int f) : fFd(f) {}
192              size_t bytesWritten() const override { return fBytesWritten; }
193              bool write(const void* buffer, size_t size) override {
194                fBytesWritten += size;
195                return size == 0 || ::write(fFd, buffer, size) > 0;
196              }
197            } fdStream(fd);
198            (void)SkEncodeImage(&fdStream, pixmap, SkEncodedImageFormat::kPNG, 100);
199            if (fn != NULL) {
200                notifyMediaScanner(fn);
201            }
202        } else {
203            write(fd, &w, 4);
204            write(fd, &h, 4);
205            write(fd, &f, 4);
206            size_t Bpp = bytesPerPixel(f);
207            for (size_t y=0 ; y<h ; y++) {
208                write(fd, base, w*Bpp);
209                base = (void *)((char *)base + s*Bpp);
210            }
211        }
212    }
213    close(fd);
214    if (mapbase != MAP_FAILED) {
215        munmap((void *)mapbase, mapsize);
216    }
217
218    // b/36066697: Avoid running static destructors.
219    _exit(0);
220}
221