blob: b44c64c4be028078c8e6ffdf331c94cbdd98cf15 [file] [log] [blame]
Steve Kondik55db0532017-06-12 11:27:18 -07001/*
2 * Copyright 2014 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#define LOG_TAG "VNC-VirtualDisplay"
18//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
21#include <binder/IPCThreadState.h>
22#include <binder/ProcessState.h>
23
24#include <gui/SurfaceComposerClient.h>
25
Steve Kondik55db0532017-06-12 11:27:18 -070026#include <GLES3/gl3.h>
Steve Kondikdda11002017-06-13 08:20:27 -070027#include <GLES3/gl3ext.h>
28#include <GLES2/gl2ext.h>
Steve Kondik55db0532017-06-12 11:27:18 -070029
30#include <ui/Rect.h>
31
32#include "VirtualDisplay.h"
33
34using namespace android;
35
36static const int kGlBytesPerPixel = 4; // GL_RGBA
37
38
39/*
40 * Returns "true" if the device is rotated 90 degrees.
41 */
42bool VirtualDisplay::isDeviceRotated(int orientation) {
43 return orientation != DISPLAY_ORIENTATION_0 &&
44 orientation != DISPLAY_ORIENTATION_180;
45}
46
47/*
48 * Sets the display projection, based on the display dimensions, video size,
49 * and device orientation.
50 */
51status_t VirtualDisplay::setDisplayProjection(const sp<IBinder>& dpy,
52 const DisplayInfo& mMainDpyInfo) {
53 status_t err;
54
55 // Set the region of the layer stack we're interested in, which in our
56 // case is "all of it". If the app is rotated (so that the width of the
57 // app is based on the height of the display), reverse width/height.
58 bool deviceRotated = isDeviceRotated(mMainDpyInfo.orientation);
59 uint32_t sourceWidth, sourceHeight;
60 if (!deviceRotated) {
61 sourceWidth = mMainDpyInfo.w;
62 sourceHeight = mMainDpyInfo.h;
63 } else {
64 ALOGV("using rotated width/height");
65 sourceHeight = mMainDpyInfo.w;
66 sourceWidth = mMainDpyInfo.h;
67 }
68 Rect layerStackRect(sourceWidth, sourceHeight);
69
70 // We need to preserve the aspect ratio of the display.
71 float displayAspect = (float) sourceHeight / (float) sourceWidth;
72
73
74 // Set the way we map the output onto the display surface (which will
75 // be e.g. 1280x720 for a 720p video). The rect is interpreted
76 // post-rotation, so if the display is rotated 90 degrees we need to
77 // "pre-rotate" it by flipping width/height, so that the orientation
78 // adjustment changes it back.
79 //
80 // We might want to encode a portrait display as landscape to use more
81 // of the screen real estate. (If players respect a 90-degree rotation
82 // hint, we can essentially get a 720x1280 video instead of 1280x720.)
83 // In that case, we swap the configured video width/height and then
84 // supply a rotation value to the display projection.
85 uint32_t videoWidth, videoHeight;
86 uint32_t outWidth, outHeight;
87 if (!mRotate) {
88 videoWidth = mWidth;
89 videoHeight = mHeight;
90 } else {
91 videoWidth = mHeight;
92 videoHeight = mWidth;
93 }
94 if (videoHeight > (uint32_t)(videoWidth * displayAspect)) {
95 // limited by narrow width; reduce height
96 outWidth = videoWidth;
97 outHeight = (uint32_t)(videoWidth * displayAspect);
98 } else {
99 // limited by short height; restrict width
100 outHeight = videoHeight;
101 outWidth = (uint32_t)(videoHeight / displayAspect);
102 }
103 uint32_t offX, offY;
104 offX = (videoWidth - outWidth) / 2;
105 offY = (videoHeight - outHeight) / 2;
106 Rect displayRect(offX, offY, offX + outWidth, offY + outHeight);
107
108 if (mRotate) {
109 printf("Rotated content area is %ux%u at offset x=%d y=%d\n",
110 outHeight, outWidth, offY, offX);
111 } else {
112 printf("Content area is %ux%u at offset x=%d y=%d\n",
113 outWidth, outHeight, offX, offY);
114 }
115
116 SurfaceComposerClient::setDisplayProjection(dpy,
117 mRotate ? DISPLAY_ORIENTATION_90 : DISPLAY_ORIENTATION_0,
118 layerStackRect, displayRect);
119 return NO_ERROR;
120}
121
Steve Kondik7225c7f2017-06-14 00:06:16 -0700122status_t VirtualDisplay::start(const DisplayInfo& mainDpyInfo) {
Steve Kondik55db0532017-06-12 11:27:18 -0700123
124 Mutex::Autolock _l(mMutex);
125
Steve Kondik55db0532017-06-12 11:27:18 -0700126 mRotate = isDeviceRotated(mainDpyInfo.orientation);
127 mWidth = mRotate ? mainDpyInfo.h : mainDpyInfo.w;
128 mHeight = mRotate ? mainDpyInfo.w : mainDpyInfo.h;
129
130 sp<ProcessState> self = ProcessState::self();
131 self->startThreadPool();
132
133 run("vnc-virtualdisplay");
134
135 mState = INIT;
136 while (mState == INIT) {
137 mStartCond.wait(mMutex);
138 }
139
140 if (mThreadResult != NO_ERROR) {
141 ALOGE("Failed to start VDS thread: err=%d", mThreadResult);
142 return mThreadResult;
143 }
144 assert(mState == RUNNING);
145
146 mDpy = SurfaceComposerClient::createDisplay(
147 String8("VNCFlinger"), false /*secure*/);
148
149 SurfaceComposerClient::openGlobalTransaction();
150 SurfaceComposerClient::setDisplaySurface(mDpy, mProducer);
151 setDisplayProjection(mDpy, mainDpyInfo);
152 SurfaceComposerClient::setDisplayLayerStack(mDpy, 0); // default stack
153 SurfaceComposerClient::closeGlobalTransaction();
154
155 ALOGV("VirtualDisplay::start successful");
156 return NO_ERROR;
157}
158
159status_t VirtualDisplay::stop() {
160 Mutex::Autolock _l(mMutex);
161 mState = STOPPING;
162 mEventCond.signal();
163 return NO_ERROR;
164}
165
166bool VirtualDisplay::threadLoop() {
167 Mutex::Autolock _l(mMutex);
168
169 mThreadResult = setup_l();
170
171 if (mThreadResult != NO_ERROR) {
172 ALOGW("Aborting VDS thread");
173 mState = STOPPED;
174 release_l();
175 mStartCond.broadcast();
176 return false;
177 }
178
179 ALOGV("VDS thread running");
180 mState = RUNNING;
181 mStartCond.broadcast();
182
183 while (mState == RUNNING) {
184 mEventCond.wait(mMutex);
185 ALOGD("Awake, frame available");
Steve Kondik7225c7f2017-06-14 00:06:16 -0700186 processFrame_l();
Steve Kondik55db0532017-06-12 11:27:18 -0700187 }
188
189 ALOGV("VDS thread stopping");
190 release_l();
191 mState = STOPPED;
192 return false; // stop
193}
194
195status_t VirtualDisplay::setup_l() {
196 status_t err;
197
198 err = mEglWindow.createPbuffer(mWidth, mHeight);
199 if (err != NO_ERROR) {
200 return err;
201 }
202 mEglWindow.makeCurrent();
203
204 glViewport(0, 0, mWidth, mHeight);
205 glDisable(GL_DEPTH_TEST);
206 glDisable(GL_CULL_FACE);
207
208 // Shader for rendering the external texture.
209 err = mExtTexProgram.setup(Program::PROGRAM_EXTERNAL_TEXTURE);
210 if (err != NO_ERROR) {
211 return err;
212 }
213
214 // Input side (buffers from virtual display).
215 glGenTextures(1, &mExtTextureName);
216 if (mExtTextureName == 0) {
217 ALOGE("glGenTextures failed: %#x", glGetError());
218 return UNKNOWN_ERROR;
219 }
220
221 mBufSize = mWidth * mHeight * kGlBytesPerPixel;
Steve Kondikdda11002017-06-13 08:20:27 -0700222
Steve Kondik55db0532017-06-12 11:27:18 -0700223 // pixel buffer for image copy
224 mPBO = new GLuint[NUM_PBO];
225 glGenBuffers(NUM_PBO, mPBO);
226
227 for (unsigned int i = 0; i < NUM_PBO; i++) {
228 glBindBuffer(GL_PIXEL_PACK_BUFFER, mPBO[i]);
229 glBufferData(GL_PIXEL_PACK_BUFFER, mBufSize, 0, GL_DYNAMIC_READ);
230 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
231 }
232
233 sp<IGraphicBufferConsumer> consumer;
234 BufferQueue::createBufferQueue(&mProducer, &consumer);
235 mGlConsumer = new GLConsumer(consumer, mExtTextureName,
236 GL_TEXTURE_EXTERNAL_OES, true, false);
237 mGlConsumer->setName(String8("virtual display"));
238 mGlConsumer->setDefaultBufferSize(mWidth, mHeight);
239 mProducer->setMaxDequeuedBufferCount(4);
240 mGlConsumer->setConsumerUsageBits(GRALLOC_USAGE_HW_TEXTURE);
241
242 mGlConsumer->setFrameAvailableListener(this);
243
244 ALOGD("VirtualDisplay::setup_l OK");
245 return NO_ERROR;
246}
247
248void* VirtualDisplay::processFrame_l() {
249 ALOGD("processFrame_l\n");
250
251 float texMatrix[16];
252 mGlConsumer->updateTexImage();
253 mGlConsumer->getTransformMatrix(texMatrix);
254
Steve Kondikdda11002017-06-13 08:20:27 -0700255 int64_t startWhen, blitWhen, readWhen, mapWhen, memcpyWhen, markWhen;
256 startWhen = systemTime(CLOCK_MONOTONIC);
257
Steve Kondik55db0532017-06-12 11:27:18 -0700258 // The data is in an external texture, so we need to render it to the
259 // pbuffer to get access to RGB pixel data. We also want to flip it
260 // upside-down for easy conversion to a bitmap.
261 int width = mEglWindow.getWidth();
262 int height = mEglWindow.getHeight();
263 mExtTexProgram.blit(mExtTextureName, texMatrix, 0, 0, mWidth, mHeight, true);
264
Steve Kondikdda11002017-06-13 08:20:27 -0700265 blitWhen = systemTime(CLOCK_MONOTONIC);
266
Steve Kondik55db0532017-06-12 11:27:18 -0700267 GLenum glErr;
268 glBindBuffer(GL_PIXEL_PACK_BUFFER, mPBO[mIndex]);
269 glReadPixels(0, 0, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, 0);
270 if ((glErr = glGetError()) != GL_NO_ERROR) {
271 ALOGE("glReadPixels failed: %#x", glErr);
272 return NULL;
273 }
274
Steve Kondikdda11002017-06-13 08:20:27 -0700275 readWhen = systemTime(CLOCK_MONOTONIC);
276
Steve Kondik55db0532017-06-12 11:27:18 -0700277 void* ptr = glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, mBufSize, GL_MAP_READ_BIT);
Steve Kondikdda11002017-06-13 08:20:27 -0700278 mapWhen = systemTime(CLOCK_MONOTONIC);
279 //memcpy(mVNCScreen->frameBuffer, ptr, mBufSize);
280 mVNCScreen->frameBuffer = (char *)ptr;
281 memcpyWhen = systemTime(CLOCK_MONOTONIC);
282 rfbMarkRectAsModified(mVNCScreen, 0, 0, mWidth, mHeight);
283 markWhen = systemTime(CLOCK_MONOTONIC);
284
Steve Kondik55db0532017-06-12 11:27:18 -0700285 glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
286 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
287
Steve Kondikdda11002017-06-13 08:20:27 -0700288 ALOGV("processFrame: blit=%.3fms read=%.3fms map=%.3fms memcpy=%.3fms mark=%.3fms",
289 (blitWhen - startWhen) / 1000000.0,
290 (readWhen - blitWhen) / 1000000.0,
291 (mapWhen - readWhen) / 1000000.0,
292 (memcpyWhen - mapWhen) / 1000000.0,
293 (markWhen - memcpyWhen) / 1000000.0);
294
295 mIndex = (mIndex + 1) % NUM_PBO;
296 return mVNCScreen->frameBuffer;
Steve Kondik55db0532017-06-12 11:27:18 -0700297}
298
299void VirtualDisplay::release_l() {
300 ALOGD("release_l");
301 mGlConsumer.clear();
302 mProducer.clear();
303 mExtTexProgram.release();
304 mEglWindow.release();
305 SurfaceComposerClient::destroyDisplay(mDpy);
306}
307
308// Callback; executes on arbitrary thread.
309void VirtualDisplay::onFrameAvailable(const BufferItem& item) {
310 Mutex::Autolock _l(mMutex);
311 mEventCond.signal();
312 ALOGD("mTimestamp=%ld mFrameNumber=%ld", item.mTimestamp, item.mFrameNumber);
313}