blob: 369d2719e6d97beb504dbd2d32c1de79396d4156 [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
26#include <GLES2/gl2.h>
27#include <GLES2/gl2ext.h>
28#include <GLES3/gl3.h>
29
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
122status_t VirtualDisplay::start(const DisplayInfo& mainDpyInfo, EventQueue *queue) {
123
124 Mutex::Autolock _l(mMutex);
125
126 mQueue = queue;
127
128 mRotate = isDeviceRotated(mainDpyInfo.orientation);
129 mWidth = mRotate ? mainDpyInfo.h : mainDpyInfo.w;
130 mHeight = mRotate ? mainDpyInfo.w : mainDpyInfo.h;
131
132 sp<ProcessState> self = ProcessState::self();
133 self->startThreadPool();
134
135 run("vnc-virtualdisplay");
136
137 mState = INIT;
138 while (mState == INIT) {
139 mStartCond.wait(mMutex);
140 }
141
142 if (mThreadResult != NO_ERROR) {
143 ALOGE("Failed to start VDS thread: err=%d", mThreadResult);
144 return mThreadResult;
145 }
146 assert(mState == RUNNING);
147
148 mDpy = SurfaceComposerClient::createDisplay(
149 String8("VNCFlinger"), false /*secure*/);
150
151 SurfaceComposerClient::openGlobalTransaction();
152 SurfaceComposerClient::setDisplaySurface(mDpy, mProducer);
153 setDisplayProjection(mDpy, mainDpyInfo);
154 SurfaceComposerClient::setDisplayLayerStack(mDpy, 0); // default stack
155 SurfaceComposerClient::closeGlobalTransaction();
156
157 ALOGV("VirtualDisplay::start successful");
158 return NO_ERROR;
159}
160
161status_t VirtualDisplay::stop() {
162 Mutex::Autolock _l(mMutex);
163 mState = STOPPING;
164 mEventCond.signal();
165 return NO_ERROR;
166}
167
168bool VirtualDisplay::threadLoop() {
169 Mutex::Autolock _l(mMutex);
170
171 mThreadResult = setup_l();
172
173 if (mThreadResult != NO_ERROR) {
174 ALOGW("Aborting VDS thread");
175 mState = STOPPED;
176 release_l();
177 mStartCond.broadcast();
178 return false;
179 }
180
181 ALOGV("VDS thread running");
182 mState = RUNNING;
183 mStartCond.broadcast();
184
185 while (mState == RUNNING) {
186 mEventCond.wait(mMutex);
187 ALOGD("Awake, frame available");
188 void* ptr = processFrame_l();
189 const Event ev(EVENT_BUFFER_READY, ptr);
190 mQueue->enqueue(ev);
191 }
192
193 ALOGV("VDS thread stopping");
194 release_l();
195 mState = STOPPED;
196 return false; // stop
197}
198
199status_t VirtualDisplay::setup_l() {
200 status_t err;
201
202 err = mEglWindow.createPbuffer(mWidth, mHeight);
203 if (err != NO_ERROR) {
204 return err;
205 }
206 mEglWindow.makeCurrent();
207
208 glViewport(0, 0, mWidth, mHeight);
209 glDisable(GL_DEPTH_TEST);
210 glDisable(GL_CULL_FACE);
211
212 // Shader for rendering the external texture.
213 err = mExtTexProgram.setup(Program::PROGRAM_EXTERNAL_TEXTURE);
214 if (err != NO_ERROR) {
215 return err;
216 }
217
218 // Input side (buffers from virtual display).
219 glGenTextures(1, &mExtTextureName);
220 if (mExtTextureName == 0) {
221 ALOGE("glGenTextures failed: %#x", glGetError());
222 return UNKNOWN_ERROR;
223 }
224
225 mBufSize = mWidth * mHeight * kGlBytesPerPixel;
226
227 // pixel buffer for image copy
228 mPBO = new GLuint[NUM_PBO];
229 glGenBuffers(NUM_PBO, mPBO);
230
231 for (unsigned int i = 0; i < NUM_PBO; i++) {
232 glBindBuffer(GL_PIXEL_PACK_BUFFER, mPBO[i]);
233 glBufferData(GL_PIXEL_PACK_BUFFER, mBufSize, 0, GL_DYNAMIC_READ);
234 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
235 }
236
237 sp<IGraphicBufferConsumer> consumer;
238 BufferQueue::createBufferQueue(&mProducer, &consumer);
239 mGlConsumer = new GLConsumer(consumer, mExtTextureName,
240 GL_TEXTURE_EXTERNAL_OES, true, false);
241 mGlConsumer->setName(String8("virtual display"));
242 mGlConsumer->setDefaultBufferSize(mWidth, mHeight);
243 mProducer->setMaxDequeuedBufferCount(4);
244 mGlConsumer->setConsumerUsageBits(GRALLOC_USAGE_HW_TEXTURE);
245
246 mGlConsumer->setFrameAvailableListener(this);
247
248 ALOGD("VirtualDisplay::setup_l OK");
249 return NO_ERROR;
250}
251
252void* VirtualDisplay::processFrame_l() {
253 ALOGD("processFrame_l\n");
254
255 float texMatrix[16];
256 mGlConsumer->updateTexImage();
257 mGlConsumer->getTransformMatrix(texMatrix);
258
259 // The data is in an external texture, so we need to render it to the
260 // pbuffer to get access to RGB pixel data. We also want to flip it
261 // upside-down for easy conversion to a bitmap.
262 int width = mEglWindow.getWidth();
263 int height = mEglWindow.getHeight();
264 mExtTexProgram.blit(mExtTextureName, texMatrix, 0, 0, mWidth, mHeight, true);
265
266 GLenum glErr;
267 glBindBuffer(GL_PIXEL_PACK_BUFFER, mPBO[mIndex]);
268 glReadPixels(0, 0, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, 0);
269 if ((glErr = glGetError()) != GL_NO_ERROR) {
270 ALOGE("glReadPixels failed: %#x", glErr);
271 return NULL;
272 }
273
274 glBindBuffer(GL_PIXEL_PACK_BUFFER, mPBO[mIndex]);
275 void* ptr = glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, mBufSize, GL_MAP_READ_BIT);
276 glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
277 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
278
279 mIndex = (mIndex + 1) % NUM_PBO;
280 return ptr;
281}
282
283void VirtualDisplay::release_l() {
284 ALOGD("release_l");
285 mGlConsumer.clear();
286 mProducer.clear();
287 mExtTexProgram.release();
288 mEglWindow.release();
289 SurfaceComposerClient::destroyDisplay(mDpy);
290}
291
292// Callback; executes on arbitrary thread.
293void VirtualDisplay::onFrameAvailable(const BufferItem& item) {
294 Mutex::Autolock _l(mMutex);
295 mEventCond.signal();
296 ALOGD("mTimestamp=%ld mFrameNumber=%ld", item.mTimestamp, item.mFrameNumber);
297}