Surface.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  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. #define LOG_TAG "Surface"
  17. #define ATRACE_TAG ATRACE_TAG_GRAPHICS
  18. //#define LOG_NDEBUG 0
  19. #include <gui/Surface.h>
  20. #include <condition_variable>
  21. #include <deque>
  22. #include <mutex>
  23. #include <thread>
  24. #include <inttypes.h>
  25. #include <android/native_window.h>
  26. #include <utils/Log.h>
  27. #include <utils/Trace.h>
  28. #include <utils/NativeHandle.h>
  29. #include <ui/DisplayStatInfo.h>
  30. #include <ui/Fence.h>
  31. #include <ui/GraphicBuffer.h>
  32. #include <ui/HdrCapabilities.h>
  33. #include <ui/Region.h>
  34. #include <gui/BufferItem.h>
  35. #include <gui/IProducerListener.h>
  36. #include <gui/ISurfaceComposer.h>
  37. #include <private/gui/ComposerService.h>
  38. namespace android {
  39. using ui::ColorMode;
  40. using ui::Dataspace;
  41. Surface::Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp)
  42. : mGraphicBufferProducer(bufferProducer),
  43. mCrop(Rect::EMPTY_RECT),
  44. mBufferAge(0),
  45. mGenerationNumber(0),
  46. mSharedBufferMode(false),
  47. mAutoRefresh(false),
  48. mSharedBufferSlot(BufferItem::INVALID_BUFFER_SLOT),
  49. mSharedBufferHasBeenQueued(false),
  50. mQueriedSupportedTimestamps(false),
  51. mFrameTimestampsSupportsPresent(false),
  52. mEnableFrameTimestamps(false),
  53. mFrameEventHistory(std::make_unique<ProducerFrameEventHistory>()) {
  54. // Initialize the ANativeWindow function pointers.
  55. ANativeWindow::setSwapInterval = hook_setSwapInterval;
  56. ANativeWindow::dequeueBuffer = hook_dequeueBuffer;
  57. ANativeWindow::cancelBuffer = hook_cancelBuffer;
  58. ANativeWindow::queueBuffer = hook_queueBuffer;
  59. ANativeWindow::query = hook_query;
  60. ANativeWindow::perform = hook_perform;
  61. ANativeWindow::dequeueBuffer_DEPRECATED = hook_dequeueBuffer_DEPRECATED;
  62. ANativeWindow::cancelBuffer_DEPRECATED = hook_cancelBuffer_DEPRECATED;
  63. ANativeWindow::lockBuffer_DEPRECATED = hook_lockBuffer_DEPRECATED;
  64. ANativeWindow::queueBuffer_DEPRECATED = hook_queueBuffer_DEPRECATED;
  65. const_cast<int&>(ANativeWindow::minSwapInterval) = 0;
  66. const_cast<int&>(ANativeWindow::maxSwapInterval) = 1;
  67. mReqWidth = 0;
  68. mReqHeight = 0;
  69. mReqFormat = 0;
  70. mReqUsage = 0;
  71. mTimestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
  72. mDataSpace = Dataspace::UNKNOWN;
  73. mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
  74. mTransform = 0;
  75. mStickyTransform = 0;
  76. mDefaultWidth = 0;
  77. mDefaultHeight = 0;
  78. mUserWidth = 0;
  79. mUserHeight = 0;
  80. mTransformHint = 0;
  81. mConsumerRunningBehind = false;
  82. mConnectedToCpu = false;
  83. mProducerControlledByApp = controlledByApp;
  84. mSwapIntervalZero = false;
  85. }
  86. Surface::~Surface() {
  87. if (mConnectedToCpu) {
  88. Surface::disconnect(NATIVE_WINDOW_API_CPU);
  89. }
  90. }
  91. sp<ISurfaceComposer> Surface::composerService() const {
  92. return ComposerService::getComposerService();
  93. }
  94. nsecs_t Surface::now() const {
  95. return systemTime();
  96. }
  97. sp<IGraphicBufferProducer> Surface::getIGraphicBufferProducer() const {
  98. return mGraphicBufferProducer;
  99. }
  100. void Surface::setSidebandStream(const sp<NativeHandle>& stream) {
  101. mGraphicBufferProducer->setSidebandStream(stream);
  102. }
  103. void Surface::allocateBuffers() {
  104. uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
  105. uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
  106. mGraphicBufferProducer->allocateBuffers(reqWidth, reqHeight,
  107. mReqFormat, mReqUsage);
  108. }
  109. status_t Surface::setGenerationNumber(uint32_t generation) {
  110. status_t result = mGraphicBufferProducer->setGenerationNumber(generation);
  111. if (result == NO_ERROR) {
  112. mGenerationNumber = generation;
  113. }
  114. return result;
  115. }
  116. uint64_t Surface::getNextFrameNumber() const {
  117. Mutex::Autolock lock(mMutex);
  118. return mNextFrameNumber;
  119. }
  120. String8 Surface::getConsumerName() const {
  121. return mGraphicBufferProducer->getConsumerName();
  122. }
  123. status_t Surface::setDequeueTimeout(nsecs_t timeout) {
  124. return mGraphicBufferProducer->setDequeueTimeout(timeout);
  125. }
  126. status_t Surface::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
  127. sp<Fence>* outFence, float outTransformMatrix[16]) {
  128. return mGraphicBufferProducer->getLastQueuedBuffer(outBuffer, outFence,
  129. outTransformMatrix);
  130. }
  131. status_t Surface::getDisplayRefreshCycleDuration(nsecs_t* outRefreshDuration) {
  132. ATRACE_CALL();
  133. DisplayStatInfo stats;
  134. status_t result = composerService()->getDisplayStats(nullptr, &stats);
  135. if (result != NO_ERROR) {
  136. return result;
  137. }
  138. *outRefreshDuration = stats.vsyncPeriod;
  139. return NO_ERROR;
  140. }
  141. void Surface::enableFrameTimestamps(bool enable) {
  142. Mutex::Autolock lock(mMutex);
  143. // If going from disabled to enabled, get the initial values for
  144. // compositor and display timing.
  145. if (!mEnableFrameTimestamps && enable) {
  146. FrameEventHistoryDelta delta;
  147. mGraphicBufferProducer->getFrameTimestamps(&delta);
  148. mFrameEventHistory->applyDelta(delta);
  149. }
  150. mEnableFrameTimestamps = enable;
  151. }
  152. status_t Surface::getCompositorTiming(
  153. nsecs_t* compositeDeadline, nsecs_t* compositeInterval,
  154. nsecs_t* compositeToPresentLatency) {
  155. Mutex::Autolock lock(mMutex);
  156. if (!mEnableFrameTimestamps) {
  157. return INVALID_OPERATION;
  158. }
  159. if (compositeDeadline != nullptr) {
  160. *compositeDeadline =
  161. mFrameEventHistory->getNextCompositeDeadline(now());
  162. }
  163. if (compositeInterval != nullptr) {
  164. *compositeInterval = mFrameEventHistory->getCompositeInterval();
  165. }
  166. if (compositeToPresentLatency != nullptr) {
  167. *compositeToPresentLatency =
  168. mFrameEventHistory->getCompositeToPresentLatency();
  169. }
  170. return NO_ERROR;
  171. }
  172. static bool checkConsumerForUpdates(
  173. const FrameEvents* e, const uint64_t lastFrameNumber,
  174. const nsecs_t* outLatchTime,
  175. const nsecs_t* outFirstRefreshStartTime,
  176. const nsecs_t* outLastRefreshStartTime,
  177. const nsecs_t* outGpuCompositionDoneTime,
  178. const nsecs_t* outDisplayPresentTime,
  179. const nsecs_t* outDequeueReadyTime,
  180. const nsecs_t* outReleaseTime) {
  181. bool checkForLatch = (outLatchTime != nullptr) && !e->hasLatchInfo();
  182. bool checkForFirstRefreshStart = (outFirstRefreshStartTime != nullptr) &&
  183. !e->hasFirstRefreshStartInfo();
  184. bool checkForGpuCompositionDone = (outGpuCompositionDoneTime != nullptr) &&
  185. !e->hasGpuCompositionDoneInfo();
  186. bool checkForDisplayPresent = (outDisplayPresentTime != nullptr) &&
  187. !e->hasDisplayPresentInfo();
  188. // LastRefreshStart, DequeueReady, and Release are never available for the
  189. // last frame.
  190. bool checkForLastRefreshStart = (outLastRefreshStartTime != nullptr) &&
  191. !e->hasLastRefreshStartInfo() &&
  192. (e->frameNumber != lastFrameNumber);
  193. bool checkForDequeueReady = (outDequeueReadyTime != nullptr) &&
  194. !e->hasDequeueReadyInfo() && (e->frameNumber != lastFrameNumber);
  195. bool checkForRelease = (outReleaseTime != nullptr) &&
  196. !e->hasReleaseInfo() && (e->frameNumber != lastFrameNumber);
  197. // RequestedPresent and Acquire info are always available producer-side.
  198. return checkForLatch || checkForFirstRefreshStart ||
  199. checkForLastRefreshStart || checkForGpuCompositionDone ||
  200. checkForDisplayPresent || checkForDequeueReady || checkForRelease;
  201. }
  202. static void getFrameTimestamp(nsecs_t *dst, const nsecs_t& src) {
  203. if (dst != nullptr) {
  204. // We always get valid timestamps for these eventually.
  205. *dst = (src == FrameEvents::TIMESTAMP_PENDING) ?
  206. NATIVE_WINDOW_TIMESTAMP_PENDING : src;
  207. }
  208. }
  209. static void getFrameTimestampFence(nsecs_t *dst,
  210. const std::shared_ptr<FenceTime>& src, bool fenceShouldBeKnown) {
  211. if (dst != nullptr) {
  212. if (!fenceShouldBeKnown) {
  213. *dst = NATIVE_WINDOW_TIMESTAMP_PENDING;
  214. return;
  215. }
  216. nsecs_t signalTime = src->getSignalTime();
  217. *dst = (signalTime == Fence::SIGNAL_TIME_PENDING) ?
  218. NATIVE_WINDOW_TIMESTAMP_PENDING :
  219. (signalTime == Fence::SIGNAL_TIME_INVALID) ?
  220. NATIVE_WINDOW_TIMESTAMP_INVALID :
  221. signalTime;
  222. }
  223. }
  224. status_t Surface::getFrameTimestamps(uint64_t frameNumber,
  225. nsecs_t* outRequestedPresentTime, nsecs_t* outAcquireTime,
  226. nsecs_t* outLatchTime, nsecs_t* outFirstRefreshStartTime,
  227. nsecs_t* outLastRefreshStartTime, nsecs_t* outGpuCompositionDoneTime,
  228. nsecs_t* outDisplayPresentTime, nsecs_t* outDequeueReadyTime,
  229. nsecs_t* outReleaseTime) {
  230. ATRACE_CALL();
  231. Mutex::Autolock lock(mMutex);
  232. if (!mEnableFrameTimestamps) {
  233. return INVALID_OPERATION;
  234. }
  235. // Verify the requested timestamps are supported.
  236. querySupportedTimestampsLocked();
  237. if (outDisplayPresentTime != nullptr && !mFrameTimestampsSupportsPresent) {
  238. return BAD_VALUE;
  239. }
  240. FrameEvents* events = mFrameEventHistory->getFrame(frameNumber);
  241. if (events == nullptr) {
  242. // If the entry isn't available in the producer, it's definitely not
  243. // available in the consumer.
  244. return NAME_NOT_FOUND;
  245. }
  246. // Update our cache of events if the requested events are not available.
  247. if (checkConsumerForUpdates(events, mLastFrameNumber,
  248. outLatchTime, outFirstRefreshStartTime, outLastRefreshStartTime,
  249. outGpuCompositionDoneTime, outDisplayPresentTime,
  250. outDequeueReadyTime, outReleaseTime)) {
  251. FrameEventHistoryDelta delta;
  252. mGraphicBufferProducer->getFrameTimestamps(&delta);
  253. mFrameEventHistory->applyDelta(delta);
  254. events = mFrameEventHistory->getFrame(frameNumber);
  255. }
  256. if (events == nullptr) {
  257. // The entry was available before the update, but was overwritten
  258. // after the update. Make sure not to send the wrong frame's data.
  259. return NAME_NOT_FOUND;
  260. }
  261. getFrameTimestamp(outRequestedPresentTime, events->requestedPresentTime);
  262. getFrameTimestamp(outLatchTime, events->latchTime);
  263. getFrameTimestamp(outFirstRefreshStartTime, events->firstRefreshStartTime);
  264. getFrameTimestamp(outLastRefreshStartTime, events->lastRefreshStartTime);
  265. getFrameTimestamp(outDequeueReadyTime, events->dequeueReadyTime);
  266. getFrameTimestampFence(outAcquireTime, events->acquireFence,
  267. events->hasAcquireInfo());
  268. getFrameTimestampFence(outGpuCompositionDoneTime,
  269. events->gpuCompositionDoneFence,
  270. events->hasGpuCompositionDoneInfo());
  271. getFrameTimestampFence(outDisplayPresentTime, events->displayPresentFence,
  272. events->hasDisplayPresentInfo());
  273. getFrameTimestampFence(outReleaseTime, events->releaseFence,
  274. events->hasReleaseInfo());
  275. return NO_ERROR;
  276. }
  277. status_t Surface::getWideColorSupport(bool* supported) {
  278. ATRACE_CALL();
  279. const sp<IBinder> display = composerService()->getInternalDisplayToken();
  280. if (display == nullptr) {
  281. return NAME_NOT_FOUND;
  282. }
  283. *supported = false;
  284. status_t error = composerService()->isWideColorDisplay(display, supported);
  285. return error;
  286. }
  287. status_t Surface::getHdrSupport(bool* supported) {
  288. ATRACE_CALL();
  289. const sp<IBinder> display = composerService()->getInternalDisplayToken();
  290. if (display == nullptr) {
  291. return NAME_NOT_FOUND;
  292. }
  293. HdrCapabilities hdrCapabilities;
  294. status_t err =
  295. composerService()->getHdrCapabilities(display, &hdrCapabilities);
  296. if (err)
  297. return err;
  298. *supported = !hdrCapabilities.getSupportedHdrTypes().empty();
  299. return NO_ERROR;
  300. }
  301. int Surface::hook_setSwapInterval(ANativeWindow* window, int interval) {
  302. Surface* c = getSelf(window);
  303. return c->setSwapInterval(interval);
  304. }
  305. int Surface::hook_dequeueBuffer(ANativeWindow* window,
  306. ANativeWindowBuffer** buffer, int* fenceFd) {
  307. Surface* c = getSelf(window);
  308. return c->dequeueBuffer(buffer, fenceFd);
  309. }
  310. int Surface::hook_cancelBuffer(ANativeWindow* window,
  311. ANativeWindowBuffer* buffer, int fenceFd) {
  312. Surface* c = getSelf(window);
  313. return c->cancelBuffer(buffer, fenceFd);
  314. }
  315. int Surface::hook_queueBuffer(ANativeWindow* window,
  316. ANativeWindowBuffer* buffer, int fenceFd) {
  317. Surface* c = getSelf(window);
  318. return c->queueBuffer(buffer, fenceFd);
  319. }
  320. int Surface::hook_dequeueBuffer_DEPRECATED(ANativeWindow* window,
  321. ANativeWindowBuffer** buffer) {
  322. Surface* c = getSelf(window);
  323. ANativeWindowBuffer* buf;
  324. int fenceFd = -1;
  325. int result = c->dequeueBuffer(&buf, &fenceFd);
  326. if (result != OK) {
  327. return result;
  328. }
  329. sp<Fence> fence(new Fence(fenceFd));
  330. int waitResult = fence->waitForever("dequeueBuffer_DEPRECATED");
  331. if (waitResult != OK) {
  332. ALOGE("dequeueBuffer_DEPRECATED: Fence::wait returned an error: %d",
  333. waitResult);
  334. c->cancelBuffer(buf, -1);
  335. return waitResult;
  336. }
  337. *buffer = buf;
  338. return result;
  339. }
  340. int Surface::hook_cancelBuffer_DEPRECATED(ANativeWindow* window,
  341. ANativeWindowBuffer* buffer) {
  342. Surface* c = getSelf(window);
  343. return c->cancelBuffer(buffer, -1);
  344. }
  345. int Surface::hook_lockBuffer_DEPRECATED(ANativeWindow* window,
  346. ANativeWindowBuffer* buffer) {
  347. Surface* c = getSelf(window);
  348. return c->lockBuffer_DEPRECATED(buffer);
  349. }
  350. int Surface::hook_queueBuffer_DEPRECATED(ANativeWindow* window,
  351. ANativeWindowBuffer* buffer) {
  352. Surface* c = getSelf(window);
  353. return c->queueBuffer(buffer, -1);
  354. }
  355. int Surface::hook_query(const ANativeWindow* window,
  356. int what, int* value) {
  357. const Surface* c = getSelf(window);
  358. return c->query(what, value);
  359. }
  360. int Surface::hook_perform(ANativeWindow* window, int operation, ...) {
  361. va_list args;
  362. va_start(args, operation);
  363. Surface* c = getSelf(window);
  364. int result = c->perform(operation, args);
  365. va_end(args);
  366. return result;
  367. }
  368. int Surface::setSwapInterval(int interval) {
  369. ATRACE_CALL();
  370. // EGL specification states:
  371. // interval is silently clamped to minimum and maximum implementation
  372. // dependent values before being stored.
  373. if (interval < minSwapInterval)
  374. interval = minSwapInterval;
  375. if (interval > maxSwapInterval)
  376. interval = maxSwapInterval;
  377. const bool wasSwapIntervalZero = mSwapIntervalZero;
  378. mSwapIntervalZero = (interval == 0);
  379. if (mSwapIntervalZero != wasSwapIntervalZero) {
  380. mGraphicBufferProducer->setAsyncMode(mSwapIntervalZero);
  381. }
  382. return NO_ERROR;
  383. }
  384. class FenceMonitor {
  385. public:
  386. explicit FenceMonitor(const char* name) : mName(name), mFencesQueued(0), mFencesSignaled(0) {
  387. std::thread thread(&FenceMonitor::loop, this);
  388. pthread_setname_np(thread.native_handle(), mName);
  389. thread.detach();
  390. }
  391. void queueFence(const sp<Fence>& fence) {
  392. char message[64];
  393. std::lock_guard<std::mutex> lock(mMutex);
  394. if (fence->getSignalTime() != Fence::SIGNAL_TIME_PENDING) {
  395. snprintf(message, sizeof(message), "%s fence %u has signaled", mName, mFencesQueued);
  396. ATRACE_NAME(message);
  397. // Need an increment on both to make the trace number correct.
  398. mFencesQueued++;
  399. mFencesSignaled++;
  400. return;
  401. }
  402. snprintf(message, sizeof(message), "Trace %s fence %u", mName, mFencesQueued);
  403. ATRACE_NAME(message);
  404. mQueue.push_back(fence);
  405. mCondition.notify_one();
  406. mFencesQueued++;
  407. ATRACE_INT(mName, int32_t(mQueue.size()));
  408. }
  409. private:
  410. #pragma clang diagnostic push
  411. #pragma clang diagnostic ignored "-Wmissing-noreturn"
  412. void loop() {
  413. while (true) {
  414. threadLoop();
  415. }
  416. }
  417. #pragma clang diagnostic pop
  418. void threadLoop() {
  419. sp<Fence> fence;
  420. uint32_t fenceNum;
  421. {
  422. std::unique_lock<std::mutex> lock(mMutex);
  423. while (mQueue.empty()) {
  424. mCondition.wait(lock);
  425. }
  426. fence = mQueue[0];
  427. fenceNum = mFencesSignaled;
  428. }
  429. {
  430. char message[64];
  431. snprintf(message, sizeof(message), "waiting for %s %u", mName, fenceNum);
  432. ATRACE_NAME(message);
  433. status_t result = fence->waitForever(message);
  434. if (result != OK) {
  435. ALOGE("Error waiting for fence: %d", result);
  436. }
  437. }
  438. {
  439. std::lock_guard<std::mutex> lock(mMutex);
  440. mQueue.pop_front();
  441. mFencesSignaled++;
  442. ATRACE_INT(mName, int32_t(mQueue.size()));
  443. }
  444. }
  445. const char* mName;
  446. uint32_t mFencesQueued;
  447. uint32_t mFencesSignaled;
  448. std::deque<sp<Fence>> mQueue;
  449. std::condition_variable mCondition;
  450. std::mutex mMutex;
  451. };
  452. int Surface::dequeueBuffer(android_native_buffer_t** buffer, int* fenceFd) {
  453. ATRACE_CALL();
  454. ALOGV("Surface::dequeueBuffer");
  455. uint32_t reqWidth;
  456. uint32_t reqHeight;
  457. PixelFormat reqFormat;
  458. uint64_t reqUsage;
  459. bool enableFrameTimestamps;
  460. {
  461. Mutex::Autolock lock(mMutex);
  462. if (mReportRemovedBuffers) {
  463. mRemovedBuffers.clear();
  464. }
  465. reqWidth = mReqWidth ? mReqWidth : mUserWidth;
  466. reqHeight = mReqHeight ? mReqHeight : mUserHeight;
  467. reqFormat = mReqFormat;
  468. reqUsage = mReqUsage;
  469. enableFrameTimestamps = mEnableFrameTimestamps;
  470. if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot !=
  471. BufferItem::INVALID_BUFFER_SLOT) {
  472. sp<GraphicBuffer>& gbuf(mSlots[mSharedBufferSlot].buffer);
  473. if (gbuf != nullptr) {
  474. *buffer = gbuf.get();
  475. *fenceFd = -1;
  476. return OK;
  477. }
  478. }
  479. } // Drop the lock so that we can still touch the Surface while blocking in IGBP::dequeueBuffer
  480. int buf = -1;
  481. sp<Fence> fence;
  482. nsecs_t startTime = systemTime();
  483. FrameEventHistoryDelta frameTimestamps;
  484. status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, reqWidth, reqHeight,
  485. reqFormat, reqUsage, &mBufferAge,
  486. enableFrameTimestamps ? &frameTimestamps
  487. : nullptr);
  488. mLastDequeueDuration = systemTime() - startTime;
  489. if (result < 0) {
  490. ALOGV("dequeueBuffer: IGraphicBufferProducer::dequeueBuffer"
  491. "(%d, %d, %d, %#" PRIx64 ") failed: %d",
  492. reqWidth, reqHeight, reqFormat, reqUsage, result);
  493. return result;
  494. }
  495. if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
  496. ALOGE("dequeueBuffer: IGraphicBufferProducer returned invalid slot number %d", buf);
  497. android_errorWriteLog(0x534e4554, "36991414"); // SafetyNet logging
  498. return FAILED_TRANSACTION;
  499. }
  500. Mutex::Autolock lock(mMutex);
  501. // Write this while holding the mutex
  502. mLastDequeueStartTime = startTime;
  503. sp<GraphicBuffer>& gbuf(mSlots[buf].buffer);
  504. // this should never happen
  505. ALOGE_IF(fence == nullptr, "Surface::dequeueBuffer: received null Fence! buf=%d", buf);
  506. if (CC_UNLIKELY(atrace_is_tag_enabled(ATRACE_TAG_GRAPHICS))) {
  507. static FenceMonitor hwcReleaseThread("HWC release");
  508. hwcReleaseThread.queueFence(fence);
  509. }
  510. if (result & IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
  511. freeAllBuffers();
  512. }
  513. if (enableFrameTimestamps) {
  514. mFrameEventHistory->applyDelta(frameTimestamps);
  515. }
  516. if ((result & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) || gbuf == nullptr) {
  517. if (mReportRemovedBuffers && (gbuf != nullptr)) {
  518. mRemovedBuffers.push_back(gbuf);
  519. }
  520. result = mGraphicBufferProducer->requestBuffer(buf, &gbuf);
  521. if (result != NO_ERROR) {
  522. ALOGE("dequeueBuffer: IGraphicBufferProducer::requestBuffer failed: %d", result);
  523. mGraphicBufferProducer->cancelBuffer(buf, fence);
  524. return result;
  525. }
  526. }
  527. if (fence->isValid()) {
  528. *fenceFd = fence->dup();
  529. if (*fenceFd == -1) {
  530. ALOGE("dequeueBuffer: error duping fence: %d", errno);
  531. // dup() should never fail; something is badly wrong. Soldier on
  532. // and hope for the best; the worst that should happen is some
  533. // visible corruption that lasts until the next frame.
  534. }
  535. } else {
  536. *fenceFd = -1;
  537. }
  538. *buffer = gbuf.get();
  539. if (mSharedBufferMode && mAutoRefresh) {
  540. mSharedBufferSlot = buf;
  541. mSharedBufferHasBeenQueued = false;
  542. } else if (mSharedBufferSlot == buf) {
  543. mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
  544. mSharedBufferHasBeenQueued = false;
  545. }
  546. return OK;
  547. }
  548. int Surface::cancelBuffer(android_native_buffer_t* buffer,
  549. int fenceFd) {
  550. ATRACE_CALL();
  551. ALOGV("Surface::cancelBuffer");
  552. Mutex::Autolock lock(mMutex);
  553. int i = getSlotFromBufferLocked(buffer);
  554. if (i < 0) {
  555. if (fenceFd >= 0) {
  556. close(fenceFd);
  557. }
  558. return i;
  559. }
  560. if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
  561. if (fenceFd >= 0) {
  562. close(fenceFd);
  563. }
  564. return OK;
  565. }
  566. sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
  567. mGraphicBufferProducer->cancelBuffer(i, fence);
  568. if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == i) {
  569. mSharedBufferHasBeenQueued = true;
  570. }
  571. return OK;
  572. }
  573. int Surface::getSlotFromBufferLocked(
  574. android_native_buffer_t* buffer) const {
  575. for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
  576. if (mSlots[i].buffer != nullptr &&
  577. mSlots[i].buffer->handle == buffer->handle) {
  578. return i;
  579. }
  580. }
  581. ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
  582. return BAD_VALUE;
  583. }
  584. int Surface::lockBuffer_DEPRECATED(android_native_buffer_t* buffer __attribute__((unused))) {
  585. ALOGV("Surface::lockBuffer");
  586. Mutex::Autolock lock(mMutex);
  587. return OK;
  588. }
  589. int Surface::queueBuffer(android_native_buffer_t* buffer, int fenceFd) {
  590. ATRACE_CALL();
  591. ALOGV("Surface::queueBuffer");
  592. Mutex::Autolock lock(mMutex);
  593. int64_t timestamp;
  594. bool isAutoTimestamp = false;
  595. if (mTimestamp == NATIVE_WINDOW_TIMESTAMP_AUTO) {
  596. timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
  597. isAutoTimestamp = true;
  598. ALOGV("Surface::queueBuffer making up timestamp: %.2f ms",
  599. timestamp / 1000000.0);
  600. } else {
  601. timestamp = mTimestamp;
  602. }
  603. int i = getSlotFromBufferLocked(buffer);
  604. if (i < 0) {
  605. if (fenceFd >= 0) {
  606. close(fenceFd);
  607. }
  608. return i;
  609. }
  610. if (mSharedBufferSlot == i && mSharedBufferHasBeenQueued) {
  611. if (fenceFd >= 0) {
  612. close(fenceFd);
  613. }
  614. return OK;
  615. }
  616. // Make sure the crop rectangle is entirely inside the buffer.
  617. Rect crop(Rect::EMPTY_RECT);
  618. mCrop.intersect(Rect(buffer->width, buffer->height), &crop);
  619. sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
  620. IGraphicBufferProducer::QueueBufferOutput output;
  621. IGraphicBufferProducer::QueueBufferInput input(timestamp, isAutoTimestamp,
  622. static_cast<android_dataspace>(mDataSpace), crop, mScalingMode,
  623. mTransform ^ mStickyTransform, fence, mStickyTransform,
  624. mEnableFrameTimestamps);
  625. // we should send HDR metadata as needed if this becomes a bottleneck
  626. input.setHdrMetadata(mHdrMetadata);
  627. if (mConnectedToCpu || mDirtyRegion.bounds() == Rect::INVALID_RECT) {
  628. input.setSurfaceDamage(Region::INVALID_REGION);
  629. } else {
  630. // Here we do two things:
  631. // 1) The surface damage was specified using the OpenGL ES convention of
  632. // the origin being in the bottom-left corner. Here we flip to the
  633. // convention that the rest of the system uses (top-left corner) by
  634. // subtracting all top/bottom coordinates from the buffer height.
  635. // 2) If the buffer is coming in rotated (for example, because the EGL
  636. // implementation is reacting to the transform hint coming back from
  637. // SurfaceFlinger), the surface damage needs to be rotated the
  638. // opposite direction, since it was generated assuming an unrotated
  639. // buffer (the app doesn't know that the EGL implementation is
  640. // reacting to the transform hint behind its back). The
  641. // transformations in the switch statement below apply those
  642. // complementary rotations (e.g., if 90 degrees, rotate 270 degrees).
  643. int width = buffer->width;
  644. int height = buffer->height;
  645. bool rotated90 = (mTransform ^ mStickyTransform) &
  646. NATIVE_WINDOW_TRANSFORM_ROT_90;
  647. if (rotated90) {
  648. std::swap(width, height);
  649. }
  650. Region flippedRegion;
  651. for (auto rect : mDirtyRegion) {
  652. int left = rect.left;
  653. int right = rect.right;
  654. int top = height - rect.bottom; // Flip from OpenGL convention
  655. int bottom = height - rect.top; // Flip from OpenGL convention
  656. switch (mTransform ^ mStickyTransform) {
  657. case NATIVE_WINDOW_TRANSFORM_ROT_90: {
  658. // Rotate 270 degrees
  659. Rect flippedRect{top, width - right, bottom, width - left};
  660. flippedRegion.orSelf(flippedRect);
  661. break;
  662. }
  663. case NATIVE_WINDOW_TRANSFORM_ROT_180: {
  664. // Rotate 180 degrees
  665. Rect flippedRect{width - right, height - bottom,
  666. width - left, height - top};
  667. flippedRegion.orSelf(flippedRect);
  668. break;
  669. }
  670. case NATIVE_WINDOW_TRANSFORM_ROT_270: {
  671. // Rotate 90 degrees
  672. Rect flippedRect{height - bottom, left,
  673. height - top, right};
  674. flippedRegion.orSelf(flippedRect);
  675. break;
  676. }
  677. default: {
  678. Rect flippedRect{left, top, right, bottom};
  679. flippedRegion.orSelf(flippedRect);
  680. break;
  681. }
  682. }
  683. }
  684. input.setSurfaceDamage(flippedRegion);
  685. }
  686. nsecs_t now = systemTime();
  687. status_t err = mGraphicBufferProducer->queueBuffer(i, input, &output);
  688. mLastQueueDuration = systemTime() - now;
  689. if (err != OK) {
  690. ALOGE("queueBuffer: error queuing buffer to SurfaceTexture, %d", err);
  691. }
  692. if (mEnableFrameTimestamps) {
  693. mFrameEventHistory->applyDelta(output.frameTimestamps);
  694. // Update timestamps with the local acquire fence.
  695. // The consumer doesn't send it back to prevent us from having two
  696. // file descriptors of the same fence.
  697. mFrameEventHistory->updateAcquireFence(mNextFrameNumber,
  698. std::make_shared<FenceTime>(fence));
  699. // Cache timestamps of signaled fences so we can close their file
  700. // descriptors.
  701. mFrameEventHistory->updateSignalTimes();
  702. }
  703. mLastFrameNumber = mNextFrameNumber;
  704. mDefaultWidth = output.width;
  705. mDefaultHeight = output.height;
  706. mNextFrameNumber = output.nextFrameNumber;
  707. // Ignore transform hint if sticky transform is set or transform to display inverse flag is
  708. // set.
  709. if (mStickyTransform == 0 && !transformToDisplayInverse()) {
  710. mTransformHint = output.transformHint;
  711. }
  712. mConsumerRunningBehind = (output.numPendingBuffers >= 2);
  713. if (!mConnectedToCpu) {
  714. // Clear surface damage back to full-buffer
  715. mDirtyRegion = Region::INVALID_REGION;
  716. }
  717. if (mSharedBufferMode && mAutoRefresh && mSharedBufferSlot == i) {
  718. mSharedBufferHasBeenQueued = true;
  719. }
  720. mQueueBufferCondition.broadcast();
  721. if (CC_UNLIKELY(atrace_is_tag_enabled(ATRACE_TAG_GRAPHICS))) {
  722. static FenceMonitor gpuCompletionThread("GPU completion");
  723. gpuCompletionThread.queueFence(fence);
  724. }
  725. return err;
  726. }
  727. void Surface::querySupportedTimestampsLocked() const {
  728. // mMutex must be locked when calling this method.
  729. if (mQueriedSupportedTimestamps) {
  730. return;
  731. }
  732. mQueriedSupportedTimestamps = true;
  733. std::vector<FrameEvent> supportedFrameTimestamps;
  734. status_t err = composerService()->getSupportedFrameTimestamps(
  735. &supportedFrameTimestamps);
  736. if (err != NO_ERROR) {
  737. return;
  738. }
  739. for (auto sft : supportedFrameTimestamps) {
  740. if (sft == FrameEvent::DISPLAY_PRESENT) {
  741. mFrameTimestampsSupportsPresent = true;
  742. }
  743. }
  744. }
  745. int Surface::query(int what, int* value) const {
  746. ATRACE_CALL();
  747. ALOGV("Surface::query");
  748. { // scope for the lock
  749. Mutex::Autolock lock(mMutex);
  750. switch (what) {
  751. case NATIVE_WINDOW_FORMAT:
  752. if (mReqFormat) {
  753. *value = static_cast<int>(mReqFormat);
  754. return NO_ERROR;
  755. }
  756. break;
  757. case NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER: {
  758. if (composerService()->authenticateSurfaceTexture(
  759. mGraphicBufferProducer)) {
  760. *value = 1;
  761. } else {
  762. *value = 0;
  763. }
  764. return NO_ERROR;
  765. }
  766. case NATIVE_WINDOW_CONCRETE_TYPE:
  767. *value = NATIVE_WINDOW_SURFACE;
  768. return NO_ERROR;
  769. case NATIVE_WINDOW_DEFAULT_WIDTH:
  770. *value = static_cast<int>(
  771. mUserWidth ? mUserWidth : mDefaultWidth);
  772. return NO_ERROR;
  773. case NATIVE_WINDOW_DEFAULT_HEIGHT:
  774. *value = static_cast<int>(
  775. mUserHeight ? mUserHeight : mDefaultHeight);
  776. return NO_ERROR;
  777. case NATIVE_WINDOW_TRANSFORM_HINT:
  778. *value = static_cast<int>(mTransformHint);
  779. return NO_ERROR;
  780. case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: {
  781. status_t err = NO_ERROR;
  782. if (!mConsumerRunningBehind) {
  783. *value = 0;
  784. } else {
  785. err = mGraphicBufferProducer->query(what, value);
  786. if (err == NO_ERROR) {
  787. mConsumerRunningBehind = *value;
  788. }
  789. }
  790. return err;
  791. }
  792. case NATIVE_WINDOW_BUFFER_AGE: {
  793. if (mBufferAge > INT32_MAX) {
  794. *value = 0;
  795. } else {
  796. *value = static_cast<int32_t>(mBufferAge);
  797. }
  798. return NO_ERROR;
  799. }
  800. case NATIVE_WINDOW_LAST_DEQUEUE_DURATION: {
  801. int64_t durationUs = mLastDequeueDuration / 1000;
  802. *value = durationUs > std::numeric_limits<int>::max() ?
  803. std::numeric_limits<int>::max() :
  804. static_cast<int>(durationUs);
  805. return NO_ERROR;
  806. }
  807. case NATIVE_WINDOW_LAST_QUEUE_DURATION: {
  808. int64_t durationUs = mLastQueueDuration / 1000;
  809. *value = durationUs > std::numeric_limits<int>::max() ?
  810. std::numeric_limits<int>::max() :
  811. static_cast<int>(durationUs);
  812. return NO_ERROR;
  813. }
  814. case NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT: {
  815. querySupportedTimestampsLocked();
  816. *value = mFrameTimestampsSupportsPresent ? 1 : 0;
  817. return NO_ERROR;
  818. }
  819. case NATIVE_WINDOW_IS_VALID: {
  820. *value = mGraphicBufferProducer != nullptr ? 1 : 0;
  821. return NO_ERROR;
  822. }
  823. case NATIVE_WINDOW_DATASPACE: {
  824. *value = static_cast<int>(mDataSpace);
  825. return NO_ERROR;
  826. }
  827. }
  828. }
  829. return mGraphicBufferProducer->query(what, value);
  830. }
  831. int Surface::perform(int operation, va_list args)
  832. {
  833. int res = NO_ERROR;
  834. switch (operation) {
  835. case NATIVE_WINDOW_CONNECT:
  836. // deprecated. must return NO_ERROR.
  837. break;
  838. case NATIVE_WINDOW_DISCONNECT:
  839. // deprecated. must return NO_ERROR.
  840. break;
  841. case NATIVE_WINDOW_SET_USAGE:
  842. res = dispatchSetUsage(args);
  843. break;
  844. case NATIVE_WINDOW_SET_CROP:
  845. res = dispatchSetCrop(args);
  846. break;
  847. case NATIVE_WINDOW_SET_BUFFER_COUNT:
  848. res = dispatchSetBufferCount(args);
  849. break;
  850. case NATIVE_WINDOW_SET_BUFFERS_GEOMETRY:
  851. res = dispatchSetBuffersGeometry(args);
  852. break;
  853. case NATIVE_WINDOW_SET_BUFFERS_TRANSFORM:
  854. res = dispatchSetBuffersTransform(args);
  855. break;
  856. case NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM:
  857. res = dispatchSetBuffersStickyTransform(args);
  858. break;
  859. case NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP:
  860. res = dispatchSetBuffersTimestamp(args);
  861. break;
  862. case NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS:
  863. res = dispatchSetBuffersDimensions(args);
  864. break;
  865. case NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS:
  866. res = dispatchSetBuffersUserDimensions(args);
  867. break;
  868. case NATIVE_WINDOW_SET_BUFFERS_FORMAT:
  869. res = dispatchSetBuffersFormat(args);
  870. break;
  871. case NATIVE_WINDOW_LOCK:
  872. res = dispatchLock(args);
  873. break;
  874. case NATIVE_WINDOW_UNLOCK_AND_POST:
  875. res = dispatchUnlockAndPost(args);
  876. break;
  877. case NATIVE_WINDOW_SET_SCALING_MODE:
  878. res = dispatchSetScalingMode(args);
  879. break;
  880. case NATIVE_WINDOW_API_CONNECT:
  881. res = dispatchConnect(args);
  882. break;
  883. case NATIVE_WINDOW_API_DISCONNECT:
  884. res = dispatchDisconnect(args);
  885. break;
  886. case NATIVE_WINDOW_SET_SIDEBAND_STREAM:
  887. res = dispatchSetSidebandStream(args);
  888. break;
  889. case NATIVE_WINDOW_SET_BUFFERS_DATASPACE:
  890. res = dispatchSetBuffersDataSpace(args);
  891. break;
  892. case NATIVE_WINDOW_SET_BUFFERS_SMPTE2086_METADATA:
  893. res = dispatchSetBuffersSmpte2086Metadata(args);
  894. break;
  895. case NATIVE_WINDOW_SET_BUFFERS_CTA861_3_METADATA:
  896. res = dispatchSetBuffersCta8613Metadata(args);
  897. break;
  898. case NATIVE_WINDOW_SET_BUFFERS_HDR10_PLUS_METADATA:
  899. res = dispatchSetBuffersHdr10PlusMetadata(args);
  900. break;
  901. case NATIVE_WINDOW_SET_SURFACE_DAMAGE:
  902. res = dispatchSetSurfaceDamage(args);
  903. break;
  904. case NATIVE_WINDOW_SET_SHARED_BUFFER_MODE:
  905. res = dispatchSetSharedBufferMode(args);
  906. break;
  907. case NATIVE_WINDOW_SET_AUTO_REFRESH:
  908. res = dispatchSetAutoRefresh(args);
  909. break;
  910. case NATIVE_WINDOW_GET_REFRESH_CYCLE_DURATION:
  911. res = dispatchGetDisplayRefreshCycleDuration(args);
  912. break;
  913. case NATIVE_WINDOW_GET_NEXT_FRAME_ID:
  914. res = dispatchGetNextFrameId(args);
  915. break;
  916. case NATIVE_WINDOW_ENABLE_FRAME_TIMESTAMPS:
  917. res = dispatchEnableFrameTimestamps(args);
  918. break;
  919. case NATIVE_WINDOW_GET_COMPOSITOR_TIMING:
  920. res = dispatchGetCompositorTiming(args);
  921. break;
  922. case NATIVE_WINDOW_GET_FRAME_TIMESTAMPS:
  923. res = dispatchGetFrameTimestamps(args);
  924. break;
  925. case NATIVE_WINDOW_GET_WIDE_COLOR_SUPPORT:
  926. res = dispatchGetWideColorSupport(args);
  927. break;
  928. case NATIVE_WINDOW_GET_HDR_SUPPORT:
  929. res = dispatchGetHdrSupport(args);
  930. break;
  931. case NATIVE_WINDOW_SET_USAGE64:
  932. res = dispatchSetUsage64(args);
  933. break;
  934. case NATIVE_WINDOW_GET_CONSUMER_USAGE64:
  935. res = dispatchGetConsumerUsage64(args);
  936. break;
  937. default:
  938. res = NAME_NOT_FOUND;
  939. break;
  940. }
  941. return res;
  942. }
  943. int Surface::dispatchConnect(va_list args) {
  944. int api = va_arg(args, int);
  945. return connect(api);
  946. }
  947. int Surface::dispatchDisconnect(va_list args) {
  948. int api = va_arg(args, int);
  949. return disconnect(api);
  950. }
  951. int Surface::dispatchSetUsage(va_list args) {
  952. uint64_t usage = va_arg(args, uint32_t);
  953. return setUsage(usage);
  954. }
  955. int Surface::dispatchSetUsage64(va_list args) {
  956. uint64_t usage = va_arg(args, uint64_t);
  957. return setUsage(usage);
  958. }
  959. int Surface::dispatchSetCrop(va_list args) {
  960. android_native_rect_t const* rect = va_arg(args, android_native_rect_t*);
  961. return setCrop(reinterpret_cast<Rect const*>(rect));
  962. }
  963. int Surface::dispatchSetBufferCount(va_list args) {
  964. size_t bufferCount = va_arg(args, size_t);
  965. return setBufferCount(static_cast<int32_t>(bufferCount));
  966. }
  967. int Surface::dispatchSetBuffersGeometry(va_list args) {
  968. uint32_t width = va_arg(args, uint32_t);
  969. uint32_t height = va_arg(args, uint32_t);
  970. PixelFormat format = va_arg(args, PixelFormat);
  971. int err = setBuffersDimensions(width, height);
  972. if (err != 0) {
  973. return err;
  974. }
  975. return setBuffersFormat(format);
  976. }
  977. int Surface::dispatchSetBuffersDimensions(va_list args) {
  978. uint32_t width = va_arg(args, uint32_t);
  979. uint32_t height = va_arg(args, uint32_t);
  980. return setBuffersDimensions(width, height);
  981. }
  982. int Surface::dispatchSetBuffersUserDimensions(va_list args) {
  983. uint32_t width = va_arg(args, uint32_t);
  984. uint32_t height = va_arg(args, uint32_t);
  985. return setBuffersUserDimensions(width, height);
  986. }
  987. int Surface::dispatchSetBuffersFormat(va_list args) {
  988. PixelFormat format = va_arg(args, PixelFormat);
  989. return setBuffersFormat(format);
  990. }
  991. int Surface::dispatchSetScalingMode(va_list args) {
  992. int mode = va_arg(args, int);
  993. return setScalingMode(mode);
  994. }
  995. int Surface::dispatchSetBuffersTransform(va_list args) {
  996. uint32_t transform = va_arg(args, uint32_t);
  997. return setBuffersTransform(transform);
  998. }
  999. int Surface::dispatchSetBuffersStickyTransform(va_list args) {
  1000. uint32_t transform = va_arg(args, uint32_t);
  1001. return setBuffersStickyTransform(transform);
  1002. }
  1003. int Surface::dispatchSetBuffersTimestamp(va_list args) {
  1004. int64_t timestamp = va_arg(args, int64_t);
  1005. return setBuffersTimestamp(timestamp);
  1006. }
  1007. int Surface::dispatchLock(va_list args) {
  1008. ANativeWindow_Buffer* outBuffer = va_arg(args, ANativeWindow_Buffer*);
  1009. ARect* inOutDirtyBounds = va_arg(args, ARect*);
  1010. return lock(outBuffer, inOutDirtyBounds);
  1011. }
  1012. int Surface::dispatchUnlockAndPost(va_list args __attribute__((unused))) {
  1013. return unlockAndPost();
  1014. }
  1015. int Surface::dispatchSetSidebandStream(va_list args) {
  1016. native_handle_t* sH = va_arg(args, native_handle_t*);
  1017. sp<NativeHandle> sidebandHandle = NativeHandle::create(sH, false);
  1018. setSidebandStream(sidebandHandle);
  1019. return OK;
  1020. }
  1021. int Surface::dispatchSetBuffersDataSpace(va_list args) {
  1022. Dataspace dataspace = static_cast<Dataspace>(va_arg(args, int));
  1023. return setBuffersDataSpace(dataspace);
  1024. }
  1025. int Surface::dispatchSetBuffersSmpte2086Metadata(va_list args) {
  1026. const android_smpte2086_metadata* metadata =
  1027. va_arg(args, const android_smpte2086_metadata*);
  1028. return setBuffersSmpte2086Metadata(metadata);
  1029. }
  1030. int Surface::dispatchSetBuffersCta8613Metadata(va_list args) {
  1031. const android_cta861_3_metadata* metadata =
  1032. va_arg(args, const android_cta861_3_metadata*);
  1033. return setBuffersCta8613Metadata(metadata);
  1034. }
  1035. int Surface::dispatchSetBuffersHdr10PlusMetadata(va_list args) {
  1036. const size_t size = va_arg(args, size_t);
  1037. const uint8_t* metadata = va_arg(args, const uint8_t*);
  1038. return setBuffersHdr10PlusMetadata(size, metadata);
  1039. }
  1040. int Surface::dispatchSetSurfaceDamage(va_list args) {
  1041. android_native_rect_t* rects = va_arg(args, android_native_rect_t*);
  1042. size_t numRects = va_arg(args, size_t);
  1043. setSurfaceDamage(rects, numRects);
  1044. return NO_ERROR;
  1045. }
  1046. int Surface::dispatchSetSharedBufferMode(va_list args) {
  1047. bool sharedBufferMode = va_arg(args, int);
  1048. return setSharedBufferMode(sharedBufferMode);
  1049. }
  1050. int Surface::dispatchSetAutoRefresh(va_list args) {
  1051. bool autoRefresh = va_arg(args, int);
  1052. return setAutoRefresh(autoRefresh);
  1053. }
  1054. int Surface::dispatchGetDisplayRefreshCycleDuration(va_list args) {
  1055. nsecs_t* outRefreshDuration = va_arg(args, int64_t*);
  1056. return getDisplayRefreshCycleDuration(outRefreshDuration);
  1057. }
  1058. int Surface::dispatchGetNextFrameId(va_list args) {
  1059. uint64_t* nextFrameId = va_arg(args, uint64_t*);
  1060. *nextFrameId = getNextFrameNumber();
  1061. return NO_ERROR;
  1062. }
  1063. int Surface::dispatchEnableFrameTimestamps(va_list args) {
  1064. bool enable = va_arg(args, int);
  1065. enableFrameTimestamps(enable);
  1066. return NO_ERROR;
  1067. }
  1068. int Surface::dispatchGetCompositorTiming(va_list args) {
  1069. nsecs_t* compositeDeadline = va_arg(args, int64_t*);
  1070. nsecs_t* compositeInterval = va_arg(args, int64_t*);
  1071. nsecs_t* compositeToPresentLatency = va_arg(args, int64_t*);
  1072. return getCompositorTiming(compositeDeadline, compositeInterval,
  1073. compositeToPresentLatency);
  1074. }
  1075. int Surface::dispatchGetFrameTimestamps(va_list args) {
  1076. uint64_t frameId = va_arg(args, uint64_t);
  1077. nsecs_t* outRequestedPresentTime = va_arg(args, int64_t*);
  1078. nsecs_t* outAcquireTime = va_arg(args, int64_t*);
  1079. nsecs_t* outLatchTime = va_arg(args, int64_t*);
  1080. nsecs_t* outFirstRefreshStartTime = va_arg(args, int64_t*);
  1081. nsecs_t* outLastRefreshStartTime = va_arg(args, int64_t*);
  1082. nsecs_t* outGpuCompositionDoneTime = va_arg(args, int64_t*);
  1083. nsecs_t* outDisplayPresentTime = va_arg(args, int64_t*);
  1084. nsecs_t* outDequeueReadyTime = va_arg(args, int64_t*);
  1085. nsecs_t* outReleaseTime = va_arg(args, int64_t*);
  1086. return getFrameTimestamps(frameId,
  1087. outRequestedPresentTime, outAcquireTime, outLatchTime,
  1088. outFirstRefreshStartTime, outLastRefreshStartTime,
  1089. outGpuCompositionDoneTime, outDisplayPresentTime,
  1090. outDequeueReadyTime, outReleaseTime);
  1091. }
  1092. int Surface::dispatchGetWideColorSupport(va_list args) {
  1093. bool* outSupport = va_arg(args, bool*);
  1094. return getWideColorSupport(outSupport);
  1095. }
  1096. int Surface::dispatchGetHdrSupport(va_list args) {
  1097. bool* outSupport = va_arg(args, bool*);
  1098. return getHdrSupport(outSupport);
  1099. }
  1100. int Surface::dispatchGetConsumerUsage64(va_list args) {
  1101. uint64_t* usage = va_arg(args, uint64_t*);
  1102. return getConsumerUsage(usage);
  1103. }
  1104. bool Surface::transformToDisplayInverse() {
  1105. return (mTransform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) ==
  1106. NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
  1107. }
  1108. int Surface::connect(int api) {
  1109. static sp<IProducerListener> listener = new DummyProducerListener();
  1110. return connect(api, listener);
  1111. }
  1112. int Surface::connect(int api, const sp<IProducerListener>& listener) {
  1113. return connect(api, listener, false);
  1114. }
  1115. int Surface::connect(
  1116. int api, bool reportBufferRemoval, const sp<SurfaceListener>& sListener) {
  1117. if (sListener != nullptr) {
  1118. mListenerProxy = new ProducerListenerProxy(this, sListener);
  1119. }
  1120. return connect(api, mListenerProxy, reportBufferRemoval);
  1121. }
  1122. int Surface::connect(
  1123. int api, const sp<IProducerListener>& listener, bool reportBufferRemoval) {
  1124. ATRACE_CALL();
  1125. ALOGV("Surface::connect");
  1126. Mutex::Autolock lock(mMutex);
  1127. IGraphicBufferProducer::QueueBufferOutput output;
  1128. mReportRemovedBuffers = reportBufferRemoval;
  1129. int err = mGraphicBufferProducer->connect(listener, api, mProducerControlledByApp, &output);
  1130. if (err == NO_ERROR) {
  1131. mDefaultWidth = output.width;
  1132. mDefaultHeight = output.height;
  1133. mNextFrameNumber = output.nextFrameNumber;
  1134. // Ignore transform hint if sticky transform is set or transform to display inverse flag is
  1135. // set. Transform hint should be ignored if the client is expected to always submit buffers
  1136. // in the same orientation.
  1137. if (mStickyTransform == 0 && !transformToDisplayInverse()) {
  1138. mTransformHint = output.transformHint;
  1139. }
  1140. mConsumerRunningBehind = (output.numPendingBuffers >= 2);
  1141. }
  1142. if (!err && api == NATIVE_WINDOW_API_CPU) {
  1143. mConnectedToCpu = true;
  1144. // Clear the dirty region in case we're switching from a non-CPU API
  1145. mDirtyRegion.clear();
  1146. } else if (!err) {
  1147. // Initialize the dirty region for tracking surface damage
  1148. mDirtyRegion = Region::INVALID_REGION;
  1149. }
  1150. return err;
  1151. }
  1152. int Surface::disconnect(int api, IGraphicBufferProducer::DisconnectMode mode) {
  1153. ATRACE_CALL();
  1154. ALOGV("Surface::disconnect");
  1155. Mutex::Autolock lock(mMutex);
  1156. mRemovedBuffers.clear();
  1157. mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
  1158. mSharedBufferHasBeenQueued = false;
  1159. freeAllBuffers();
  1160. int err = mGraphicBufferProducer->disconnect(api, mode);
  1161. if (!err) {
  1162. mReqFormat = 0;
  1163. mReqWidth = 0;
  1164. mReqHeight = 0;
  1165. mReqUsage = 0;
  1166. mCrop.clear();
  1167. mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
  1168. mTransform = 0;
  1169. mStickyTransform = 0;
  1170. if (api == NATIVE_WINDOW_API_CPU) {
  1171. mConnectedToCpu = false;
  1172. }
  1173. }
  1174. return err;
  1175. }
  1176. int Surface::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
  1177. sp<Fence>* outFence) {
  1178. ATRACE_CALL();
  1179. ALOGV("Surface::detachNextBuffer");
  1180. if (outBuffer == nullptr || outFence == nullptr) {
  1181. return BAD_VALUE;
  1182. }
  1183. Mutex::Autolock lock(mMutex);
  1184. if (mReportRemovedBuffers) {
  1185. mRemovedBuffers.clear();
  1186. }
  1187. sp<GraphicBuffer> buffer(nullptr);
  1188. sp<Fence> fence(nullptr);
  1189. status_t result = mGraphicBufferProducer->detachNextBuffer(
  1190. &buffer, &fence);
  1191. if (result != NO_ERROR) {
  1192. return result;
  1193. }
  1194. *outBuffer = buffer;
  1195. if (fence != nullptr && fence->isValid()) {
  1196. *outFence = fence;
  1197. } else {
  1198. *outFence = Fence::NO_FENCE;
  1199. }
  1200. for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
  1201. if (mSlots[i].buffer != nullptr &&
  1202. mSlots[i].buffer->getId() == buffer->getId()) {
  1203. if (mReportRemovedBuffers) {
  1204. mRemovedBuffers.push_back(mSlots[i].buffer);
  1205. }
  1206. mSlots[i].buffer = nullptr;
  1207. }
  1208. }
  1209. return NO_ERROR;
  1210. }
  1211. int Surface::attachBuffer(ANativeWindowBuffer* buffer)
  1212. {
  1213. ATRACE_CALL();
  1214. ALOGV("Surface::attachBuffer");
  1215. Mutex::Autolock lock(mMutex);
  1216. if (mReportRemovedBuffers) {
  1217. mRemovedBuffers.clear();
  1218. }
  1219. sp<GraphicBuffer> graphicBuffer(static_cast<GraphicBuffer*>(buffer));
  1220. uint32_t priorGeneration = graphicBuffer->mGenerationNumber;
  1221. graphicBuffer->mGenerationNumber = mGenerationNumber;
  1222. int32_t attachedSlot = -1;
  1223. status_t result = mGraphicBufferProducer->attachBuffer(&attachedSlot, graphicBuffer);
  1224. if (result != NO_ERROR) {
  1225. ALOGE("attachBuffer: IGraphicBufferProducer call failed (%d)", result);
  1226. graphicBuffer->mGenerationNumber = priorGeneration;
  1227. return result;
  1228. }
  1229. if (mReportRemovedBuffers && (mSlots[attachedSlot].buffer != nullptr)) {
  1230. mRemovedBuffers.push_back(mSlots[attachedSlot].buffer);
  1231. }
  1232. mSlots[attachedSlot].buffer = graphicBuffer;
  1233. return NO_ERROR;
  1234. }
  1235. int Surface::setUsage(uint64_t reqUsage)
  1236. {
  1237. ALOGV("Surface::setUsage");
  1238. Mutex::Autolock lock(mMutex);
  1239. if (reqUsage != mReqUsage) {
  1240. mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
  1241. }
  1242. mReqUsage = reqUsage;
  1243. return OK;
  1244. }
  1245. int Surface::setCrop(Rect const* rect)
  1246. {
  1247. ATRACE_CALL();
  1248. Rect realRect(Rect::EMPTY_RECT);
  1249. if (rect == nullptr || rect->isEmpty()) {
  1250. realRect.clear();
  1251. } else {
  1252. realRect = *rect;
  1253. }
  1254. ALOGV("Surface::setCrop rect=[%d %d %d %d]",
  1255. realRect.left, realRect.top, realRect.right, realRect.bottom);
  1256. Mutex::Autolock lock(mMutex);
  1257. mCrop = realRect;
  1258. return NO_ERROR;
  1259. }
  1260. int Surface::setBufferCount(int bufferCount)
  1261. {
  1262. ATRACE_CALL();
  1263. ALOGV("Surface::setBufferCount");
  1264. Mutex::Autolock lock(mMutex);
  1265. status_t err = NO_ERROR;
  1266. if (bufferCount == 0) {
  1267. err = mGraphicBufferProducer->setMaxDequeuedBufferCount(1);
  1268. } else {
  1269. int minUndequeuedBuffers = 0;
  1270. err = mGraphicBufferProducer->query(
  1271. NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBuffers);
  1272. if (err == NO_ERROR) {
  1273. err = mGraphicBufferProducer->setMaxDequeuedBufferCount(
  1274. bufferCount - minUndequeuedBuffers);
  1275. }
  1276. }
  1277. ALOGE_IF(err, "IGraphicBufferProducer::setBufferCount(%d) returned %s",
  1278. bufferCount, strerror(-err));
  1279. return err;
  1280. }
  1281. int Surface::setMaxDequeuedBufferCount(int maxDequeuedBuffers) {
  1282. ATRACE_CALL();
  1283. ALOGV("Surface::setMaxDequeuedBufferCount");
  1284. Mutex::Autolock lock(mMutex);
  1285. status_t err = mGraphicBufferProducer->setMaxDequeuedBufferCount(
  1286. maxDequeuedBuffers);
  1287. ALOGE_IF(err, "IGraphicBufferProducer::setMaxDequeuedBufferCount(%d) "
  1288. "returned %s", maxDequeuedBuffers, strerror(-err));
  1289. return err;
  1290. }
  1291. int Surface::setAsyncMode(bool async) {
  1292. ATRACE_CALL();
  1293. ALOGV("Surface::setAsyncMode");
  1294. Mutex::Autolock lock(mMutex);
  1295. status_t err = mGraphicBufferProducer->setAsyncMode(async);
  1296. ALOGE_IF(err, "IGraphicBufferProducer::setAsyncMode(%d) returned %s",
  1297. async, strerror(-err));
  1298. return err;
  1299. }
  1300. int Surface::setSharedBufferMode(bool sharedBufferMode) {
  1301. ATRACE_CALL();
  1302. ALOGV("Surface::setSharedBufferMode (%d)", sharedBufferMode);
  1303. Mutex::Autolock lock(mMutex);
  1304. status_t err = mGraphicBufferProducer->setSharedBufferMode(
  1305. sharedBufferMode);
  1306. if (err == NO_ERROR) {
  1307. mSharedBufferMode = sharedBufferMode;
  1308. }
  1309. ALOGE_IF(err, "IGraphicBufferProducer::setSharedBufferMode(%d) returned"
  1310. "%s", sharedBufferMode, strerror(-err));
  1311. return err;
  1312. }
  1313. int Surface::setAutoRefresh(bool autoRefresh) {
  1314. ATRACE_CALL();
  1315. ALOGV("Surface::setAutoRefresh (%d)", autoRefresh);
  1316. Mutex::Autolock lock(mMutex);
  1317. status_t err = mGraphicBufferProducer->setAutoRefresh(autoRefresh);
  1318. if (err == NO_ERROR) {
  1319. mAutoRefresh = autoRefresh;
  1320. }
  1321. ALOGE_IF(err, "IGraphicBufferProducer::setAutoRefresh(%d) returned %s",
  1322. autoRefresh, strerror(-err));
  1323. return err;
  1324. }
  1325. int Surface::setBuffersDimensions(uint32_t width, uint32_t height)
  1326. {
  1327. ATRACE_CALL();
  1328. ALOGV("Surface::setBuffersDimensions");
  1329. if ((width && !height) || (!width && height))
  1330. return BAD_VALUE;
  1331. Mutex::Autolock lock(mMutex);
  1332. if (width != mReqWidth || height != mReqHeight) {
  1333. mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
  1334. }
  1335. mReqWidth = width;
  1336. mReqHeight = height;
  1337. return NO_ERROR;
  1338. }
  1339. int Surface::setBuffersUserDimensions(uint32_t width, uint32_t height)
  1340. {
  1341. ATRACE_CALL();
  1342. ALOGV("Surface::setBuffersUserDimensions");
  1343. if ((width && !height) || (!width && height))
  1344. return BAD_VALUE;
  1345. Mutex::Autolock lock(mMutex);
  1346. if (width != mUserWidth || height != mUserHeight) {
  1347. mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
  1348. }
  1349. mUserWidth = width;
  1350. mUserHeight = height;
  1351. return NO_ERROR;
  1352. }
  1353. int Surface::setBuffersFormat(PixelFormat format)
  1354. {
  1355. ALOGV("Surface::setBuffersFormat");
  1356. Mutex::Autolock lock(mMutex);
  1357. if (format != mReqFormat) {
  1358. mSharedBufferSlot = BufferItem::INVALID_BUFFER_SLOT;
  1359. }
  1360. mReqFormat = format;
  1361. return NO_ERROR;
  1362. }
  1363. int Surface::setScalingMode(int mode)
  1364. {
  1365. ATRACE_CALL();
  1366. ALOGV("Surface::setScalingMode(%d)", mode);
  1367. switch (mode) {
  1368. case NATIVE_WINDOW_SCALING_MODE_FREEZE:
  1369. case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
  1370. case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
  1371. case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
  1372. break;
  1373. default:
  1374. ALOGE("unknown scaling mode: %d", mode);
  1375. return BAD_VALUE;
  1376. }
  1377. Mutex::Autolock lock(mMutex);
  1378. mScalingMode = mode;
  1379. return NO_ERROR;
  1380. }
  1381. int Surface::setBuffersTransform(uint32_t transform)
  1382. {
  1383. ATRACE_CALL();
  1384. ALOGV("Surface::setBuffersTransform");
  1385. Mutex::Autolock lock(mMutex);
  1386. // Ensure NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY is sticky. If the client sets the flag, do not
  1387. // override it until the surface is disconnected. This is a temporary workaround for camera
  1388. // until they switch to using Buffer State Layers. Currently if client sets the buffer transform
  1389. // it may be overriden by the buffer producer when the producer sets the buffer transform.
  1390. if (transformToDisplayInverse()) {
  1391. transform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
  1392. }
  1393. mTransform = transform;
  1394. return NO_ERROR;
  1395. }
  1396. int Surface::setBuffersStickyTransform(uint32_t transform)
  1397. {
  1398. ATRACE_CALL();
  1399. ALOGV("Surface::setBuffersStickyTransform");
  1400. Mutex::Autolock lock(mMutex);
  1401. mStickyTransform = transform;
  1402. return NO_ERROR;
  1403. }
  1404. int Surface::setBuffersTimestamp(int64_t timestamp)
  1405. {
  1406. ALOGV("Surface::setBuffersTimestamp");
  1407. Mutex::Autolock lock(mMutex);
  1408. mTimestamp = timestamp;
  1409. return NO_ERROR;
  1410. }
  1411. int Surface::setBuffersDataSpace(Dataspace dataSpace)
  1412. {
  1413. ALOGV("Surface::setBuffersDataSpace");
  1414. Mutex::Autolock lock(mMutex);
  1415. mDataSpace = dataSpace;
  1416. return NO_ERROR;
  1417. }
  1418. int Surface::setBuffersSmpte2086Metadata(const android_smpte2086_metadata* metadata) {
  1419. ALOGV("Surface::setBuffersSmpte2086Metadata");
  1420. Mutex::Autolock lock(mMutex);
  1421. if (metadata) {
  1422. mHdrMetadata.smpte2086 = *metadata;
  1423. mHdrMetadata.validTypes |= HdrMetadata::SMPTE2086;
  1424. } else {
  1425. mHdrMetadata.validTypes &= ~HdrMetadata::SMPTE2086;
  1426. }
  1427. return NO_ERROR;
  1428. }
  1429. int Surface::setBuffersCta8613Metadata(const android_cta861_3_metadata* metadata) {
  1430. ALOGV("Surface::setBuffersCta8613Metadata");
  1431. Mutex::Autolock lock(mMutex);
  1432. if (metadata) {
  1433. mHdrMetadata.cta8613 = *metadata;
  1434. mHdrMetadata.validTypes |= HdrMetadata::CTA861_3;
  1435. } else {
  1436. mHdrMetadata.validTypes &= ~HdrMetadata::CTA861_3;
  1437. }
  1438. return NO_ERROR;
  1439. }
  1440. int Surface::setBuffersHdr10PlusMetadata(const size_t size, const uint8_t* metadata) {
  1441. ALOGV("Surface::setBuffersBlobMetadata");
  1442. Mutex::Autolock lock(mMutex);
  1443. if (size > 0) {
  1444. mHdrMetadata.hdr10plus.assign(metadata, metadata + size);
  1445. mHdrMetadata.validTypes |= HdrMetadata::HDR10PLUS;
  1446. } else {
  1447. mHdrMetadata.validTypes &= ~HdrMetadata::HDR10PLUS;
  1448. mHdrMetadata.hdr10plus.clear();
  1449. }
  1450. return NO_ERROR;
  1451. }
  1452. Dataspace Surface::getBuffersDataSpace() {
  1453. ALOGV("Surface::getBuffersDataSpace");
  1454. Mutex::Autolock lock(mMutex);
  1455. return mDataSpace;
  1456. }
  1457. void Surface::freeAllBuffers() {
  1458. for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
  1459. mSlots[i].buffer = nullptr;
  1460. }
  1461. }
  1462. status_t Surface::getAndFlushBuffersFromSlots(const std::vector<int32_t>& slots,
  1463. std::vector<sp<GraphicBuffer>>* outBuffers) {
  1464. ALOGV("Surface::getAndFlushBuffersFromSlots");
  1465. for (int32_t i : slots) {
  1466. if (i < 0 || i >= NUM_BUFFER_SLOTS) {
  1467. ALOGE("%s: Invalid slotIndex: %d", __FUNCTION__, i);
  1468. return BAD_VALUE;
  1469. }
  1470. }
  1471. Mutex::Autolock lock(mMutex);
  1472. for (int32_t i : slots) {
  1473. if (mSlots[i].buffer == nullptr) {
  1474. ALOGW("%s: Discarded slot %d doesn't contain buffer!", __FUNCTION__, i);
  1475. continue;
  1476. }
  1477. outBuffers->push_back(mSlots[i].buffer);
  1478. mSlots[i].buffer = nullptr;
  1479. }
  1480. return OK;
  1481. }
  1482. void Surface::setSurfaceDamage(android_native_rect_t* rects, size_t numRects) {
  1483. ATRACE_CALL();
  1484. ALOGV("Surface::setSurfaceDamage");
  1485. Mutex::Autolock lock(mMutex);
  1486. if (mConnectedToCpu || numRects == 0) {
  1487. mDirtyRegion = Region::INVALID_REGION;
  1488. return;
  1489. }
  1490. mDirtyRegion.clear();
  1491. for (size_t r = 0; r < numRects; ++r) {
  1492. // We intentionally flip top and bottom here, since because they're
  1493. // specified with a bottom-left origin, top > bottom, which fails
  1494. // validation in the Region class. We will fix this up when we flip to a
  1495. // top-left origin in queueBuffer.
  1496. Rect rect(rects[r].left, rects[r].bottom, rects[r].right, rects[r].top);
  1497. mDirtyRegion.orSelf(rect);
  1498. }
  1499. }
  1500. // ----------------------------------------------------------------------
  1501. // the lock/unlock APIs must be used from the same thread
  1502. static status_t copyBlt(
  1503. const sp<GraphicBuffer>& dst,
  1504. const sp<GraphicBuffer>& src,
  1505. const Region& reg,
  1506. int *dstFenceFd)
  1507. {
  1508. if (dst->getId() == src->getId())
  1509. return OK;
  1510. // src and dst with, height and format must be identical. no verification
  1511. // is done here.
  1512. status_t err;
  1513. uint8_t* src_bits = nullptr;
  1514. err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(),
  1515. reinterpret_cast<void**>(&src_bits));
  1516. ALOGE_IF(err, "error locking src buffer %s", strerror(-err));
  1517. uint8_t* dst_bits = nullptr;
  1518. err = dst->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(),
  1519. reinterpret_cast<void**>(&dst_bits), *dstFenceFd);
  1520. ALOGE_IF(err, "error locking dst buffer %s", strerror(-err));
  1521. *dstFenceFd = -1;
  1522. Region::const_iterator head(reg.begin());
  1523. Region::const_iterator tail(reg.end());
  1524. if (head != tail && src_bits && dst_bits) {
  1525. const size_t bpp = bytesPerPixel(src->format);
  1526. const size_t dbpr = static_cast<uint32_t>(dst->stride) * bpp;
  1527. const size_t sbpr = static_cast<uint32_t>(src->stride) * bpp;
  1528. while (head != tail) {
  1529. const Rect& r(*head++);
  1530. int32_t h = r.height();
  1531. if (h <= 0) continue;
  1532. size_t size = static_cast<uint32_t>(r.width()) * bpp;
  1533. uint8_t const * s = src_bits +
  1534. static_cast<uint32_t>(r.left + src->stride * r.top) * bpp;
  1535. uint8_t * d = dst_bits +
  1536. static_cast<uint32_t>(r.left + dst->stride * r.top) * bpp;
  1537. if (dbpr==sbpr && size==sbpr) {
  1538. size *= static_cast<size_t>(h);
  1539. h = 1;
  1540. }
  1541. do {
  1542. memcpy(d, s, size);
  1543. d += dbpr;
  1544. s += sbpr;
  1545. } while (--h > 0);
  1546. }
  1547. }
  1548. if (src_bits)
  1549. src->unlock();
  1550. if (dst_bits)
  1551. dst->unlockAsync(dstFenceFd);
  1552. return err;
  1553. }
  1554. // ----------------------------------------------------------------------------
  1555. status_t Surface::lock(
  1556. ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds)
  1557. {
  1558. if (mLockedBuffer != nullptr) {
  1559. ALOGE("Surface::lock failed, already locked");
  1560. return INVALID_OPERATION;
  1561. }
  1562. if (!mConnectedToCpu) {
  1563. int err = Surface::connect(NATIVE_WINDOW_API_CPU);
  1564. if (err) {
  1565. return err;
  1566. }
  1567. // we're intending to do software rendering from this point
  1568. setUsage(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
  1569. }
  1570. ANativeWindowBuffer* out;
  1571. int fenceFd = -1;
  1572. status_t err = dequeueBuffer(&out, &fenceFd);
  1573. ALOGE_IF(err, "dequeueBuffer failed (%s)", strerror(-err));
  1574. if (err == NO_ERROR) {
  1575. sp<GraphicBuffer> backBuffer(GraphicBuffer::getSelf(out));
  1576. const Rect bounds(backBuffer->width, backBuffer->height);
  1577. Region newDirtyRegion;
  1578. if (inOutDirtyBounds) {
  1579. newDirtyRegion.set(static_cast<Rect const&>(*inOutDirtyBounds));
  1580. newDirtyRegion.andSelf(bounds);
  1581. } else {
  1582. newDirtyRegion.set(bounds);
  1583. }
  1584. // figure out if we can copy the frontbuffer back
  1585. const sp<GraphicBuffer>& frontBuffer(mPostedBuffer);
  1586. const bool canCopyBack = (frontBuffer != nullptr &&
  1587. backBuffer->width == frontBuffer->width &&
  1588. backBuffer->height == frontBuffer->height &&
  1589. backBuffer->format == frontBuffer->format);
  1590. if (canCopyBack) {
  1591. // copy the area that is invalid and not repainted this round
  1592. const Region copyback(mDirtyRegion.subtract(newDirtyRegion));
  1593. if (!copyback.isEmpty()) {
  1594. copyBlt(backBuffer, frontBuffer, copyback, &fenceFd);
  1595. }
  1596. } else {
  1597. // if we can't copy-back anything, modify the user's dirty
  1598. // region to make sure they redraw the whole buffer
  1599. newDirtyRegion.set(bounds);
  1600. mDirtyRegion.clear();
  1601. Mutex::Autolock lock(mMutex);
  1602. for (size_t i=0 ; i<NUM_BUFFER_SLOTS ; i++) {
  1603. mSlots[i].dirtyRegion.clear();
  1604. }
  1605. }
  1606. { // scope for the lock
  1607. Mutex::Autolock lock(mMutex);
  1608. int backBufferSlot(getSlotFromBufferLocked(backBuffer.get()));
  1609. if (backBufferSlot >= 0) {
  1610. Region& dirtyRegion(mSlots[backBufferSlot].dirtyRegion);
  1611. mDirtyRegion.subtract(dirtyRegion);
  1612. dirtyRegion = newDirtyRegion;
  1613. }
  1614. }
  1615. mDirtyRegion.orSelf(newDirtyRegion);
  1616. if (inOutDirtyBounds) {
  1617. *inOutDirtyBounds = newDirtyRegion.getBounds();
  1618. }
  1619. void* vaddr;
  1620. status_t res = backBuffer->lockAsync(
  1621. GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
  1622. newDirtyRegion.bounds(), &vaddr, fenceFd);
  1623. ALOGW_IF(res, "failed locking buffer (handle = %p)",
  1624. backBuffer->handle);
  1625. if (res != 0) {
  1626. err = INVALID_OPERATION;
  1627. } else {
  1628. mLockedBuffer = backBuffer;
  1629. outBuffer->width = backBuffer->width;
  1630. outBuffer->height = backBuffer->height;
  1631. outBuffer->stride = backBuffer->stride;
  1632. outBuffer->format = backBuffer->format;
  1633. outBuffer->bits = vaddr;
  1634. }
  1635. }
  1636. return err;
  1637. }
  1638. status_t Surface::unlockAndPost()
  1639. {
  1640. if (mLockedBuffer == nullptr) {
  1641. ALOGE("Surface::unlockAndPost failed, no locked buffer");
  1642. return INVALID_OPERATION;
  1643. }
  1644. int fd = -1;
  1645. status_t err = mLockedBuffer->unlockAsync(&fd);
  1646. ALOGE_IF(err, "failed unlocking buffer (%p)", mLockedBuffer->handle);
  1647. err = queueBuffer(mLockedBuffer.get(), fd);
  1648. ALOGE_IF(err, "queueBuffer (handle=%p) failed (%s)",
  1649. mLockedBuffer->handle, strerror(-err));
  1650. mPostedBuffer = mLockedBuffer;
  1651. mLockedBuffer = nullptr;
  1652. return err;
  1653. }
  1654. bool Surface::waitForNextFrame(uint64_t lastFrame, nsecs_t timeout) {
  1655. Mutex::Autolock lock(mMutex);
  1656. if (mNextFrameNumber > lastFrame) {
  1657. return true;
  1658. }
  1659. return mQueueBufferCondition.waitRelative(mMutex, timeout) == OK;
  1660. }
  1661. status_t Surface::getUniqueId(uint64_t* outId) const {
  1662. Mutex::Autolock lock(mMutex);
  1663. return mGraphicBufferProducer->getUniqueId(outId);
  1664. }
  1665. int Surface::getConsumerUsage(uint64_t* outUsage) const {
  1666. Mutex::Autolock lock(mMutex);
  1667. return mGraphicBufferProducer->getConsumerUsage(outUsage);
  1668. }
  1669. nsecs_t Surface::getLastDequeueStartTime() const {
  1670. Mutex::Autolock lock(mMutex);
  1671. return mLastDequeueStartTime;
  1672. }
  1673. status_t Surface::getAndFlushRemovedBuffers(std::vector<sp<GraphicBuffer>>* out) {
  1674. if (out == nullptr) {
  1675. ALOGE("%s: out must not be null!", __FUNCTION__);
  1676. return BAD_VALUE;
  1677. }
  1678. Mutex::Autolock lock(mMutex);
  1679. *out = mRemovedBuffers;
  1680. mRemovedBuffers.clear();
  1681. return OK;
  1682. }
  1683. status_t Surface::attachAndQueueBufferWithDataspace(Surface* surface, sp<GraphicBuffer> buffer,
  1684. Dataspace dataspace) {
  1685. if (buffer == nullptr) {
  1686. return BAD_VALUE;
  1687. }
  1688. int err = static_cast<ANativeWindow*>(surface)->perform(surface, NATIVE_WINDOW_API_CONNECT,
  1689. NATIVE_WINDOW_API_CPU);
  1690. if (err != OK) {
  1691. return err;
  1692. }
  1693. ui::Dataspace tmpDataspace = surface->getBuffersDataSpace();
  1694. err = surface->setBuffersDataSpace(dataspace);
  1695. if (err != OK) {
  1696. return err;
  1697. }
  1698. err = surface->attachBuffer(buffer->getNativeBuffer());
  1699. if (err != OK) {
  1700. return err;
  1701. }
  1702. err = static_cast<ANativeWindow*>(surface)->queueBuffer(surface, buffer->getNativeBuffer(), -1);
  1703. if (err != OK) {
  1704. return err;
  1705. }
  1706. err = surface->setBuffersDataSpace(tmpDataspace);
  1707. if (err != OK) {
  1708. return err;
  1709. }
  1710. err = surface->disconnect(NATIVE_WINDOW_API_CPU);
  1711. return err;
  1712. }
  1713. void Surface::ProducerListenerProxy::onBuffersDiscarded(const std::vector<int32_t>& slots) {
  1714. ATRACE_CALL();
  1715. sp<Surface> parent = mParent.promote();
  1716. if (parent == nullptr) {
  1717. return;
  1718. }
  1719. std::vector<sp<GraphicBuffer>> discardedBufs;
  1720. status_t res = parent->getAndFlushBuffersFromSlots(slots, &discardedBufs);
  1721. if (res != OK) {
  1722. ALOGE("%s: Failed to get buffers from slots: %s(%d)", __FUNCTION__,
  1723. strerror(-res), res);
  1724. return;
  1725. }
  1726. mSurfaceListener->onBuffersDiscarded(discardedBufs);
  1727. }
  1728. }; // namespace android