• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 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 "SkiaCapture.h"
18 
19 #undef LOG_TAG
20 #define LOG_TAG "RenderEngine"
21 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
22 
23 #include <android-base/properties.h>
24 #include <android-base/stringprintf.h>
25 #include <log/log.h>
26 #include <renderengine/RenderEngine.h>
27 #include <utils/Trace.h>
28 
29 #include "CommonPool.h"
30 #include "src/utils/SkMultiPictureDocument.h"
31 
32 namespace android {
33 namespace renderengine {
34 namespace skia {
35 
36 // The root of the filename to write a recorded SKP to. In order for this file to
37 // be written to /data/user/, user must run 'adb shell setenforce 0' on the device.
38 static const std::string CAPTURED_FILENAME_BASE = "/data/user/re_skiacapture";
39 
~SkiaCapture()40 SkiaCapture::~SkiaCapture() {
41     mTimer.stop();
42 }
43 
tryCapture(SkSurface * surface)44 SkCanvas* SkiaCapture::tryCapture(SkSurface* surface) NO_THREAD_SAFETY_ANALYSIS {
45     ATRACE_CALL();
46 
47     // If we are not running yet, set up.
48     if (CC_LIKELY(!mCaptureRunning)) {
49         mTimerInterval = std::chrono::milliseconds(
50                 base::GetIntProperty(PROPERTY_DEBUG_RENDERENGINE_CAPTURE_SKIA_MS, 0));
51         // Set up the multi-frame capture. If we fail to set it up, then just return canvas.
52         // If interval is 0, return surface.
53         if (CC_LIKELY(mTimerInterval == 0ms || !setupMultiFrameCapture())) {
54             return surface->getCanvas();
55         }
56         // Start the new timer. When timer expires, write to file.
57         mTimer.setTimeout(
58                 [this] {
59                     const std::scoped_lock lock(mMutex);
60                     LOG_ALWAYS_FATAL_IF(mCurrentPageCanvas != nullptr);
61                     writeToFile();
62                     // To avoid going in circles, set the flag to 0. This way the capture can be
63                     // restarted just by setting the flag and without restarting the process.
64                     base::SetProperty(PROPERTY_DEBUG_RENDERENGINE_CAPTURE_SKIA_MS, "0");
65                 },
66                 mTimerInterval);
67     }
68 
69     mMutex.lock();
70 
71     // Create a canvas pointer, fill it.
72     mCurrentPageCanvas = mMultiPic->beginPage(surface->width(), surface->height());
73 
74     // Setting up an nway canvas is common to any kind of capture.
75     mNwayCanvas = std::make_unique<SkNWayCanvas>(surface->width(), surface->height());
76     mNwayCanvas->addCanvas(surface->getCanvas());
77     mNwayCanvas->addCanvas(mCurrentPageCanvas);
78 
79     return mNwayCanvas.get();
80 }
81 
endCapture()82 void SkiaCapture::endCapture() NO_THREAD_SAFETY_ANALYSIS {
83     ATRACE_CALL();
84     // Don't end anything if we are not running.
85     if (CC_LIKELY(!mCaptureRunning)) {
86         return;
87     }
88     // Reset the canvas pointer.
89     mCurrentPageCanvas = nullptr;
90     mNwayCanvas.reset();
91     // End page.
92     if (mMultiPic) {
93         mMultiPic->endPage();
94     }
95     mMutex.unlock();
96 }
97 
tryOffscreenCapture(SkSurface * surface,OffscreenState * state)98 SkCanvas* SkiaCapture::tryOffscreenCapture(SkSurface* surface, OffscreenState* state) {
99     ATRACE_CALL();
100     // Don't start anything if we are not running.
101     if (CC_LIKELY(!mCaptureRunning)) {
102         return surface->getCanvas();
103     }
104 
105     // Create a canvas pointer, fill it.
106     state->offscreenRecorder = std::make_unique<SkPictureRecorder>();
107     SkCanvas* pictureCanvas =
108             state->offscreenRecorder->beginRecording(surface->width(), surface->height());
109 
110     // Setting up an nway canvas is common to any kind of capture.
111     state->offscreenCanvas = std::make_unique<SkNWayCanvas>(surface->width(), surface->height());
112     state->offscreenCanvas->addCanvas(surface->getCanvas());
113     state->offscreenCanvas->addCanvas(pictureCanvas);
114 
115     return state->offscreenCanvas.get();
116 }
117 
endOffscreenCapture(OffscreenState * state)118 uint64_t SkiaCapture::endOffscreenCapture(OffscreenState* state) {
119     ATRACE_CALL();
120     // Don't end anything if we are not running.
121     if (CC_LIKELY(!mCaptureRunning)) {
122         return 0;
123     }
124 
125     // compute the uniqueID for this capture
126     static std::atomic<uint64_t> nextID{1};
127     const uint64_t uniqueID = nextID.fetch_add(1, std::memory_order_relaxed);
128 
129     // Reset the canvas pointer as we are no longer drawing into it
130     state->offscreenCanvas.reset();
131 
132     // Record the offscreen as a picture in the currently active page.
133     SkRect bounds =
134             SkRect::Make(state->offscreenRecorder->getRecordingCanvas()->imageInfo().dimensions());
135     mCurrentPageCanvas
136             ->drawAnnotation(bounds,
137                              String8::format("OffscreenLayerDraw|%" PRId64, uniqueID).c_str(),
138                              nullptr);
139     mCurrentPageCanvas->drawPicture(state->offscreenRecorder->finishRecordingAsPicture());
140 
141     // Reset the offscreen picture recorder
142     state->offscreenRecorder.reset();
143 
144     return uniqueID;
145 }
146 
writeToFile()147 void SkiaCapture::writeToFile() {
148     ATRACE_CALL();
149     // Pass mMultiPic and mOpenMultiPicStream to a background thread, which will
150     // handle the heavyweight serialization work and destroy them.
151     // mOpenMultiPicStream is released to a bare pointer because keeping it in
152     // a smart pointer makes the lambda non-copyable. The lambda is only called
153     // once, so this is safe.
154     SkFILEWStream* stream = mOpenMultiPicStream.release();
155     CommonPool::post([doc = std::move(mMultiPic), stream, name = std::move(mCaptureFile)] {
156         ALOGD("Finalizing multi frame SKP");
157         doc->close();
158         delete stream;
159         ALOGD("Multi frame SKP saved to %s.", name.c_str());
160         base::SetProperty(PROPERTY_DEBUG_RENDERENGINE_CAPTURE_FILENAME, name);
161     });
162     mCaptureRunning = false;
163 }
164 
setupMultiFrameCapture()165 bool SkiaCapture::setupMultiFrameCapture() {
166     ATRACE_CALL();
167     ALOGD("Set up multi-frame capture, ms = %llu", mTimerInterval.count());
168     base::SetProperty(PROPERTY_DEBUG_RENDERENGINE_CAPTURE_FILENAME, "");
169     const std::scoped_lock lock(mMutex);
170 
171     // Attach a timestamp to the file.
172     mCaptureFile.clear();
173     base::StringAppendF(&mCaptureFile, "%s_%lld.mskp", CAPTURED_FILENAME_BASE.c_str(),
174                         std::chrono::steady_clock::now().time_since_epoch().count());
175     auto stream = std::make_unique<SkFILEWStream>(mCaptureFile.c_str());
176     // We own this stream and need to hold it until close() finishes.
177     if (stream->isValid()) {
178         mOpenMultiPicStream = std::move(stream);
179         mSerialContext.reset(new SkSharingSerialContext());
180         SkSerialProcs procs;
181         procs.fImageProc = SkSharingSerialContext::serializeImage;
182         procs.fImageCtx = mSerialContext.get();
183         procs.fTypefaceProc = [](SkTypeface* tf, void* ctx) {
184             return tf->serialize(SkTypeface::SerializeBehavior::kDoIncludeData);
185         };
186         // SkDocuments don't take ownership of the streams they write.
187         // we need to keep it until after mMultiPic.close()
188         // procs is passed as a pointer, but just as a method of having an optional default.
189         // procs doesn't need to outlive this Make call
190         // The last argument is a callback for the endPage behavior.
191         // See SkSharingProc.h for more explanation of this callback.
192         mMultiPic = SkMakeMultiPictureDocument(
193                 mOpenMultiPicStream.get(), &procs,
194                 [sharingCtx = mSerialContext.get()](const SkPicture* pic) {
195                     SkSharingSerialContext::collectNonTextureImagesFromPicture(pic, sharingCtx);
196                 });
197         mCaptureRunning = true;
198         return true;
199     } else {
200         ALOGE("Could not open \"%s\" for writing.", mCaptureFile.c_str());
201         return false;
202     }
203 }
204 
205 } // namespace skia
206 } // namespace renderengine
207 } // namespace android
208