Surface.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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 <android/native_window.h>
  20. #include <binder/Parcel.h>
  21. #include <utils/Log.h>
  22. #include <utils/Trace.h>
  23. #include <utils/NativeHandle.h>
  24. #include <ui/Fence.h>
  25. #include <ui/Region.h>
  26. #include <gui/IProducerListener.h>
  27. #include <gui/ISurfaceComposer.h>
  28. #include <gui/SurfaceComposerClient.h>
  29. #include <gui/GLConsumer.h>
  30. #include <gui/Surface.h>
  31. #include <private/gui/ComposerService.h>
  32. namespace android {
  33. Surface::Surface(
  34. const sp<IGraphicBufferProducer>& bufferProducer,
  35. bool controlledByApp)
  36. : mGraphicBufferProducer(bufferProducer),
  37. mGenerationNumber(0)
  38. {
  39. // Initialize the ANativeWindow function pointers.
  40. ANativeWindow::setSwapInterval = hook_setSwapInterval;
  41. ANativeWindow::dequeueBuffer = hook_dequeueBuffer;
  42. ANativeWindow::cancelBuffer = hook_cancelBuffer;
  43. ANativeWindow::queueBuffer = hook_queueBuffer;
  44. ANativeWindow::query = hook_query;
  45. ANativeWindow::perform = hook_perform;
  46. ANativeWindow::dequeueBuffer_DEPRECATED = hook_dequeueBuffer_DEPRECATED;
  47. ANativeWindow::cancelBuffer_DEPRECATED = hook_cancelBuffer_DEPRECATED;
  48. ANativeWindow::lockBuffer_DEPRECATED = hook_lockBuffer_DEPRECATED;
  49. ANativeWindow::queueBuffer_DEPRECATED = hook_queueBuffer_DEPRECATED;
  50. const_cast<int&>(ANativeWindow::minSwapInterval) = 0;
  51. const_cast<int&>(ANativeWindow::maxSwapInterval) = 1;
  52. mReqWidth = 0;
  53. mReqHeight = 0;
  54. mReqFormat = 0;
  55. mReqUsage = 0;
  56. mTimestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
  57. mDataSpace = HAL_DATASPACE_UNKNOWN;
  58. mCrop.clear();
  59. mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
  60. mTransform = 0;
  61. mStickyTransform = 0;
  62. mDefaultWidth = 0;
  63. mDefaultHeight = 0;
  64. mUserWidth = 0;
  65. mUserHeight = 0;
  66. mTransformHint = 0;
  67. mConsumerRunningBehind = false;
  68. mConnectedToCpu = false;
  69. mProducerControlledByApp = controlledByApp;
  70. mSwapIntervalZero = false;
  71. }
  72. Surface::~Surface() {
  73. if (mConnectedToCpu) {
  74. Surface::disconnect(NATIVE_WINDOW_API_CPU);
  75. }
  76. }
  77. sp<IGraphicBufferProducer> Surface::getIGraphicBufferProducer() const {
  78. return mGraphicBufferProducer;
  79. }
  80. void Surface::setSidebandStream(const sp<NativeHandle>& stream) {
  81. mGraphicBufferProducer->setSidebandStream(stream);
  82. }
  83. void Surface::allocateBuffers() {
  84. uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
  85. uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
  86. mGraphicBufferProducer->allocateBuffers(mSwapIntervalZero, reqWidth,
  87. reqHeight, mReqFormat, mReqUsage);
  88. }
  89. status_t Surface::setGenerationNumber(uint32_t generation) {
  90. status_t result = mGraphicBufferProducer->setGenerationNumber(generation);
  91. if (result == NO_ERROR) {
  92. mGenerationNumber = generation;
  93. }
  94. return result;
  95. }
  96. String8 Surface::getConsumerName() const {
  97. return mGraphicBufferProducer->getConsumerName();
  98. }
  99. int Surface::hook_setSwapInterval(ANativeWindow* window, int interval) {
  100. Surface* c = getSelf(window);
  101. return c->setSwapInterval(interval);
  102. }
  103. int Surface::hook_dequeueBuffer(ANativeWindow* window,
  104. ANativeWindowBuffer** buffer, int* fenceFd) {
  105. Surface* c = getSelf(window);
  106. return c->dequeueBuffer(buffer, fenceFd);
  107. }
  108. int Surface::hook_cancelBuffer(ANativeWindow* window,
  109. ANativeWindowBuffer* buffer, int fenceFd) {
  110. Surface* c = getSelf(window);
  111. return c->cancelBuffer(buffer, fenceFd);
  112. }
  113. int Surface::hook_queueBuffer(ANativeWindow* window,
  114. ANativeWindowBuffer* buffer, int fenceFd) {
  115. Surface* c = getSelf(window);
  116. return c->queueBuffer(buffer, fenceFd);
  117. }
  118. int Surface::hook_dequeueBuffer_DEPRECATED(ANativeWindow* window,
  119. ANativeWindowBuffer** buffer) {
  120. Surface* c = getSelf(window);
  121. ANativeWindowBuffer* buf;
  122. int fenceFd = -1;
  123. int result = c->dequeueBuffer(&buf, &fenceFd);
  124. sp<Fence> fence(new Fence(fenceFd));
  125. int waitResult = fence->waitForever("dequeueBuffer_DEPRECATED");
  126. if (waitResult != OK) {
  127. ALOGE("dequeueBuffer_DEPRECATED: Fence::wait returned an error: %d",
  128. waitResult);
  129. c->cancelBuffer(buf, -1);
  130. return waitResult;
  131. }
  132. *buffer = buf;
  133. return result;
  134. }
  135. int Surface::hook_cancelBuffer_DEPRECATED(ANativeWindow* window,
  136. ANativeWindowBuffer* buffer) {
  137. Surface* c = getSelf(window);
  138. return c->cancelBuffer(buffer, -1);
  139. }
  140. int Surface::hook_lockBuffer_DEPRECATED(ANativeWindow* window,
  141. ANativeWindowBuffer* buffer) {
  142. Surface* c = getSelf(window);
  143. return c->lockBuffer_DEPRECATED(buffer);
  144. }
  145. int Surface::hook_queueBuffer_DEPRECATED(ANativeWindow* window,
  146. ANativeWindowBuffer* buffer) {
  147. Surface* c = getSelf(window);
  148. return c->queueBuffer(buffer, -1);
  149. }
  150. int Surface::hook_query(const ANativeWindow* window,
  151. int what, int* value) {
  152. const Surface* c = getSelf(window);
  153. return c->query(what, value);
  154. }
  155. int Surface::hook_perform(ANativeWindow* window, int operation, ...) {
  156. va_list args;
  157. va_start(args, operation);
  158. Surface* c = getSelf(window);
  159. return c->perform(operation, args);
  160. }
  161. int Surface::setSwapInterval(int interval) {
  162. ATRACE_CALL();
  163. // EGL specification states:
  164. // interval is silently clamped to minimum and maximum implementation
  165. // dependent values before being stored.
  166. if (interval < minSwapInterval)
  167. interval = minSwapInterval;
  168. if (interval > maxSwapInterval)
  169. interval = maxSwapInterval;
  170. mSwapIntervalZero = (interval == 0);
  171. return NO_ERROR;
  172. }
  173. int Surface::dequeueBuffer(android_native_buffer_t** buffer, int* fenceFd) {
  174. ATRACE_CALL();
  175. ALOGV("Surface::dequeueBuffer");
  176. uint32_t reqWidth;
  177. uint32_t reqHeight;
  178. bool swapIntervalZero;
  179. PixelFormat reqFormat;
  180. uint32_t reqUsage;
  181. {
  182. Mutex::Autolock lock(mMutex);
  183. reqWidth = mReqWidth ? mReqWidth : mUserWidth;
  184. reqHeight = mReqHeight ? mReqHeight : mUserHeight;
  185. swapIntervalZero = mSwapIntervalZero;
  186. reqFormat = mReqFormat;
  187. reqUsage = mReqUsage;
  188. } // Drop the lock so that we can still touch the Surface while blocking in IGBP::dequeueBuffer
  189. int buf = -1;
  190. sp<Fence> fence;
  191. status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, swapIntervalZero,
  192. reqWidth, reqHeight, reqFormat, reqUsage);
  193. if (result < 0) {
  194. ALOGV("dequeueBuffer: IGraphicBufferProducer::dequeueBuffer(%d, %d, %d, %d, %d)"
  195. "failed: %d", swapIntervalZero, reqWidth, reqHeight, reqFormat,
  196. reqUsage, result);
  197. return result;
  198. }
  199. if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
  200. ALOGE("dequeueBuffer: IGraphicBufferProducer returned invalid slot number %d", buf);
  201. android_errorWriteLog(0x534e4554, "36991414"); // SafetyNet logging
  202. return FAILED_TRANSACTION;
  203. }
  204. Mutex::Autolock lock(mMutex);
  205. sp<GraphicBuffer>& gbuf(mSlots[buf].buffer);
  206. // this should never happen
  207. ALOGE_IF(fence == NULL, "Surface::dequeueBuffer: received null Fence! buf=%d", buf);
  208. if (result & IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
  209. freeAllBuffers();
  210. }
  211. if ((result & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) || gbuf == 0) {
  212. result = mGraphicBufferProducer->requestBuffer(buf, &gbuf);
  213. if (result != NO_ERROR) {
  214. ALOGE("dequeueBuffer: IGraphicBufferProducer::requestBuffer failed: %d", result);
  215. mGraphicBufferProducer->cancelBuffer(buf, fence);
  216. return result;
  217. }
  218. }
  219. if (fence->isValid()) {
  220. *fenceFd = fence->dup();
  221. if (*fenceFd == -1) {
  222. ALOGE("dequeueBuffer: error duping fence: %d", errno);
  223. // dup() should never fail; something is badly wrong. Soldier on
  224. // and hope for the best; the worst that should happen is some
  225. // visible corruption that lasts until the next frame.
  226. }
  227. } else {
  228. *fenceFd = -1;
  229. }
  230. *buffer = gbuf.get();
  231. return OK;
  232. }
  233. int Surface::cancelBuffer(android_native_buffer_t* buffer,
  234. int fenceFd) {
  235. ATRACE_CALL();
  236. ALOGV("Surface::cancelBuffer");
  237. Mutex::Autolock lock(mMutex);
  238. int i = getSlotFromBufferLocked(buffer);
  239. if (i < 0) {
  240. if (fenceFd >= 0) {
  241. close(fenceFd);
  242. }
  243. return i;
  244. }
  245. sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
  246. mGraphicBufferProducer->cancelBuffer(i, fence);
  247. return OK;
  248. }
  249. int Surface::getSlotFromBufferLocked(
  250. android_native_buffer_t* buffer) const {
  251. for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
  252. if (mSlots[i].buffer != NULL &&
  253. mSlots[i].buffer->handle == buffer->handle) {
  254. return i;
  255. }
  256. }
  257. ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
  258. return BAD_VALUE;
  259. }
  260. int Surface::lockBuffer_DEPRECATED(android_native_buffer_t* buffer __attribute__((unused))) {
  261. ALOGV("Surface::lockBuffer");
  262. Mutex::Autolock lock(mMutex);
  263. return OK;
  264. }
  265. int Surface::queueBuffer(android_native_buffer_t* buffer, int fenceFd) {
  266. ATRACE_CALL();
  267. ALOGV("Surface::queueBuffer");
  268. Mutex::Autolock lock(mMutex);
  269. int64_t timestamp;
  270. bool isAutoTimestamp = false;
  271. if (mTimestamp == NATIVE_WINDOW_TIMESTAMP_AUTO) {
  272. timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
  273. isAutoTimestamp = true;
  274. ALOGV("Surface::queueBuffer making up timestamp: %.2f ms",
  275. timestamp / 1000000.f);
  276. } else {
  277. timestamp = mTimestamp;
  278. }
  279. int i = getSlotFromBufferLocked(buffer);
  280. if (i < 0) {
  281. if (fenceFd >= 0) {
  282. close(fenceFd);
  283. }
  284. return i;
  285. }
  286. // Make sure the crop rectangle is entirely inside the buffer.
  287. Rect crop;
  288. mCrop.intersect(Rect(buffer->width, buffer->height), &crop);
  289. sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
  290. IGraphicBufferProducer::QueueBufferOutput output;
  291. IGraphicBufferProducer::QueueBufferInput input(timestamp, isAutoTimestamp,
  292. mDataSpace, crop, mScalingMode, mTransform ^ mStickyTransform,
  293. mSwapIntervalZero, fence, mStickyTransform);
  294. if (mConnectedToCpu || mDirtyRegion.bounds() == Rect::INVALID_RECT) {
  295. input.setSurfaceDamage(Region::INVALID_REGION);
  296. } else {
  297. // Here we do two things:
  298. // 1) The surface damage was specified using the OpenGL ES convention of
  299. // the origin being in the bottom-left corner. Here we flip to the
  300. // convention that the rest of the system uses (top-left corner) by
  301. // subtracting all top/bottom coordinates from the buffer height.
  302. // 2) If the buffer is coming in rotated (for example, because the EGL
  303. // implementation is reacting to the transform hint coming back from
  304. // SurfaceFlinger), the surface damage needs to be rotated the
  305. // opposite direction, since it was generated assuming an unrotated
  306. // buffer (the app doesn't know that the EGL implementation is
  307. // reacting to the transform hint behind its back). The
  308. // transformations in the switch statement below apply those
  309. // complementary rotations (e.g., if 90 degrees, rotate 270 degrees).
  310. int width = buffer->width;
  311. int height = buffer->height;
  312. bool rotated90 = (mTransform ^ mStickyTransform) &
  313. NATIVE_WINDOW_TRANSFORM_ROT_90;
  314. if (rotated90) {
  315. std::swap(width, height);
  316. }
  317. Region flippedRegion;
  318. for (auto rect : mDirtyRegion) {
  319. int left = rect.left;
  320. int right = rect.right;
  321. int top = height - rect.bottom; // Flip from OpenGL convention
  322. int bottom = height - rect.top; // Flip from OpenGL convention
  323. switch (mTransform ^ mStickyTransform) {
  324. case NATIVE_WINDOW_TRANSFORM_ROT_90: {
  325. // Rotate 270 degrees
  326. Rect flippedRect{top, width - right, bottom, width - left};
  327. flippedRegion.orSelf(flippedRect);
  328. break;
  329. }
  330. case NATIVE_WINDOW_TRANSFORM_ROT_180: {
  331. // Rotate 180 degrees
  332. Rect flippedRect{width - right, height - bottom,
  333. width - left, height - top};
  334. flippedRegion.orSelf(flippedRect);
  335. break;
  336. }
  337. case NATIVE_WINDOW_TRANSFORM_ROT_270: {
  338. // Rotate 90 degrees
  339. Rect flippedRect{height - bottom, left,
  340. height - top, right};
  341. flippedRegion.orSelf(flippedRect);
  342. break;
  343. }
  344. default: {
  345. Rect flippedRect{left, top, right, bottom};
  346. flippedRegion.orSelf(flippedRect);
  347. break;
  348. }
  349. }
  350. }
  351. input.setSurfaceDamage(flippedRegion);
  352. }
  353. status_t err = mGraphicBufferProducer->queueBuffer(i, input, &output);
  354. if (err != OK) {
  355. ALOGE("queueBuffer: error queuing buffer to SurfaceTexture, %d", err);
  356. }
  357. uint32_t numPendingBuffers = 0;
  358. uint32_t hint = 0;
  359. output.deflate(&mDefaultWidth, &mDefaultHeight, &hint,
  360. &numPendingBuffers);
  361. // Disable transform hint if sticky transform is set.
  362. if (mStickyTransform == 0) {
  363. mTransformHint = hint;
  364. }
  365. mConsumerRunningBehind = (numPendingBuffers >= 2);
  366. if (!mConnectedToCpu) {
  367. // Clear surface damage back to full-buffer
  368. mDirtyRegion = Region::INVALID_REGION;
  369. }
  370. return err;
  371. }
  372. int Surface::query(int what, int* value) const {
  373. ATRACE_CALL();
  374. ALOGV("Surface::query");
  375. { // scope for the lock
  376. Mutex::Autolock lock(mMutex);
  377. switch (what) {
  378. case NATIVE_WINDOW_FORMAT:
  379. if (mReqFormat) {
  380. *value = static_cast<int>(mReqFormat);
  381. return NO_ERROR;
  382. }
  383. break;
  384. case NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER: {
  385. sp<ISurfaceComposer> composer(
  386. ComposerService::getComposerService());
  387. if (composer->authenticateSurfaceTexture(mGraphicBufferProducer)) {
  388. *value = 1;
  389. } else {
  390. *value = 0;
  391. }
  392. return NO_ERROR;
  393. }
  394. case NATIVE_WINDOW_CONCRETE_TYPE:
  395. *value = NATIVE_WINDOW_SURFACE;
  396. return NO_ERROR;
  397. case NATIVE_WINDOW_DEFAULT_WIDTH:
  398. *value = static_cast<int>(
  399. mUserWidth ? mUserWidth : mDefaultWidth);
  400. return NO_ERROR;
  401. case NATIVE_WINDOW_DEFAULT_HEIGHT:
  402. *value = static_cast<int>(
  403. mUserHeight ? mUserHeight : mDefaultHeight);
  404. return NO_ERROR;
  405. case NATIVE_WINDOW_TRANSFORM_HINT:
  406. *value = static_cast<int>(mTransformHint);
  407. return NO_ERROR;
  408. case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: {
  409. status_t err = NO_ERROR;
  410. if (!mConsumerRunningBehind) {
  411. *value = 0;
  412. } else {
  413. err = mGraphicBufferProducer->query(what, value);
  414. if (err == NO_ERROR) {
  415. mConsumerRunningBehind = *value;
  416. }
  417. }
  418. return err;
  419. }
  420. }
  421. }
  422. return mGraphicBufferProducer->query(what, value);
  423. }
  424. int Surface::perform(int operation, va_list args)
  425. {
  426. int res = NO_ERROR;
  427. switch (operation) {
  428. case NATIVE_WINDOW_CONNECT:
  429. // deprecated. must return NO_ERROR.
  430. break;
  431. case NATIVE_WINDOW_DISCONNECT:
  432. // deprecated. must return NO_ERROR.
  433. break;
  434. case NATIVE_WINDOW_SET_USAGE:
  435. res = dispatchSetUsage(args);
  436. break;
  437. case NATIVE_WINDOW_SET_CROP:
  438. res = dispatchSetCrop(args);
  439. break;
  440. case NATIVE_WINDOW_SET_BUFFER_COUNT:
  441. res = dispatchSetBufferCount(args);
  442. break;
  443. case NATIVE_WINDOW_SET_BUFFERS_GEOMETRY:
  444. res = dispatchSetBuffersGeometry(args);
  445. break;
  446. case NATIVE_WINDOW_SET_BUFFERS_TRANSFORM:
  447. res = dispatchSetBuffersTransform(args);
  448. break;
  449. case NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM:
  450. res = dispatchSetBuffersStickyTransform(args);
  451. break;
  452. case NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP:
  453. res = dispatchSetBuffersTimestamp(args);
  454. break;
  455. case NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS:
  456. res = dispatchSetBuffersDimensions(args);
  457. break;
  458. case NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS:
  459. res = dispatchSetBuffersUserDimensions(args);
  460. break;
  461. case NATIVE_WINDOW_SET_BUFFERS_FORMAT:
  462. res = dispatchSetBuffersFormat(args);
  463. break;
  464. case NATIVE_WINDOW_LOCK:
  465. res = dispatchLock(args);
  466. break;
  467. case NATIVE_WINDOW_UNLOCK_AND_POST:
  468. res = dispatchUnlockAndPost(args);
  469. break;
  470. case NATIVE_WINDOW_SET_SCALING_MODE:
  471. res = dispatchSetScalingMode(args);
  472. break;
  473. case NATIVE_WINDOW_API_CONNECT:
  474. res = dispatchConnect(args);
  475. break;
  476. case NATIVE_WINDOW_API_DISCONNECT:
  477. res = dispatchDisconnect(args);
  478. break;
  479. case NATIVE_WINDOW_SET_SIDEBAND_STREAM:
  480. res = dispatchSetSidebandStream(args);
  481. break;
  482. case NATIVE_WINDOW_SET_BUFFERS_DATASPACE:
  483. res = dispatchSetBuffersDataSpace(args);
  484. break;
  485. case NATIVE_WINDOW_SET_SURFACE_DAMAGE:
  486. res = dispatchSetSurfaceDamage(args);
  487. break;
  488. default:
  489. res = NAME_NOT_FOUND;
  490. break;
  491. }
  492. return res;
  493. }
  494. int Surface::dispatchConnect(va_list args) {
  495. int api = va_arg(args, int);
  496. return connect(api);
  497. }
  498. int Surface::dispatchDisconnect(va_list args) {
  499. int api = va_arg(args, int);
  500. return disconnect(api);
  501. }
  502. int Surface::dispatchSetUsage(va_list args) {
  503. int usage = va_arg(args, int);
  504. return setUsage(static_cast<uint32_t>(usage));
  505. }
  506. int Surface::dispatchSetCrop(va_list args) {
  507. android_native_rect_t const* rect = va_arg(args, android_native_rect_t*);
  508. return setCrop(reinterpret_cast<Rect const*>(rect));
  509. }
  510. int Surface::dispatchSetBufferCount(va_list args) {
  511. size_t bufferCount = va_arg(args, size_t);
  512. return setBufferCount(static_cast<int32_t>(bufferCount));
  513. }
  514. int Surface::dispatchSetBuffersGeometry(va_list args) {
  515. uint32_t width = va_arg(args, uint32_t);
  516. uint32_t height = va_arg(args, uint32_t);
  517. PixelFormat format = va_arg(args, PixelFormat);
  518. int err = setBuffersDimensions(width, height);
  519. if (err != 0) {
  520. return err;
  521. }
  522. return setBuffersFormat(format);
  523. }
  524. int Surface::dispatchSetBuffersDimensions(va_list args) {
  525. uint32_t width = va_arg(args, uint32_t);
  526. uint32_t height = va_arg(args, uint32_t);
  527. return setBuffersDimensions(width, height);
  528. }
  529. int Surface::dispatchSetBuffersUserDimensions(va_list args) {
  530. uint32_t width = va_arg(args, uint32_t);
  531. uint32_t height = va_arg(args, uint32_t);
  532. return setBuffersUserDimensions(width, height);
  533. }
  534. int Surface::dispatchSetBuffersFormat(va_list args) {
  535. PixelFormat format = va_arg(args, PixelFormat);
  536. return setBuffersFormat(format);
  537. }
  538. int Surface::dispatchSetScalingMode(va_list args) {
  539. int mode = va_arg(args, int);
  540. return setScalingMode(mode);
  541. }
  542. int Surface::dispatchSetBuffersTransform(va_list args) {
  543. uint32_t transform = va_arg(args, uint32_t);
  544. return setBuffersTransform(transform);
  545. }
  546. int Surface::dispatchSetBuffersStickyTransform(va_list args) {
  547. uint32_t transform = va_arg(args, uint32_t);
  548. return setBuffersStickyTransform(transform);
  549. }
  550. int Surface::dispatchSetBuffersTimestamp(va_list args) {
  551. int64_t timestamp = va_arg(args, int64_t);
  552. return setBuffersTimestamp(timestamp);
  553. }
  554. int Surface::dispatchLock(va_list args) {
  555. ANativeWindow_Buffer* outBuffer = va_arg(args, ANativeWindow_Buffer*);
  556. ARect* inOutDirtyBounds = va_arg(args, ARect*);
  557. return lock(outBuffer, inOutDirtyBounds);
  558. }
  559. int Surface::dispatchUnlockAndPost(va_list args __attribute__((unused))) {
  560. return unlockAndPost();
  561. }
  562. int Surface::dispatchSetSidebandStream(va_list args) {
  563. native_handle_t* sH = va_arg(args, native_handle_t*);
  564. sp<NativeHandle> sidebandHandle = NativeHandle::create(sH, false);
  565. setSidebandStream(sidebandHandle);
  566. return OK;
  567. }
  568. int Surface::dispatchSetBuffersDataSpace(va_list args) {
  569. android_dataspace dataspace =
  570. static_cast<android_dataspace>(va_arg(args, int));
  571. return setBuffersDataSpace(dataspace);
  572. }
  573. int Surface::dispatchSetSurfaceDamage(va_list args) {
  574. android_native_rect_t* rects = va_arg(args, android_native_rect_t*);
  575. size_t numRects = va_arg(args, size_t);
  576. setSurfaceDamage(rects, numRects);
  577. return NO_ERROR;
  578. }
  579. int Surface::connect(int api) {
  580. static sp<IProducerListener> listener = new DummyProducerListener();
  581. return connect(api, listener);
  582. }
  583. int Surface::connect(int api, const sp<IProducerListener>& listener) {
  584. ATRACE_CALL();
  585. ALOGV("Surface::connect");
  586. Mutex::Autolock lock(mMutex);
  587. IGraphicBufferProducer::QueueBufferOutput output;
  588. int err = mGraphicBufferProducer->connect(listener, api, mProducerControlledByApp, &output);
  589. if (err == NO_ERROR) {
  590. uint32_t numPendingBuffers = 0;
  591. uint32_t hint = 0;
  592. output.deflate(&mDefaultWidth, &mDefaultHeight, &hint,
  593. &numPendingBuffers);
  594. // Disable transform hint if sticky transform is set.
  595. if (mStickyTransform == 0) {
  596. mTransformHint = hint;
  597. }
  598. mConsumerRunningBehind = (numPendingBuffers >= 2);
  599. }
  600. if (!err && api == NATIVE_WINDOW_API_CPU) {
  601. mConnectedToCpu = true;
  602. // Clear the dirty region in case we're switching from a non-CPU API
  603. mDirtyRegion.clear();
  604. } else if (!err) {
  605. // Initialize the dirty region for tracking surface damage
  606. mDirtyRegion = Region::INVALID_REGION;
  607. }
  608. return err;
  609. }
  610. int Surface::disconnect(int api) {
  611. ATRACE_CALL();
  612. ALOGV("Surface::disconnect");
  613. Mutex::Autolock lock(mMutex);
  614. freeAllBuffers();
  615. int err = mGraphicBufferProducer->disconnect(api);
  616. if (!err) {
  617. mReqFormat = 0;
  618. mReqWidth = 0;
  619. mReqHeight = 0;
  620. mReqUsage = 0;
  621. mCrop.clear();
  622. mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
  623. mTransform = 0;
  624. mStickyTransform = 0;
  625. if (api == NATIVE_WINDOW_API_CPU) {
  626. mConnectedToCpu = false;
  627. }
  628. }
  629. return err;
  630. }
  631. int Surface::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
  632. sp<Fence>* outFence) {
  633. ATRACE_CALL();
  634. ALOGV("Surface::detachNextBuffer");
  635. if (outBuffer == NULL || outFence == NULL) {
  636. return BAD_VALUE;
  637. }
  638. Mutex::Autolock lock(mMutex);
  639. sp<GraphicBuffer> buffer(NULL);
  640. sp<Fence> fence(NULL);
  641. status_t result = mGraphicBufferProducer->detachNextBuffer(
  642. &buffer, &fence);
  643. if (result != NO_ERROR) {
  644. return result;
  645. }
  646. *outBuffer = buffer;
  647. if (fence != NULL && fence->isValid()) {
  648. *outFence = fence;
  649. } else {
  650. *outFence = Fence::NO_FENCE;
  651. }
  652. return NO_ERROR;
  653. }
  654. int Surface::attachBuffer(ANativeWindowBuffer* buffer)
  655. {
  656. ATRACE_CALL();
  657. ALOGV("Surface::attachBuffer");
  658. Mutex::Autolock lock(mMutex);
  659. sp<GraphicBuffer> graphicBuffer(static_cast<GraphicBuffer*>(buffer));
  660. uint32_t priorGeneration = graphicBuffer->mGenerationNumber;
  661. graphicBuffer->mGenerationNumber = mGenerationNumber;
  662. int32_t attachedSlot = -1;
  663. status_t result = mGraphicBufferProducer->attachBuffer(
  664. &attachedSlot, graphicBuffer);
  665. if (result != NO_ERROR) {
  666. ALOGE("attachBuffer: IGraphicBufferProducer call failed (%d)", result);
  667. graphicBuffer->mGenerationNumber = priorGeneration;
  668. return result;
  669. }
  670. mSlots[attachedSlot].buffer = graphicBuffer;
  671. return NO_ERROR;
  672. }
  673. int Surface::setUsage(uint32_t reqUsage)
  674. {
  675. ALOGV("Surface::setUsage");
  676. Mutex::Autolock lock(mMutex);
  677. mReqUsage = reqUsage;
  678. return OK;
  679. }
  680. int Surface::setCrop(Rect const* rect)
  681. {
  682. ATRACE_CALL();
  683. Rect realRect;
  684. if (rect == NULL || rect->isEmpty()) {
  685. realRect.clear();
  686. } else {
  687. realRect = *rect;
  688. }
  689. ALOGV("Surface::setCrop rect=[%d %d %d %d]",
  690. realRect.left, realRect.top, realRect.right, realRect.bottom);
  691. Mutex::Autolock lock(mMutex);
  692. mCrop = realRect;
  693. return NO_ERROR;
  694. }
  695. int Surface::setBufferCount(int bufferCount)
  696. {
  697. ATRACE_CALL();
  698. ALOGV("Surface::setBufferCount");
  699. Mutex::Autolock lock(mMutex);
  700. status_t err = mGraphicBufferProducer->setBufferCount(bufferCount);
  701. ALOGE_IF(err, "IGraphicBufferProducer::setBufferCount(%d) returned %s",
  702. bufferCount, strerror(-err));
  703. if (err == NO_ERROR) {
  704. freeAllBuffers();
  705. }
  706. return err;
  707. }
  708. int Surface::setBuffersDimensions(uint32_t width, uint32_t height)
  709. {
  710. ATRACE_CALL();
  711. ALOGV("Surface::setBuffersDimensions");
  712. if ((width && !height) || (!width && height))
  713. return BAD_VALUE;
  714. Mutex::Autolock lock(mMutex);
  715. mReqWidth = width;
  716. mReqHeight = height;
  717. return NO_ERROR;
  718. }
  719. int Surface::setBuffersUserDimensions(uint32_t width, uint32_t height)
  720. {
  721. ATRACE_CALL();
  722. ALOGV("Surface::setBuffersUserDimensions");
  723. if ((width && !height) || (!width && height))
  724. return BAD_VALUE;
  725. Mutex::Autolock lock(mMutex);
  726. mUserWidth = width;
  727. mUserHeight = height;
  728. return NO_ERROR;
  729. }
  730. int Surface::setBuffersFormat(PixelFormat format)
  731. {
  732. ALOGV("Surface::setBuffersFormat");
  733. Mutex::Autolock lock(mMutex);
  734. mReqFormat = format;
  735. return NO_ERROR;
  736. }
  737. int Surface::setScalingMode(int mode)
  738. {
  739. ATRACE_CALL();
  740. ALOGV("Surface::setScalingMode(%d)", mode);
  741. switch (mode) {
  742. case NATIVE_WINDOW_SCALING_MODE_FREEZE:
  743. case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
  744. case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
  745. break;
  746. default:
  747. ALOGE("unknown scaling mode: %d", mode);
  748. return BAD_VALUE;
  749. }
  750. Mutex::Autolock lock(mMutex);
  751. mScalingMode = mode;
  752. return NO_ERROR;
  753. }
  754. int Surface::setBuffersTransform(uint32_t transform)
  755. {
  756. ATRACE_CALL();
  757. ALOGV("Surface::setBuffersTransform");
  758. Mutex::Autolock lock(mMutex);
  759. mTransform = transform;
  760. return NO_ERROR;
  761. }
  762. int Surface::setBuffersStickyTransform(uint32_t transform)
  763. {
  764. ATRACE_CALL();
  765. ALOGV("Surface::setBuffersStickyTransform");
  766. Mutex::Autolock lock(mMutex);
  767. mStickyTransform = transform;
  768. return NO_ERROR;
  769. }
  770. int Surface::setBuffersTimestamp(int64_t timestamp)
  771. {
  772. ALOGV("Surface::setBuffersTimestamp");
  773. Mutex::Autolock lock(mMutex);
  774. mTimestamp = timestamp;
  775. return NO_ERROR;
  776. }
  777. int Surface::setBuffersDataSpace(android_dataspace dataSpace)
  778. {
  779. ALOGV("Surface::setBuffersDataSpace");
  780. Mutex::Autolock lock(mMutex);
  781. mDataSpace = dataSpace;
  782. return NO_ERROR;
  783. }
  784. void Surface::freeAllBuffers() {
  785. for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
  786. mSlots[i].buffer = 0;
  787. }
  788. }
  789. void Surface::setSurfaceDamage(android_native_rect_t* rects, size_t numRects) {
  790. ATRACE_CALL();
  791. ALOGV("Surface::setSurfaceDamage");
  792. Mutex::Autolock lock(mMutex);
  793. if (mConnectedToCpu || numRects == 0) {
  794. mDirtyRegion = Region::INVALID_REGION;
  795. return;
  796. }
  797. mDirtyRegion.clear();
  798. for (size_t r = 0; r < numRects; ++r) {
  799. // We intentionally flip top and bottom here, since because they're
  800. // specified with a bottom-left origin, top > bottom, which fails
  801. // validation in the Region class. We will fix this up when we flip to a
  802. // top-left origin in queueBuffer.
  803. Rect rect(rects[r].left, rects[r].bottom, rects[r].right, rects[r].top);
  804. mDirtyRegion.orSelf(rect);
  805. }
  806. }
  807. // ----------------------------------------------------------------------
  808. // the lock/unlock APIs must be used from the same thread
  809. static status_t copyBlt(
  810. const sp<GraphicBuffer>& dst,
  811. const sp<GraphicBuffer>& src,
  812. const Region& reg)
  813. {
  814. // src and dst with, height and format must be identical. no verification
  815. // is done here.
  816. status_t err;
  817. uint8_t* src_bits = NULL;
  818. err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(),
  819. reinterpret_cast<void**>(&src_bits));
  820. ALOGE_IF(err, "error locking src buffer %s", strerror(-err));
  821. uint8_t* dst_bits = NULL;
  822. err = dst->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(),
  823. reinterpret_cast<void**>(&dst_bits));
  824. ALOGE_IF(err, "error locking dst buffer %s", strerror(-err));
  825. Region::const_iterator head(reg.begin());
  826. Region::const_iterator tail(reg.end());
  827. if (head != tail && src_bits && dst_bits) {
  828. const size_t bpp = bytesPerPixel(src->format);
  829. const size_t dbpr = static_cast<uint32_t>(dst->stride) * bpp;
  830. const size_t sbpr = static_cast<uint32_t>(src->stride) * bpp;
  831. while (head != tail) {
  832. const Rect& r(*head++);
  833. int32_t h = r.height();
  834. if (h <= 0) continue;
  835. size_t size = static_cast<uint32_t>(r.width()) * bpp;
  836. uint8_t const * s = src_bits +
  837. static_cast<uint32_t>(r.left + src->stride * r.top) * bpp;
  838. uint8_t * d = dst_bits +
  839. static_cast<uint32_t>(r.left + dst->stride * r.top) * bpp;
  840. if (dbpr==sbpr && size==sbpr) {
  841. size *= static_cast<size_t>(h);
  842. h = 1;
  843. }
  844. do {
  845. memcpy(d, s, size);
  846. d += dbpr;
  847. s += sbpr;
  848. } while (--h > 0);
  849. }
  850. }
  851. if (src_bits)
  852. src->unlock();
  853. if (dst_bits)
  854. dst->unlock();
  855. return err;
  856. }
  857. // ----------------------------------------------------------------------------
  858. status_t Surface::lock(
  859. ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds)
  860. {
  861. if (mLockedBuffer != 0) {
  862. ALOGE("Surface::lock failed, already locked");
  863. return INVALID_OPERATION;
  864. }
  865. if (!mConnectedToCpu) {
  866. int err = Surface::connect(NATIVE_WINDOW_API_CPU);
  867. if (err) {
  868. return err;
  869. }
  870. // we're intending to do software rendering from this point
  871. setUsage(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
  872. }
  873. ANativeWindowBuffer* out;
  874. int fenceFd = -1;
  875. status_t err = dequeueBuffer(&out, &fenceFd);
  876. ALOGE_IF(err, "dequeueBuffer failed (%s)", strerror(-err));
  877. if (err == NO_ERROR) {
  878. sp<GraphicBuffer> backBuffer(GraphicBuffer::getSelf(out));
  879. const Rect bounds(backBuffer->width, backBuffer->height);
  880. Region newDirtyRegion;
  881. if (inOutDirtyBounds) {
  882. newDirtyRegion.set(static_cast<Rect const&>(*inOutDirtyBounds));
  883. newDirtyRegion.andSelf(bounds);
  884. } else {
  885. newDirtyRegion.set(bounds);
  886. }
  887. // figure out if we can copy the frontbuffer back
  888. int backBufferSlot(getSlotFromBufferLocked(backBuffer.get()));
  889. const sp<GraphicBuffer>& frontBuffer(mPostedBuffer);
  890. const bool canCopyBack = (frontBuffer != 0 &&
  891. backBuffer->width == frontBuffer->width &&
  892. backBuffer->height == frontBuffer->height &&
  893. backBuffer->format == frontBuffer->format);
  894. if (canCopyBack) {
  895. Mutex::Autolock lock(mMutex);
  896. Region oldDirtyRegion;
  897. if(mSlots[backBufferSlot].dirtyRegion.isEmpty()) {
  898. oldDirtyRegion.set(bounds);
  899. } else {
  900. for(int i = 0 ; i < NUM_BUFFER_SLOTS; i++ ) {
  901. if(i != backBufferSlot && !mSlots[i].dirtyRegion.isEmpty())
  902. oldDirtyRegion.orSelf(mSlots[i].dirtyRegion);
  903. }
  904. }
  905. const Region copyback(oldDirtyRegion.subtract(newDirtyRegion));
  906. if (!copyback.isEmpty())
  907. copyBlt(backBuffer, frontBuffer, copyback);
  908. } else {
  909. // if we can't copy-back anything, modify the user's dirty
  910. // region to make sure they redraw the whole buffer
  911. newDirtyRegion.set(bounds);
  912. Mutex::Autolock lock(mMutex);
  913. for (size_t i=0 ; i<NUM_BUFFER_SLOTS ; i++) {
  914. mSlots[i].dirtyRegion.clear();
  915. }
  916. }
  917. { // scope for the lock
  918. Mutex::Autolock lock(mMutex);
  919. mSlots[backBufferSlot].dirtyRegion = newDirtyRegion;
  920. }
  921. if (inOutDirtyBounds) {
  922. *inOutDirtyBounds = newDirtyRegion.getBounds();
  923. }
  924. void* vaddr;
  925. status_t res = backBuffer->lockAsync(
  926. GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
  927. newDirtyRegion.bounds(), &vaddr, fenceFd);
  928. ALOGW_IF(res, "failed locking buffer (handle = %p)",
  929. backBuffer->handle);
  930. if (res != 0) {
  931. err = INVALID_OPERATION;
  932. } else {
  933. mLockedBuffer = backBuffer;
  934. outBuffer->width = backBuffer->width;
  935. outBuffer->height = backBuffer->height;
  936. outBuffer->stride = backBuffer->stride;
  937. outBuffer->format = backBuffer->format;
  938. outBuffer->bits = vaddr;
  939. }
  940. }
  941. return err;
  942. }
  943. status_t Surface::unlockAndPost()
  944. {
  945. if (mLockedBuffer == 0) {
  946. ALOGE("Surface::unlockAndPost failed, no locked buffer");
  947. return INVALID_OPERATION;
  948. }
  949. int fd = -1;
  950. status_t err = mLockedBuffer->unlockAsync(&fd);
  951. ALOGE_IF(err, "failed unlocking buffer (%p)", mLockedBuffer->handle);
  952. err = queueBuffer(mLockedBuffer.get(), fd);
  953. ALOGE_IF(err, "queueBuffer (handle=%p) failed (%s)",
  954. mLockedBuffer->handle, strerror(-err));
  955. mPostedBuffer = mLockedBuffer;
  956. mLockedBuffer = 0;
  957. return err;
  958. }
  959. }; // namespace android