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
22#include <linux/fb.h>
23#include <sys/ioctl.h>
24#include <sys/mman.h>
25
26#include <binder/ProcessState.h>
27
28#include <gui/SurfaceComposerClient.h>
29#include <gui/ISurfaceComposer.h>
30
31#include <ui/PixelFormat.h>
32
33#include <SkImageEncoder.h>
34#include <SkBitmap.h>
35#include <SkData.h>
36#include <SkStream.h>
37
38using namespace android;
39
40static uint32_t DEFAULT_DISPLAY_ID = ISurfaceComposer::eDisplayIdMain;
41
42static void usage(const char* pname)
43{
44    fprintf(stderr,
45            "usage: %s [-hp] [-d display-id] [FILENAME]\n"
46            "   -h: this message\n"
47            "   -p: save the file as a png.\n"
48            "   -d: specify the display id to capture, default %d.\n"
49            "If FILENAME ends with .png it will be saved as a png.\n"
50            "If FILENAME is not given, the results will be printed to stdout.\n",
51            pname, DEFAULT_DISPLAY_ID
52    );
53}
54
55static SkColorType flinger2skia(PixelFormat f)
56{
57    switch (f) {
58        case PIXEL_FORMAT_RGB_565:
59            return kRGB_565_SkColorType;
60        default:
61            return kN32_SkColorType;
62    }
63}
64
65static status_t vinfoToPixelFormat(const fb_var_screeninfo& vinfo,
66        uint32_t* bytespp, uint32_t* f)
67{
68
69    switch (vinfo.bits_per_pixel) {
70        case 16:
71            *f = PIXEL_FORMAT_RGB_565;
72            *bytespp = 2;
73            break;
74        case 24:
75            *f = PIXEL_FORMAT_RGB_888;
76            *bytespp = 3;
77            break;
78        case 32:
79            // TODO: do better decoding of vinfo here
80            *f = PIXEL_FORMAT_RGBX_8888;
81            *bytespp = 4;
82            break;
83        default:
84            return BAD_VALUE;
85    }
86    return NO_ERROR;
87}
88
89int main(int argc, char** argv)
90{
91    ProcessState::self()->startThreadPool();
92
93    const char* pname = argv[0];
94    bool png = false;
95    int32_t displayId = DEFAULT_DISPLAY_ID;
96    int c;
97    while ((c = getopt(argc, argv, "phd:")) != -1) {
98        switch (c) {
99            case 'p':
100                png = true;
101                break;
102            case 'd':
103                displayId = atoi(optarg);
104                break;
105            case '?':
106            case 'h':
107                usage(pname);
108                return 1;
109        }
110    }
111    argc -= optind;
112    argv += optind;
113
114    int fd = -1;
115    if (argc == 0) {
116        fd = dup(STDOUT_FILENO);
117    } else if (argc == 1) {
118        const char* fn = argv[0];
119        fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0664);
120        if (fd == -1) {
121            fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
122            return 1;
123        }
124        const int len = strlen(fn);
125        if (len >= 4 && 0 == strcmp(fn+len-4, ".png")) {
126            png = true;
127        }
128    }
129
130    if (fd == -1) {
131        usage(pname);
132        return 1;
133    }
134
135    void const* mapbase = MAP_FAILED;
136    ssize_t mapsize = -1;
137
138    void const* base = 0;
139    uint32_t w, s, h, f;
140    size_t size = 0;
141
142    ScreenshotClient screenshot;
143    sp<IBinder> display = SurfaceComposerClient::getBuiltInDisplay(displayId);
144    if (display != NULL && screenshot.update(display, Rect(), false) == NO_ERROR) {
145        base = screenshot.getPixels();
146        w = screenshot.getWidth();
147        h = screenshot.getHeight();
148        s = screenshot.getStride();
149        f = screenshot.getFormat();
150        size = screenshot.getSize();
151    } else {
152        const char* fbpath = "/dev/graphics/fb0";
153        int fb = open(fbpath, O_RDONLY);
154        if (fb >= 0) {
155            struct fb_var_screeninfo vinfo;
156            if (ioctl(fb, FBIOGET_VSCREENINFO, &vinfo) == 0) {
157                uint32_t bytespp;
158                if (vinfoToPixelFormat(vinfo, &bytespp, &f) == NO_ERROR) {
159                    size_t offset = (vinfo.xoffset + vinfo.yoffset*vinfo.xres) * bytespp;
160                    w = vinfo.xres;
161                    h = vinfo.yres;
162                    s = vinfo.xres;
163                    size = w*h*bytespp;
164                    mapsize = offset + size;
165                    mapbase = mmap(0, mapsize, PROT_READ, MAP_PRIVATE, fb, 0);
166                    if (mapbase != MAP_FAILED) {
167                        base = (void const *)((char const *)mapbase + offset);
168                    }
169                }
170            }
171            close(fb);
172        }
173    }
174
175    if (base) {
176        if (png) {
177            const SkImageInfo info = SkImageInfo::Make(w, h, flinger2skia(f),
178                                                       kPremul_SkAlphaType);
179            SkBitmap b;
180            b.installPixels(info, const_cast<void*>(base), s*bytesPerPixel(f));
181            SkDynamicMemoryWStream stream;
182            SkImageEncoder::EncodeStream(&stream, b,
183                    SkImageEncoder::kPNG_Type, SkImageEncoder::kDefaultQuality);
184            SkData* streamData = stream.copyToData();
185            write(fd, streamData->data(), streamData->size());
186            streamData->unref();
187        } else {
188            write(fd, &w, 4);
189            write(fd, &h, 4);
190            write(fd, &f, 4);
191            size_t Bpp = bytesPerPixel(f);
192            for (size_t y=0 ; y<h ; y++) {
193                write(fd, base, w*Bpp);
194                base = (void *)((char *)base + s*Bpp);
195            }
196        }
197    }
198    close(fd);
199    if (mapbase != MAP_FAILED) {
200        munmap((void *)mapbase, mapsize);
201    }
202    return 0;
203}
204