• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "host-common/opengles.h"
16 
17 #include "aemu/base/GLObjectCounter.h"
18 #include "aemu/base/files/PathUtils.h"
19 #include "aemu/base/files/Stream.h"
20 #include "aemu/base/memory/MemoryTracker.h"
21 #include "aemu/base/SharedLibrary.h"
22 #include "aemu/base/system/System.h"
23 #include "host-common/address_space_device.h"
24 #include "host-common/address_space_graphics.h"
25 #include "host-common/address_space_graphics_types.h"
26 #include "host-common/GfxstreamFatalError.h"
27 #include "host-common/GoldfishDma.h"
28 #include "host-common/RefcountPipe.h"
29 #include "host-common/FeatureControl.h"
30 #include "host-common/globals.h"
31 #include "host-common/opengl/emugl_config.h"
32 #include "host-common/opengl/GLProcessPipe.h"
33 #include "host-common/opengl/logger.h"
34 #include "host-common/opengl/gpuinfo.h"
35 
36 #include "render-utils/render_api_functions.h"
37 #include "OpenGLESDispatch/EGLDispatch.h"
38 #include "OpenGLESDispatch/GLESv2Dispatch.h"
39 
40 #include <assert.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 
44 #include <optional>
45 
46 #define D(...)
47 #define DD(...)
48 #define E(...)
49 
50 // #define D(...) do { \
51 //     VERBOSE_PRINT(init,__VA_ARGS__); \
52 //     android_opengl_logger_write(__VA_ARGS__); \
53 // } while(0);
54 //
55 // #define DD(...) do { \
56 //     VERBOSE_PRINT(gles,__VA_ARGS__); \
57 //     android_opengl_logger_write(__VA_ARGS__); \
58 // } while(0);
59 //
60 // #define E(fmt,...) do { \
61 //     derror(fmt, ##__VA_ARGS__); \
62 //     android_opengl_logger_write(fmt "\n", ##__VA_ARGS__); \
63 // } while(0);
64 
65 using android::base::pj;
66 using android::base::SharedLibrary;
67 using android::emulation::asg::AddressSpaceGraphicsContext;
68 using android::emulation::asg::ConsumerCallbacks;
69 using android::emulation::asg::ConsumerInterface;
70 using emugl::ABORT_REASON_OTHER;
71 using emugl::FatalError;
72 using gfxstream::gl::EGLDispatch;
73 using gfxstream::gl::GLESv2Dispatch;
74 
75 /* Name of the GLES rendering library we're going to use */
76 #define RENDERER_LIB_NAME "libOpenglRender"
77 
78 /* Declared in "android/globals.h" */
79 int  android_gles_fast_pipes = 1;
80 
81 // Define the Render API function pointers.
82 #define FUNCTION_(ret, name, sig, params) \
83         inline ret (*name) sig = NULL;
84 LIST_RENDER_API_FUNCTIONS(FUNCTION_)
85 #undef FUNCTION_
86 
87 static bool sOpenglLoggerInitialized = false;
88 static bool sRendererUsesSubWindow = false;
89 static bool sEgl2egl = false;
90 static gfxstream::RenderLib* sRenderLib = nullptr;
91 static gfxstream::RendererPtr sRenderer = nullptr;
92 
android_prepareOpenglesEmulation()93 int android_prepareOpenglesEmulation() {
94     android_init_opengl_logger();
95 
96     bool glFineLogging = android::base::getEnvironmentVariable("ANDROID_EMUGL_FINE_LOG") == "1";
97     bool glLogPrinting = android::base::getEnvironmentVariable("ANDROID_EMUGL_LOG_PRINT") == "1";
98 
99     AndroidOpenglLoggerFlags loggerFlags =
100         static_cast<AndroidOpenglLoggerFlags>(
101         (glFineLogging ? OPENGL_LOGGER_DO_FINE_LOGGING : 0) |
102         (glLogPrinting ? OPENGL_LOGGER_PRINT_TO_STDOUT : 0));
103 
104     android_opengl_logger_set_flags(loggerFlags);
105 
106     sOpenglLoggerInitialized = true;
107     sRendererUsesSubWindow = true;
108 
109     sEgl2egl = false;
110     if (android::base::getEnvironmentVariable("ANDROID_EGL_ON_EGL") == "1") {
111         sEgl2egl = true;
112     }
113 
114     return 0;
115 }
116 
android_setOpenglesEmulation(void * renderLib,void * eglDispatch,void * glesv2Dispatch)117 int android_setOpenglesEmulation(void* renderLib, void* eglDispatch, void* glesv2Dispatch) {
118     sRenderLib = (gfxstream::RenderLib*)renderLib;
119     (void)eglDispatch;
120     (void)glesv2Dispatch;
121     sEgl2egl = android::base::getEnvironmentVariable("ANDROID_EGL_ON_EGL") == "1";
122     return 0;
123 }
124 
android_initOpenglesEmulation()125 int android_initOpenglesEmulation() {
126     GFXSTREAM_ABORT(FatalError(ABORT_REASON_OTHER))
127         << "Not meant to call android_initOpenglesEmulation in the new build.";
128 }
129 
130 int
android_startOpenglesRenderer(int width,int height,bool guestPhoneApi,int guestApiLevel,const QAndroidVmOperations * vm_operations,const QAndroidEmulatorWindowAgent * window_agent,const QAndroidMultiDisplayAgent * multi_display_agent,int * glesMajorVersion_out,int * glesMinorVersion_out)131 android_startOpenglesRenderer(int width, int height, bool guestPhoneApi, int guestApiLevel,
132                               const QAndroidVmOperations *vm_operations,
133                               const QAndroidEmulatorWindowAgent *window_agent,
134                               const QAndroidMultiDisplayAgent *multi_display_agent,
135                               int* glesMajorVersion_out,
136                               int* glesMinorVersion_out)
137 {
138     if (!sRenderLib) {
139         D("Can't start OpenGLES renderer without support libraries");
140         return -1;
141     }
142 
143     if (sRenderer) {
144         return 0;
145     }
146 
147     const GpuInfoList& gpuList = globalGpuInfoList();
148     std::string gpuInfoAsString = gpuList.dump();
149     android_opengl_logger_write("%s: gpu info", __func__);
150     android_opengl_logger_write("%s", gpuInfoAsString.c_str());
151 
152     sRenderLib->setRenderer(emuglConfig_get_current_renderer());
153     sRenderLib->setAvdInfo(guestPhoneApi, guestApiLevel);
154     // sRenderLib->setCrashReporter(&crashhandler_die_format);
155     // sRenderLib->setFeatureController(&android::featurecontrol::isEnabled);
156     sRenderLib->setSyncDevice(goldfish_sync_create_timeline,
157             goldfish_sync_create_fence,
158             goldfish_sync_timeline_inc,
159             goldfish_sync_destroy_timeline,
160             goldfish_sync_register_trigger_wait,
161             goldfish_sync_device_exists);
162 
163     emugl_logger_struct logfuncs;
164     logfuncs.coarse = android_opengl_logger_write;
165     logfuncs.fine = android_opengl_cxt_logger_write;
166     sRenderLib->setLogger(logfuncs);
167     sRenderLib->setGLObjectCounter(android::base::GLObjectCounter::get());
168     emugl_dma_ops dma_ops;
169     dma_ops.get_host_addr = android_goldfish_dma_ops.get_host_addr;
170     dma_ops.unlock = android_goldfish_dma_ops.unlock;
171     sRenderLib->setDmaOps(dma_ops);
172     sRenderLib->setVmOps(*vm_operations);
173     sRenderLib->setAddressSpaceDeviceControlOps(get_address_space_device_control_ops());
174     sRenderLib->setWindowOps(*window_agent, *multi_display_agent);
175     // sRenderLib->setUsageTracker(android::base::CpuUsage::get(),
176     //                             android::base::MemoryTracker::get());
177 
178     sRenderer = sRenderLib->initRenderer(width, height, sRendererUsesSubWindow, sEgl2egl);
179 
180     // android::snapshot::Snapshotter::get().addOperationCallback(
181     //         [](android::snapshot::Snapshotter::Operation op,
182     //            android::snapshot::Snapshotter::Stage stage) {
183     //             sRenderer->snapshotOperationCallback(op, stage);
184     //         });
185 
186     android::emulation::registerOnLastRefCallback(
187             sRenderLib->getOnLastColorBufferRef());
188 
189     ConsumerInterface iface = {
190         // create
191         [](struct asg_context context,
192            android::base::Stream* loadStream, ConsumerCallbacks callbacks,
193            uint32_t contextId, uint32_t capsetId,
194            std::optional<std::string> nameOpt) {
195            return sRenderer->addressSpaceGraphicsConsumerCreate(
196                context, loadStream, callbacks, contextId, capsetId, std::move(nameOpt));
197         },
198         // destroy
199         [](void* consumer) {
200            sRenderer->addressSpaceGraphicsConsumerDestroy(consumer);
201         },
202         // pre save
203         [](void* consumer) {
204            sRenderer->addressSpaceGraphicsConsumerPreSave(consumer);
205         },
206         // global presave
207         []() {
208            sRenderer->pauseAllPreSave();
209         },
210         // save
211         [](void* consumer, android::base::Stream* stream) {
212            sRenderer->addressSpaceGraphicsConsumerSave(consumer, stream);
213         },
214         // global postsave
215         []() {
216            sRenderer->resumeAll();
217         },
218         // postSave
219         [](void* consumer) {
220            sRenderer->addressSpaceGraphicsConsumerPostSave(consumer);
221         },
222         // postLoad
223         [](void* consumer) {
224            sRenderer->addressSpaceGraphicsConsumerRegisterPostLoadRenderThread(consumer);
225         },
226         // global preload
227         []() {
228             // This wants to address that when using asg, pipe wants to clean
229             // up all render threads and wait for gl objects, but framebuffer
230             // notices that there is a render thread info that is still not
231             // cleaned up because these render threads come from asg.
232             android::opengl::forEachProcessPipeIdRunAndErase([](uint64_t id) {
233                 android_cleanupProcGLObjects(id);
234             });
235             android_waitForOpenglesProcessCleanup();
236         },
237     };
238     AddressSpaceGraphicsContext::setConsumer(iface);
239 
240     if (!sRenderer) {
241         D("Can't start OpenGLES renderer?");
242         return -1;
243     }
244 
245     // after initRenderer is a success, the maximum GLES API is calculated depending
246     // on feature control and host GPU support. Set the obtained GLES version here.
247     if (glesMajorVersion_out && glesMinorVersion_out)
248         sRenderLib->getGlesVersion(glesMajorVersion_out, glesMinorVersion_out);
249     return 0;
250 }
251 
252 bool
android_asyncReadbackSupported()253 android_asyncReadbackSupported() {
254     if (sRenderer) {
255         return sRenderer->asyncReadbackSupported();
256     } else {
257         D("tried to query async readback support "
258           "before renderer initialized. Likely guest rendering");
259         return false;
260     }
261 }
262 
263 void
android_setPostCallback(OnPostFunc onPost,void * onPostContext,bool useBgraReadback,uint32_t displayId)264 android_setPostCallback(OnPostFunc onPost, void* onPostContext, bool useBgraReadback, uint32_t displayId)
265 {
266     if (sRenderer) {
267         sRenderer->setPostCallback(onPost, onPostContext, useBgraReadback, displayId);
268     }
269 }
270 
android_getReadPixelsFunc()271 ReadPixelsFunc android_getReadPixelsFunc() {
272     if (sRenderer) {
273         return sRenderer->getReadPixelsCallback();
274     } else {
275         return nullptr;
276     }
277 }
278 
android_getFlushReadPixelPipeline()279 FlushReadPixelPipeline android_getFlushReadPixelPipeline() {
280     if (sRenderer) {
281         return sRenderer->getFlushReadPixelPipeline();
282     } else {
283         return nullptr;
284     }
285 }
286 
287 
strdupBaseString(const char * src)288 static char* strdupBaseString(const char* src) {
289     const char* begin = strchr(src, '(');
290     if (!begin) {
291         return strdup(src);
292     }
293 
294     const char* end = strrchr(begin + 1, ')');
295     if (!end) {
296         return strdup(src);
297     }
298 
299     // src is of the form:
300     // "foo (barzzzzzzzzzz)"
301     //       ^            ^
302     //       (b+1)        e
303     //     = 5            18
304     int len;
305     begin += 1;
306     len = end - begin;
307 
308     char* result;
309     result = (char*)malloc(len + 1);
310     memcpy(result, begin, len);
311     result[len] = '\0';
312     return result;
313 }
314 
android_getOpenglesHardwareStrings(char ** vendor,char ** renderer,char ** version)315 void android_getOpenglesHardwareStrings(char** vendor,
316                                         char** renderer,
317                                         char** version) {
318     assert(vendor != NULL && renderer != NULL && version != NULL);
319     assert(*vendor == NULL && *renderer == NULL && *version == NULL);
320     if (!sRenderer) {
321         D("Can't get OpenGL ES hardware strings when renderer not started");
322         return;
323     }
324 
325     const gfxstream::Renderer::HardwareStrings strings = sRenderer->getHardwareStrings();
326     D("OpenGL Vendor=[%s]", strings.vendor.c_str());
327     D("OpenGL Renderer=[%s]", strings.renderer.c_str());
328     D("OpenGL Version=[%s]", strings.version.c_str());
329 
330     /* Special case for the default ES to GL translators: extract the strings
331      * of the underlying OpenGL implementation. */
332     if (strncmp(strings.vendor.c_str(), "Google", 6) == 0 &&
333             strncmp(strings.renderer.c_str(), "Android Emulator OpenGL ES Translator", 37) == 0) {
334         *vendor = strdupBaseString(strings.vendor.c_str());
335         *renderer = strdupBaseString(strings.renderer.c_str());
336         *version = strdupBaseString(strings.version.c_str());
337     } else {
338         *vendor = strdup(strings.vendor.c_str());
339         *renderer = strdup(strings.renderer.c_str());
340         *version = strdup(strings.version.c_str());
341     }
342 }
343 
android_getOpenglesVersion(int * maj,int * min)344 void android_getOpenglesVersion(int* maj, int* min) {
345     sRenderLib->getGlesVersion(maj, min);
346     fprintf(stderr, "%s: maj min %d %d\n", __func__, *maj, *min);
347 }
348 
349 void
android_stopOpenglesRenderer(bool wait)350 android_stopOpenglesRenderer(bool wait)
351 {
352     if (sRenderer) {
353         sRenderer->stop(wait);
354         if (wait) {
355             sRenderer.reset();
356             android_stop_opengl_logger();
357         }
358     }
359 }
360 
361 void
android_finishOpenglesRenderer()362 android_finishOpenglesRenderer()
363 {
364     if (sRenderer) {
365         sRenderer->finish();
366     }
367 }
368 
369 static gfxstream::RenderOpt sOpt;
370 static int sWidth, sHeight;
371 static int sNewWidth, sNewHeight;
372 
android_showOpenglesWindow(void * window,int wx,int wy,int ww,int wh,int fbw,int fbh,float dpr,float rotation,bool deleteExisting,bool hideWindow)373 int android_showOpenglesWindow(void* window,
374                                int wx,
375                                int wy,
376                                int ww,
377                                int wh,
378                                int fbw,
379                                int fbh,
380                                float dpr,
381                                float rotation,
382                                bool deleteExisting,
383                                bool hideWindow) {
384     if (!sRenderer) {
385         return -1;
386     }
387     FBNativeWindowType win = (FBNativeWindowType)(uintptr_t)window;
388     bool success = sRenderer->showOpenGLSubwindow(win, wx, wy, ww, wh, fbw, fbh,
389                                                   dpr, rotation, deleteExisting,
390                                                   hideWindow);
391     sNewWidth = ww * dpr;
392     sNewHeight = wh * dpr;
393     return success ? 0 : -1;
394 }
395 
396 void
android_setOpenglesTranslation(float px,float py)397 android_setOpenglesTranslation(float px, float py)
398 {
399     if (sRenderer) {
400         sRenderer->setOpenGLDisplayTranslation(px, py);
401     }
402 }
403 
404 void
android_setOpenglesScreenMask(int width,int height,const unsigned char * rgbaData)405 android_setOpenglesScreenMask(int width, int height, const unsigned char* rgbaData)
406 {
407     if (sRenderer) {
408         sRenderer->setScreenMask(width, height, rgbaData);
409     }
410 }
411 
412 int
android_hideOpenglesWindow(void)413 android_hideOpenglesWindow(void)
414 {
415     if (!sRenderer) {
416         return -1;
417     }
418     bool success = sRenderer->destroyOpenGLSubwindow();
419     return success ? 0 : -1;
420 }
421 
422 void
android_redrawOpenglesWindow(void)423 android_redrawOpenglesWindow(void)
424 {
425     if (sRenderer) {
426         sRenderer->repaintOpenGLDisplay();
427     }
428 }
429 
430 bool
android_hasGuestPostedAFrame(void)431 android_hasGuestPostedAFrame(void)
432 {
433     if (sRenderer) {
434         return sRenderer->hasGuestPostedAFrame();
435     }
436     return false;
437 }
438 
439 void
android_resetGuestPostedAFrame(void)440 android_resetGuestPostedAFrame(void)
441 {
442     if (sRenderer) {
443         sRenderer->resetGuestPostedAFrame();
444     }
445 }
446 
447 static ScreenshotFunc sScreenshotFunc = nullptr;
448 
android_registerScreenshotFunc(ScreenshotFunc f)449 void android_registerScreenshotFunc(ScreenshotFunc f)
450 {
451     sScreenshotFunc = f;
452 }
453 
android_screenShot(const char * dirname,uint32_t displayId)454 bool android_screenShot(const char* dirname, uint32_t displayId)
455 {
456     if (sScreenshotFunc) {
457         return sScreenshotFunc(dirname, displayId);
458     }
459     return false;
460 }
461 
android_getOpenglesRenderer()462 const gfxstream::RendererPtr& android_getOpenglesRenderer() { return sRenderer; }
463 
android_onGuestGraphicsProcessCreate(uint64_t puid)464 void android_onGuestGraphicsProcessCreate(uint64_t puid) {
465     if (sRenderer) {
466         sRenderer->onGuestGraphicsProcessCreate(puid);
467     }
468 }
469 
android_cleanupProcGLObjects(uint64_t puid)470 void android_cleanupProcGLObjects(uint64_t puid) {
471     if (sRenderer) {
472         sRenderer->cleanupProcGLObjects(puid);
473     }
474 }
475 
android_cleanupProcGLObjectsAndWaitFinished(uint64_t puid)476 void android_cleanupProcGLObjectsAndWaitFinished(uint64_t puid) {
477     if (sRenderer) {
478         sRenderer->cleanupProcGLObjects(puid);
479     }
480 }
481 
android_waitForOpenglesProcessCleanup()482 void android_waitForOpenglesProcessCleanup() {
483     if (sRenderer) {
484         sRenderer->waitForProcessCleanup();
485     }
486 }
487 
android_getVirtioGpuOps()488 struct AndroidVirtioGpuOps* android_getVirtioGpuOps() {
489     if (sRenderer) {
490         return sRenderer->getVirtioGpuOps();
491     }
492     return nullptr;
493 }
494 
android_getEGLDispatch()495 const void* android_getEGLDispatch() {
496     if (sRenderer) {
497         return sRenderer->getEglDispatch();
498     }
499     return nullptr;
500 }
501 
android_getGLESv2Dispatch()502 const void* android_getGLESv2Dispatch() {
503     if (sRenderer) {
504         return sRenderer->getGles2Dispatch();
505     }
506     return nullptr;
507 }
508 
android_setVsyncHz(int vsyncHz)509 void android_setVsyncHz(int vsyncHz) {
510     if (sRenderer) {
511         sRenderer->setVsyncHz(vsyncHz);
512     }
513 }
514 
android_setOpenglesDisplayConfigs(int configId,int w,int h,int dpiX,int dpiY)515 void android_setOpenglesDisplayConfigs(int configId, int w, int h, int dpiX,
516                                        int dpiY) {
517     if (sRenderer) {
518         sRenderer->setDisplayConfigs(configId, w, h, dpiX, dpiY);
519     }
520 }
521 
android_setOpenglesDisplayActiveConfig(int configId)522 void android_setOpenglesDisplayActiveConfig(int configId) {
523     if (sRenderer) {
524         sRenderer->setDisplayActiveConfig(configId);
525     }
526 }
527