当前位置:   article > 正文

Android13 SurfaceFlinger composite(合成)流程分析_surfaceflinger::composite

surfaceflinger::composite

SurfaceFlinger的composite方法,用于将多个窗口的图像进行合成,主要负责对相关要进行上帧的layer进行,识别排序好,然后合成,有hwc合成的会构建对应OutputLayer传递hwc,GPU合成则直接合成,再传递到hwc中,它主要完成以下几个步骤:

  1. 从队列中获取所有待合成的缓冲区。

  2. 将这些缓冲区按照一定的顺序进行合成,生成最终的图像。

  3. 将合成后的图像提交给HWC进行显示。

SurfaceFlinger的composite方法代码如下:

  1. //frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
  2. std::unique_ptr<compositionengine::CompositionEngine> mCompositionEngine;
  3. void SurfaceFlinger::composite(nsecs_t frameTime, int64_t vsyncId)
  4. FTL_FAKE_GUARD(kMainThreadContext) {
  5. ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
  6. if (mPowerHintSessionData.sessionEnabled) {
  7. mPowerHintSessionData.compositeStart = systemTime();
  8. }
  9. compositionengine::CompositionRefreshArgs refreshArgs;
  10. const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
  11. refreshArgs.outputs.reserve(displays.size());
  12. for (const auto& [_, display] : displays) {
  13. refreshArgs.outputs.push_back(display->getCompositionDisplay());
  14. }
  15. mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
  16. if (auto layerFE = layer->getCompositionEngineLayerFE())
  17. refreshArgs.layers.push_back(layerFE);
  18. });
  19. refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
  20. for (auto layer : mLayersWithQueuedFrames) {
  21. if (auto layerFE = layer->getCompositionEngineLayerFE())
  22. refreshArgs.layersWithQueuedFrames.push_back(layerFE);
  23. }
  24. refreshArgs.outputColorSetting = useColorManagement
  25. ? mDisplayColorSetting
  26. : compositionengine::OutputColorSetting::kUnmanaged;
  27. refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
  28. refreshArgs.forceOutputColorMode = mForceColorMode;
  29. refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
  30. refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
  31. refreshArgs.blursAreExpensive = mBlursAreExpensive;
  32. refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
  33. if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
  34. refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
  35. mDrawingState.colorMatrixChanged = false;
  36. }
  37. refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
  38. if (mDebugFlashDelay != 0) {
  39. refreshArgs.devOptForceClientComposition = true;
  40. refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
  41. }
  42. const auto expectedPresentTime = mExpectedPresentTime.load();
  43. const auto prevVsyncTime = mScheduler->getPreviousVsyncFrom(expectedPresentTime);
  44. const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
  45. refreshArgs.earliestPresentTime = prevVsyncTime - hwcMinWorkDuration;
  46. refreshArgs.previousPresentFence = mPreviousPresentFences[0].fenceTime;
  47. refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
  48. refreshArgs.expectedPresentTime = expectedPresentTime;
  49. // Store the present time just before calling to the composition engine so we could notify
  50. // the scheduler.
  51. const auto presentTime = systemTime();
  52. mCompositionEngine->present(refreshArgs);
  53. if (mPowerHintSessionData.sessionEnabled) {
  54. mPowerHintSessionData.presentEnd = systemTime();
  55. }
  56. mTimeStats->recordFrameDuration(frameTime, systemTime());
  57. if (mScheduler->onPostComposition(presentTime)) {
  58. scheduleComposite(FrameHint::kNone);
  59. }
  60. postFrame();
  61. postComposition();
  62. const bool prevFrameHadClientComposition = mHadClientComposition;
  63. mHadClientComposition = mHadDeviceComposition = mReusedClientComposition = false;
  64. TimeStats::ClientCompositionRecord clientCompositionRecord;
  65. for (const auto& [_, display] : displays) {
  66. const auto& state = display->getCompositionDisplay()->getState();
  67. mHadClientComposition |= state.usesClientComposition && !state.reusedClientComposition;
  68. mHadDeviceComposition |= state.usesDeviceComposition;
  69. mReusedClientComposition |= state.reusedClientComposition;
  70. clientCompositionRecord.predicted |=
  71. (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
  72. clientCompositionRecord.predictionSucceeded |=
  73. (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
  74. }
  75. clientCompositionRecord.hadClientComposition = mHadClientComposition;
  76. clientCompositionRecord.reused = mReusedClientComposition;
  77. clientCompositionRecord.changed = prevFrameHadClientComposition != mHadClientComposition;
  78. mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
  79. // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
  80. const bool usedGpuComposition = mHadClientComposition || mReusedClientComposition;
  81. modulateVsync(&VsyncModulator::onDisplayRefresh, usedGpuComposition);
  82. mLayersWithQueuedFrames.clear();
  83. if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
  84. // This will block and should only be used for debugging.
  85. mLayerTracing.notify(mVisibleRegionsDirty, frameTime);
  86. }
  87. mVisibleRegionsWereDirtyThisFrame = mVisibleRegionsDirty; // Cache value for use in post-comp
  88. mVisibleRegionsDirty = false;
  89. if (mCompositionEngine->needsAnotherUpdate()) {
  90. scheduleCommit(FrameHint::kNone);
  91. }
  92. // calculate total render time for performance hinting if adpf cpu hint is enabled,
  93. if (mPowerHintSessionData.sessionEnabled) {
  94. const nsecs_t flingerDuration =
  95. (mPowerHintSessionData.presentEnd - mPowerHintSessionData.commitStart);
  96. mPowerAdvisor->sendActualWorkDuration(flingerDuration, mPowerHintSessionData.presentEnd);
  97. }
  98. }

调用CompositionEngine的present,开始真正的Layer合成:

  1. //frameworks/native/services/surfaceflinger/CompositionEngine/src/CompositionEngine.cpp
  2. void CompositionEngine::present(CompositionRefreshArgs& args) {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. preComposition(args);
  6. {
  7. // latchedLayers is used to track the set of front-end layer state that
  8. // has been latched across all outputs for the prepare step, and is not
  9. // needed for anything else.
  10. LayerFESet latchedLayers;
  11. for (const auto& output : args.outputs) {
  12. output->prepare(args, latchedLayers);
  13. }
  14. }
  15. updateLayerStateFromFE(args);
  16. for (const auto& output : args.outputs) {
  17. output->present(args);
  18. }
  19. }

上面方面主要处理如下:

1、调用CompositionEngine的preComposition方法,进行layer预合成。

2、调用Output的prepare方法,进行预合成。

3、调用Output的present方法,进行Layer合成。

下面分别进行分析:

CompositionEngine preComposition

调用CompositionEngine的preComposition方法,进行合成前预处理:

  1. //frameworks/native/services/surfaceflinger/CompositionEngine/src/CompositionEngine.cpp
  2. void CompositionEngine::preComposition(CompositionRefreshArgs& args) {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. bool needsAnotherUpdate = false;
  6. mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
  7. //遍历所有layer,进行layer预合成
  8. for (auto& layer : args.layers) {
  9. if (layer->onPreComposition(mRefreshStartTime)) {
  10. needsAnotherUpdate = true;
  11. }
  12. }
  13. mNeedsAnotherUpdate = needsAnotherUpdate;
  14. }

BufferLayer onPreComposition

调用Layer的onPreComposition方法,BufferLayer继承于Layer:

  1. //frameworks/native/services/surfaceflinger/BufferLayer.cpp
  2. bool BufferLayer::onPreComposition(nsecs_t) {
  3. return hasReadyFrame();
  4. }

调用BufferLayer的hasReadyFrame方法:

  1. //frameworks/native/services/surfaceflinger/BufferLayer.cpp
  2. bool BufferLayer::hasReadyFrame() const {
  3. return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
  4. }

Output prepare

调用Output的prepare方法,进行预合成:

  1. /frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::prepare(const compositionengine::CompositionRefreshArgs& refreshArgs,
  3. LayerFESet& geomSnapshots) {
  4. ATRACE_CALL();
  5. ALOGV(__FUNCTION__);
  6. rebuildLayerStacks(refreshArgs, geomSnapshots); //Output实际上就是display, 通过调用每个Display的rebuildLayerStacks ,建立display 的 LayerStacks.
  7. }

Output rebuildLayerStacks

调用Output的rebuildLayerStacks方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::rebuildLayerStacks(const compositionengine::CompositionRefreshArgs& refreshArgs,
  3. LayerFESet& layerFESet) {
  4. ATRACE_CALL();
  5. ALOGV(__FUNCTION__);
  6. auto& outputState = editState();
  7. // Do nothing if this output is not enabled or there is no need to perform this update
  8. if (!outputState.isEnabled || CC_LIKELY(!refreshArgs.updatingOutputGeometryThisFrame)) {
  9. return;
  10. }
  11. // Process the layers to determine visibility and coverage
  12. compositionengine::Output::CoverageState coverage{layerFESet};
  13. collectVisibleLayers(refreshArgs, coverage);
  14. // Compute the resulting coverage for this output, and store it for later
  15. const ui::Transform& tr = outputState.transform;
  16. Region undefinedRegion{outputState.displaySpace.getBoundsAsRect()};
  17. undefinedRegion.subtractSelf(tr.transform(coverage.aboveOpaqueLayers));
  18. outputState.undefinedRegion = undefinedRegion;
  19. outputState.dirtyRegion.orSelf(coverage.dirtyRegion);
  20. }

Output present

调用Output的present方法,进行Layer合成。

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::present(const compositionengine::CompositionRefreshArgs& refreshArgs) {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. updateColorProfile(refreshArgs); //更新颜色配置文件
  6. updateCompositionState(refreshArgs); //更新合成状态
  7. planComposition(); //计划合成
  8. writeCompositionState(refreshArgs); //写入合成状态
  9. setColorTransform(refreshArgs); //设置颜色矩阵
  10. beginFrame(); //开始帧
  11. GpuCompositionResult result;
  12. const bool predictCompositionStrategy = canPredictCompositionStrategy(refreshArgs);
  13. if (predictCompositionStrategy) {
  14. result = prepareFrameAsync(refreshArgs); //准备帧数据以进行显示(Async方式)
  15. } else {
  16. prepareFrame(); //准备帧数据以进行显示
  17. }
  18. devOptRepaintFlash(refreshArgs); //处理显示输出设备的可选重绘闪烁
  19. finishFrame(refreshArgs, std::move(result)); //完成帧
  20. postFramebuffer(); //将帧缓冲区(framebuffer)的内容发送到显示设备进行显示
  21. renderCachedSets(refreshArgs); //进行渲染缓存设置
  22. }

上面方法主要处理如下:

1、调用Output的updateColorProfile方法,更新颜色配置。

2、调用Output的updateCompositionState方法,更新合成状态。

3、调用Output的planComposition方法,计划合成。

4、调用Output的writeCompositionState方法,写入合成状态。

5、调用Output的setColorTransform方法,设置颜色矩阵。

6、调用Output的beginFrame方法,开始帧。

7、调用Output的prepareFrameAsync方法,准备帧数据以进行显示(Async方式)。

8、调用Output的prepareFrame方法,准备帧数据以进行显示。

9、调用Output的devOptRepaintFlash方法,处理显示输出设备的可选重绘闪烁。

10、调用Output的finishFrame方法,完成帧。

11、调用Output的postFramebuffer方法,将帧缓冲区(framebuffer)的内容发送到显示设备进行显示。

12、调用Output的renderCachedSets方法,进行渲染缓存设置。

下面分别进行分析:

Output updateColorProfile

调用Output的updateColorProfile方法,更新颜色配置:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::updateColorProfile(const compositionengine::CompositionRefreshArgs& refreshArgs) {
  3. setColorProfile(pickColorProfile(refreshArgs));
  4. }

调用Output的setColorProfile方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::setColorProfile(const ColorProfile& colorProfile) {
  3. ui::Dataspace targetDataspace =
  4. getDisplayColorProfile()->getTargetDataspace(colorProfile.mode, colorProfile.dataspace,
  5. colorProfile.colorSpaceAgnosticDataspace);
  6. auto& outputState = editState();
  7. if (outputState.colorMode == colorProfile.mode &&
  8. outputState.dataspace == colorProfile.dataspace &&
  9. outputState.renderIntent == colorProfile.renderIntent &&
  10. outputState.targetDataspace == targetDataspace) {
  11. return;
  12. }
  13. outputState.colorMode = colorProfile.mode;
  14. outputState.dataspace = colorProfile.dataspace;
  15. outputState.renderIntent = colorProfile.renderIntent;
  16. outputState.targetDataspace = targetDataspace;
  17. mRenderSurface->setBufferDataspace(colorProfile.dataspace); //设置缓存数据空间
  18. ALOGV("Set active color mode: %s (%d), active render intent: %s (%d)",
  19. decodeColorMode(colorProfile.mode).c_str(), colorProfile.mode,
  20. decodeRenderIntent(colorProfile.renderIntent).c_str(), colorProfile.renderIntent);
  21. dirtyEntireOutput(); //重置脏区
  22. }

上面方法主要处理如下:

1、调用mRenderSurface(RenderSurface)的setBufferDataspace方法,设置缓存数据空间。

2、调用Output的dirtyEntireOutput方法,重置脏区。

下面分别进行分析:

RenderSurface setBufferDataspace

调用mRenderSurface(RenderSurface)的setBufferDataspace方法,设置缓存数据空间:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/RenderSurface.cpp
  2. void RenderSurface::setBufferDataspace(ui::Dataspace dataspace) {
  3. native_window_set_buffers_data_space(mNativeWindow.get(),
  4. static_cast<android_dataspace>(dataspace));
  5. }

Output updateCompositionState

调用Output的updateCompositionState方法,更新合成状态:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::updateCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. if (!getState().isEnabled) {
  6. return;
  7. }
  8. mLayerRequestingBackgroundBlur = findLayerRequestingBackgroundComposition();
  9. bool forceClientComposition = mLayerRequestingBackgroundBlur != nullptr;
  10. for (auto* layer : getOutputLayersOrderedByZ()) {
  11. layer->updateCompositionState(refreshArgs.updatingGeometryThisFrame,
  12. refreshArgs.devOptForceClientComposition ||
  13. forceClientComposition,
  14. refreshArgs.internalDisplayRotationFlags);
  15. if (mLayerRequestingBackgroundBlur == layer) {
  16. forceClientComposition = false;
  17. }
  18. }
  19. }

OutputLayer updateCompositionState

调用OutputLayer的updateCompositionState方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/OutputLayer.cpp
  2. void OutputLayer::updateCompositionState(
  3. bool includeGeometry, bool forceClientComposition,
  4. ui::Transform::RotationFlags internalDisplayRotationFlags) {
  5. const auto* layerFEState = getLayerFE().getCompositionState();
  6. if (!layerFEState) {
  7. return;
  8. }
  9. const auto& outputState = getOutput().getState();
  10. const auto& profile = *getOutput().getDisplayColorProfile();
  11. auto& state = editState();
  12. if (includeGeometry) {
  13. // Clear the forceClientComposition flag before it is set for any
  14. // reason. Note that since it can be set by some checks below when
  15. // updating the geometry state, we only clear it when updating the
  16. // geometry since those conditions for forcing client composition won't
  17. // go away otherwise.
  18. state.forceClientComposition = false;
  19. state.displayFrame = calculateOutputDisplayFrame();
  20. state.sourceCrop = calculateOutputSourceCrop(internalDisplayRotationFlags);
  21. state.bufferTransform = static_cast<Hwc2::Transform>(
  22. calculateOutputRelativeBufferTransform(internalDisplayRotationFlags));
  23. if ((layerFEState->isSecure && !outputState.isSecure) ||
  24. (state.bufferTransform & ui::Transform::ROT_INVALID)) {
  25. state.forceClientComposition = true;
  26. }
  27. }
  28. // Determine the output dependent dataspace for this layer. If it is
  29. // colorspace agnostic, it just uses the dataspace chosen for the output to
  30. // avoid the need for color conversion.
  31. state.dataspace = layerFEState->isColorspaceAgnostic &&
  32. outputState.targetDataspace != ui::Dataspace::UNKNOWN
  33. ? outputState.targetDataspace
  34. : layerFEState->dataspace;
  35. // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
  36. // We do this here instead of in buffer info so that dumpsys can still report layers that are
  37. // using the 170M transfer. Also we only do this if the colorspace is not agnostic for the
  38. // layer, in case the color profile uses a 170M transfer function.
  39. if (outputState.treat170mAsSrgb && !layerFEState->isColorspaceAgnostic &&
  40. (state.dataspace & HAL_DATASPACE_TRANSFER_MASK) == HAL_DATASPACE_TRANSFER_SMPTE_170M) {
  41. state.dataspace = static_cast<ui::Dataspace>(
  42. (state.dataspace & HAL_DATASPACE_STANDARD_MASK) |
  43. (state.dataspace & HAL_DATASPACE_RANGE_MASK) | HAL_DATASPACE_TRANSFER_SRGB);
  44. }
  45. // For hdr content, treat the white point as the display brightness - HDR content should not be
  46. // boosted or dimmed.
  47. // If the layer explicitly requests to disable dimming, then don't dim either.
  48. if (isHdrDataspace(state.dataspace) ||
  49. getOutput().getState().displayBrightnessNits == getOutput().getState().sdrWhitePointNits ||
  50. getOutput().getState().displayBrightnessNits == 0.f || !layerFEState->dimmingEnabled) {
  51. state.dimmingRatio = 1.f;
  52. state.whitePointNits = getOutput().getState().displayBrightnessNits;
  53. } else {
  54. state.dimmingRatio = std::clamp(getOutput().getState().sdrWhitePointNits /
  55. getOutput().getState().displayBrightnessNits,
  56. 0.f, 1.f);
  57. state.whitePointNits = getOutput().getState().sdrWhitePointNits;
  58. }
  59. // These are evaluated every frame as they can potentially change at any
  60. // time.
  61. if (layerFEState->forceClientComposition || !profile.isDataspaceSupported(state.dataspace) ||
  62. forceClientComposition) {
  63. state.forceClientComposition = true;
  64. }
  65. }

Output planComposition

调用Output的planComposition方法,计划合成:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::planComposition() {
  3. if (!mPlanner || !getState().isEnabled) {
  4. return;
  5. }
  6. ATRACE_CALL();
  7. ALOGV(__FUNCTION__);
  8. mPlanner->plan(getOutputLayersOrderedByZ());
  9. }

Planner plan

调用Planner的plan方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Planner.cpp
  2. void Planner::plan(
  3. compositionengine::Output::OutputLayersEnumerator<compositionengine::Output>&& layers) {
  4. ATRACE_CALL();
  5. std::unordered_set<LayerId> removedLayers;
  6. removedLayers.reserve(mPreviousLayers.size());
  7. std::transform(mPreviousLayers.begin(), mPreviousLayers.end(),
  8. std::inserter(removedLayers, removedLayers.begin()),
  9. [](const auto& layer) { return layer.first; });
  10. std::vector<LayerId> currentLayerIds;
  11. for (auto layer : layers) {
  12. LayerId id = layer->getLayerFE().getSequence();
  13. if (const auto layerEntry = mPreviousLayers.find(id); layerEntry != mPreviousLayers.end()) {
  14. // Track changes from previous info
  15. LayerState& state = layerEntry->second;
  16. ftl::Flags<LayerStateField> differences = state.update(layer);
  17. if (differences.get() == 0) {
  18. state.incrementFramesSinceBufferUpdate();
  19. } else {
  20. ALOGV("Layer %s changed: %s", state.getName().c_str(),
  21. differences.string().c_str());
  22. if (differences.test(LayerStateField::Buffer)) {
  23. state.resetFramesSinceBufferUpdate();
  24. } else {
  25. state.incrementFramesSinceBufferUpdate();
  26. }
  27. }
  28. } else {
  29. LayerState state(layer);
  30. ALOGV("Added layer %s", state.getName().c_str());
  31. mPreviousLayers.emplace(std::make_pair(id, std::move(state)));
  32. }
  33. currentLayerIds.emplace_back(id);
  34. if (const auto found = removedLayers.find(id); found != removedLayers.end()) {
  35. removedLayers.erase(found);
  36. }
  37. }
  38. mCurrentLayers.clear();
  39. mCurrentLayers.reserve(currentLayerIds.size());
  40. std::transform(currentLayerIds.cbegin(), currentLayerIds.cend(),
  41. std::back_inserter(mCurrentLayers), [this](LayerId id) {
  42. LayerState* state = &mPreviousLayers.at(id);
  43. state->getOutputLayer()->editState().overrideInfo = {};
  44. return state;
  45. });
  46. const NonBufferHash hash = getNonBufferHash(mCurrentLayers);
  47. mFlattenedHash =
  48. mFlattener.flattenLayers(mCurrentLayers, hash, std::chrono::steady_clock::now());
  49. const bool layersWereFlattened = hash != mFlattenedHash;
  50. ALOGV("[%s] Initial hash %zx flattened hash %zx", __func__, hash, mFlattenedHash);
  51. if (mPredictorEnabled) {
  52. mPredictedPlan =
  53. mPredictor.getPredictedPlan(layersWereFlattened ? std::vector<const LayerState*>()
  54. : mCurrentLayers,
  55. mFlattenedHash);
  56. if (mPredictedPlan) {
  57. ALOGV("[%s] Predicting plan %s", __func__, to_string(mPredictedPlan->plan).c_str());
  58. } else {
  59. ALOGV("[%s] No prediction found\n", __func__);
  60. }
  61. }
  62. // Clean up the set of previous layers now that the view of the LayerStates in the flattener are
  63. // up-to-date.
  64. for (LayerId removedLayer : removedLayers) {
  65. if (const auto layerEntry = mPreviousLayers.find(removedLayer);
  66. layerEntry != mPreviousLayers.end()) {
  67. const auto& [id, state] = *layerEntry;
  68. ALOGV("Removed layer %s", state.getName().c_str());
  69. mPreviousLayers.erase(removedLayer);
  70. }
  71. }
  72. }

Output writeCompositionState

调用Output的writeCompositionState方法,写入合成状态:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::writeCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. if (!getState().isEnabled) {
  6. return;
  7. }
  8. editState().earliestPresentTime = refreshArgs.earliestPresentTime;
  9. editState().previousPresentFence = refreshArgs.previousPresentFence;
  10. editState().expectedPresentTime = refreshArgs.expectedPresentTime;
  11. compositionengine::OutputLayer* peekThroughLayer = nullptr;
  12. sp<GraphicBuffer> previousOverride = nullptr;
  13. bool includeGeometry = refreshArgs.updatingGeometryThisFrame;
  14. uint32_t z = 0;
  15. bool overrideZ = false;
  16. uint64_t outputLayerHash = 0;
  17. for (auto* layer : getOutputLayersOrderedByZ()) {
  18. if (layer == peekThroughLayer) {
  19. // No longer needed, although it should not show up again, so
  20. // resetting it is not truly needed either.
  21. peekThroughLayer = nullptr;
  22. // peekThroughLayer was already drawn ahead of its z order.
  23. continue;
  24. }
  25. bool skipLayer = false;
  26. const auto& overrideInfo = layer->getState().overrideInfo;
  27. if (overrideInfo.buffer != nullptr) {
  28. if (previousOverride && overrideInfo.buffer->getBuffer() == previousOverride) {
  29. ALOGV("Skipping redundant buffer");
  30. skipLayer = true;
  31. } else {
  32. // First layer with the override buffer.
  33. if (overrideInfo.peekThroughLayer) {
  34. peekThroughLayer = overrideInfo.peekThroughLayer;
  35. // Draw peekThroughLayer first.
  36. overrideZ = true;
  37. includeGeometry = true;
  38. constexpr bool isPeekingThrough = true;
  39. peekThroughLayer->writeStateToHWC(includeGeometry, false, z++, overrideZ,
  40. isPeekingThrough);
  41. outputLayerHash ^= android::hashCombine(
  42. reinterpret_cast<uint64_t>(&peekThroughLayer->getLayerFE()),
  43. z, includeGeometry, overrideZ, isPeekingThrough,
  44. peekThroughLayer->requiresClientComposition());
  45. }
  46. previousOverride = overrideInfo.buffer->getBuffer();
  47. }
  48. }
  49. constexpr bool isPeekingThrough = false;
  50. layer->writeStateToHWC(includeGeometry, skipLayer, z++, overrideZ, isPeekingThrough);
  51. if (!skipLayer) {
  52. outputLayerHash ^= android::hashCombine(
  53. reinterpret_cast<uint64_t>(&layer->getLayerFE()),
  54. z, includeGeometry, overrideZ, isPeekingThrough,
  55. layer->requiresClientComposition());
  56. }
  57. }
  58. editState().outputLayerHash = outputLayerHash;
  59. }

Output setColorTransform

调用Output的setColorTransform方法,设置颜色矩阵:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::setColorTransform(const compositionengine::CompositionRefreshArgs& args) {
  3. auto& colorTransformMatrix = editState().colorTransformMatrix;
  4. if (!args.colorTransformMatrix || colorTransformMatrix == args.colorTransformMatrix) {
  5. return;
  6. }
  7. colorTransformMatrix = *args.colorTransformMatrix;
  8. dirtyEntireOutput();
  9. }

Output beginFrame

调用Output的beginFrame方法,开始帧:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::beginFrame() {
  3. auto& outputState = editState();
  4. const bool dirty = !getDirtyRegion().isEmpty();
  5. const bool empty = getOutputLayerCount() == 0;
  6. const bool wasEmpty = !outputState.lastCompositionHadVisibleLayers;
  7. // If nothing has changed (!dirty), don't recompose.
  8. // If something changed, but we don't currently have any visible layers,
  9. // and didn't when we last did a composition, then skip it this time.
  10. // The second rule does two things:
  11. // - When all layers are removed from a display, we'll emit one black
  12. // frame, then nothing more until we get new layers.
  13. // - When a display is created with a private layer stack, we won't
  14. // emit any black frames until a layer is added to the layer stack.
  15. const bool mustRecompose = dirty && !(empty && wasEmpty);
  16. const char flagPrefix[] = {'-', '+'};
  17. static_cast<void>(flagPrefix);
  18. ALOGV_IF("%s: %s composition for %s (%cdirty %cempty %cwasEmpty)", __FUNCTION__,
  19. mustRecompose ? "doing" : "skipping", getName().c_str(), flagPrefix[dirty],
  20. flagPrefix[empty], flagPrefix[wasEmpty]);
  21. mRenderSurface->beginFrame(mustRecompose);
  22. if (mustRecompose) {
  23. outputState.lastCompositionHadVisibleLayers = !empty;
  24. }
  25. }

RenderSurface beginFrame

调用mRenderSurface(RenderSurface)的beginFrame方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/RenderSurface.cpp
  2. const sp<DisplaySurface> mDisplaySurface;
  3. status_t RenderSurface::beginFrame(bool mustRecompose) {
  4. return mDisplaySurface->beginFrame(mustRecompose);
  5. }

调用mDisplaySurface(DisplaySurface)的beginFrame方法,FramebufferSurface继承DisplaySurface,调用FramebufferSurface的beginFrame方法:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
  2. status_t FramebufferSurface::beginFrame(bool /*mustRecompose*/) {
  3. return NO_ERROR;
  4. }
VirtualDisplaySurface beginFrame

调用mDisplaySurface(DisplaySurface)的beginFrame方法,VirtualDisplaySurface继承DisplaySurface,调用VirtualDisplaySurface的beginFrame方法:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
  2. status_t VirtualDisplaySurface::beginFrame(bool mustRecompose) {
  3. if (GpuVirtualDisplayId::tryCast(mDisplayId)) {
  4. return NO_ERROR;
  5. }
  6. mMustRecompose = mustRecompose;
  7. VDS_LOGW_IF(mDebugState != DebugState::Idle, "Unexpected %s in %s state", __func__,
  8. ftl::enum_string(mDebugState).c_str());
  9. mDebugState = DebugState::Begun;
  10. return refreshOutputBuffer();
  11. }

调用VirtualDisplaySurface的refreshOutputBuffer方法,刷新输出缓冲区:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
  2. HWComposer& mHwc;
  3. status_t VirtualDisplaySurface::refreshOutputBuffer() {
  4. LOG_ALWAYS_FATAL_IF(GpuVirtualDisplayId::tryCast(mDisplayId).has_value());
  5. if (mOutputProducerSlot >= 0) {
  6. mSource[SOURCE_SINK]->cancelBuffer(
  7. mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot),
  8. mOutputFence);
  9. }
  10. int sslot;
  11. status_t result = dequeueBuffer(SOURCE_SINK, mOutputFormat, mOutputUsage,
  12. &sslot, &mOutputFence);
  13. if (result < 0)
  14. return result;
  15. mOutputProducerSlot = mapSource2ProducerSlot(SOURCE_SINK, sslot);
  16. // On GPU-only frames, we don't have the right output buffer acquire fence
  17. // until after GPU calls queueBuffer(). So here we just set the buffer
  18. // (for use in HWC prepare) but not the fence; we'll call this again with
  19. // the proper fence once we have it.
  20. const auto halDisplayId = HalVirtualDisplayId::tryCast(mDisplayId);
  21. LOG_FATAL_IF(!halDisplayId);
  22. result = mHwc.setOutputBuffer(*halDisplayId, Fence::NO_FENCE,
  23. mProducerBuffers[mOutputProducerSlot]);
  24. return result;
  25. }
HWComposer setOutputBuffer

调用mHwc(HWComposer)的setOutputBuffer方法:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/HWComposer.cpp
  2. std::unordered_map<HalDisplayId, DisplayData> mDisplayData;
  3. std::unique_ptr<HWC2::Display> hwcDisplay;
  4. status_t HWComposer::setOutputBuffer(HalVirtualDisplayId displayId, const sp<Fence>& acquireFence,
  5. const sp<GraphicBuffer>& buffer) {
  6. RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
  7. const auto& displayData = mDisplayData[displayId];
  8. auto error = displayData.hwcDisplay->setOutputBuffer(buffer, acquireFence);
  9. RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
  10. return NO_ERROR;
  11. }
HWC2::Display setOutputBuffer

调用HWC2::Display的setOutputBuffer方法,之后就是HWC的处理了。

Output prepareFrameAsync

调用Output的prepareFrameAsync方法,准备帧数据以进行显示(Async方式):

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. GpuCompositionResult Output::prepareFrameAsync(const CompositionRefreshArgs& refreshArgs) {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. auto& state = editState();
  6. const auto& previousChanges = state.previousDeviceRequestedChanges;
  7. std::optional<android::HWComposer::DeviceRequestedChanges> changes;
  8. resetCompositionStrategy();
  9. auto hwcResult = chooseCompositionStrategyAsync(&changes);
  10. if (state.previousDeviceRequestedSuccess) {
  11. applyCompositionStrategy(previousChanges);
  12. }
  13. finishPrepareFrame();
  14. base::unique_fd bufferFence;
  15. std::shared_ptr<renderengine::ExternalTexture> buffer;
  16. updateProtectedContentState();
  17. const bool dequeueSucceeded = dequeueRenderBuffer(&bufferFence, &buffer);
  18. GpuCompositionResult compositionResult;
  19. if (dequeueSucceeded) {
  20. std::optional<base::unique_fd> optFd =
  21. composeSurfaces(Region::INVALID_REGION, refreshArgs, buffer, bufferFence);
  22. if (optFd) {
  23. compositionResult.fence = std::move(*optFd);
  24. }
  25. }
  26. auto chooseCompositionSuccess = hwcResult.get();
  27. const bool predictionSucceeded = dequeueSucceeded && changes == previousChanges;
  28. state.strategyPrediction = predictionSucceeded ? CompositionStrategyPredictionState::SUCCESS
  29. : CompositionStrategyPredictionState::FAIL;
  30. if (!predictionSucceeded) {
  31. ATRACE_NAME("CompositionStrategyPredictionMiss");
  32. resetCompositionStrategy();
  33. if (chooseCompositionSuccess) {
  34. applyCompositionStrategy(changes);
  35. }
  36. finishPrepareFrame();
  37. // Track the dequeued buffer to reuse so we don't need to dequeue another one.
  38. compositionResult.buffer = buffer;
  39. } else {
  40. ATRACE_NAME("CompositionStrategyPredictionHit");
  41. }
  42. state.previousDeviceRequestedChanges = std::move(changes);
  43. state.previousDeviceRequestedSuccess = chooseCompositionSuccess;
  44. return compositionResult;
  45. }

Output prepareFrame

调用Output的prepareFrame方法,准备帧数据以进行显示:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::prepareFrame() {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. auto& outputState = editState();
  6. if (!outputState.isEnabled) {
  7. return;
  8. }
  9. std::optional<android::HWComposer::DeviceRequestedChanges> changes;
  10. bool success = chooseCompositionStrategy(&changes); //向HWC询问合成策略
  11. resetCompositionStrategy();
  12. outputState.strategyPrediction = CompositionStrategyPredictionState::DISABLED;
  13. outputState.previousDeviceRequestedChanges = changes;
  14. outputState.previousDeviceRequestedSuccess = success;
  15. if (success) {
  16. applyCompositionStrategy(changes);
  17. }
  18. finishPrepareFrame();
  19. }

Output chooseCompositionStrategy

调用Output的chooseCompositionStrategy方法,向HWC询问合成策略:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. std::unique_ptr<HwcAsyncWorker> mHwComposerAsyncWorker;
  3. std::future<bool> Output::chooseCompositionStrategyAsync(
  4. std::optional<android::HWComposer::DeviceRequestedChanges>* changes) {
  5. return mHwComposerAsyncWorker->send(
  6. [&, changes]() { return chooseCompositionStrategy(changes); });
  7. }

调用mHwComposerAsyncWorker(HwcAsyncWorker)的send方法,获取合成策略:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/HwcAsyncWorker.cpp
  2. std::future<bool> HwcAsyncWorker::send(std::function<bool()> task) {
  3. std::unique_lock<std::mutex> lock(mMutex);
  4. android::base::ScopedLockAssertion assumeLock(mMutex);
  5. mTask = std::packaged_task<bool()>([task = std::move(task)]() { return task(); });
  6. mTaskRequested = true;
  7. mCv.notify_one();
  8. return mTask.get_future();
  9. }

返回chooseCompositionStrategy:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Display.cpp
  2. bool Display::chooseCompositionStrategy(
  3. std::optional<android::HWComposer::DeviceRequestedChanges>* outChanges) {
  4. ATRACE_CALL();
  5. ALOGV(__FUNCTION__);
  6. if (mIsDisconnected) {
  7. return false;
  8. }
  9. // If we don't have a HWC display, then we are done.
  10. const auto halDisplayId = HalDisplayId::tryCast(mId);
  11. if (!halDisplayId) {
  12. return false;
  13. }
  14. // Get any composition changes requested by the HWC device, and apply them.
  15. std::optional<android::HWComposer::DeviceRequestedChanges> changes;
  16. auto& hwc = getCompositionEngine().getHwComposer();
  17. if (status_t result =
  18. hwc.getDeviceCompositionChanges(*halDisplayId, anyLayersRequireClientComposition(),
  19. getState().earliestPresentTime,
  20. getState().previousPresentFence,
  21. getState().expectedPresentTime, outChanges);
  22. result != NO_ERROR) {
  23. ALOGE("chooseCompositionStrategy failed for %s: %d (%s)", getName().c_str(), result,
  24. strerror(-result));
  25. return false;
  26. }
  27. return true;
  28. }
HWComposer getDeviceCompositionChanges

调用hwc(HWComposer)的getDeviceCompositionChanges方法,向HWC获取合成策略:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/HWComposer.cpp
  2. status_t HWComposer::getDeviceCompositionChanges(
  3. HalDisplayId displayId, bool frameUsesClientComposition,
  4. std::chrono::steady_clock::time_point earliestPresentTime,
  5. const std::shared_ptr<FenceTime>& previousPresentFence, nsecs_t expectedPresentTime,
  6. std::optional<android::HWComposer::DeviceRequestedChanges>* outChanges) {
  7. ATRACE_CALL();
  8. RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
  9. auto& displayData = mDisplayData[displayId];
  10. auto& hwcDisplay = displayData.hwcDisplay;
  11. if (!hwcDisplay->isConnected()) {
  12. return NO_ERROR;
  13. }
  14. uint32_t numTypes = 0;
  15. uint32_t numRequests = 0;
  16. hal::Error error = hal::Error::NONE;
  17. // First try to skip validate altogether. We can do that when
  18. // 1. The previous frame has not been presented yet or already passed the
  19. // earliest time to present. Otherwise, we may present a frame too early.
  20. // 2. There is no client composition. Otherwise, we first need to render the
  21. // client target buffer.
  22. const bool canSkipValidate = [&] {
  23. // We must call validate if we have client composition
  24. if (frameUsesClientComposition) {
  25. return false;
  26. }
  27. // If composer supports getting the expected present time, we can skip
  28. // as composer will make sure to prevent early presentation
  29. if (mComposer->isSupported(Hwc2::Composer::OptionalFeature::ExpectedPresentTime)) {
  30. return true;
  31. }
  32. // composer doesn't support getting the expected present time. We can only
  33. // skip validate if we know that we are not going to present early.
  34. return std::chrono::steady_clock::now() >= earliestPresentTime ||
  35. previousPresentFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING;
  36. }();
  37. displayData.validateWasSkipped = false;
  38. if (canSkipValidate) {
  39. sp<Fence> outPresentFence;
  40. uint32_t state = UINT32_MAX;
  41. error = hwcDisplay->presentOrValidate(expectedPresentTime, &numTypes, &numRequests,
  42. &outPresentFence, &state);
  43. if (!hasChangesError(error)) {
  44. RETURN_IF_HWC_ERROR_FOR("presentOrValidate", error, displayId, UNKNOWN_ERROR);
  45. }
  46. if (state == 1) { //Present Succeeded.
  47. std::unordered_map<HWC2::Layer*, sp<Fence>> releaseFences;
  48. error = hwcDisplay->getReleaseFences(&releaseFences);
  49. displayData.releaseFences = std::move(releaseFences);
  50. displayData.lastPresentFence = outPresentFence;
  51. displayData.validateWasSkipped = true;
  52. displayData.presentError = error;
  53. return NO_ERROR;
  54. }
  55. // Present failed but Validate ran.
  56. } else {
  57. error = hwcDisplay->validate(expectedPresentTime, &numTypes, &numRequests);
  58. }
  59. ALOGV("SkipValidate failed, Falling back to SLOW validate/present");
  60. if (!hasChangesError(error)) {
  61. RETURN_IF_HWC_ERROR_FOR("validate", error, displayId, BAD_INDEX);
  62. }
  63. android::HWComposer::DeviceRequestedChanges::ChangedTypes changedTypes;
  64. changedTypes.reserve(numTypes);
  65. error = hwcDisplay->getChangedCompositionTypes(&changedTypes);
  66. RETURN_IF_HWC_ERROR_FOR("getChangedCompositionTypes", error, displayId, BAD_INDEX);
  67. auto displayRequests = static_cast<hal::DisplayRequest>(0);
  68. android::HWComposer::DeviceRequestedChanges::LayerRequests layerRequests;
  69. layerRequests.reserve(numRequests);
  70. error = hwcDisplay->getRequests(&displayRequests, &layerRequests);
  71. RETURN_IF_HWC_ERROR_FOR("getRequests", error, displayId, BAD_INDEX);
  72. DeviceRequestedChanges::ClientTargetProperty clientTargetProperty;
  73. error = hwcDisplay->getClientTargetProperty(&clientTargetProperty);
  74. outChanges->emplace(DeviceRequestedChanges{std::move(changedTypes), std::move(displayRequests),
  75. std::move(layerRequests),
  76. std::move(clientTargetProperty)});
  77. error = hwcDisplay->acceptChanges();
  78. RETURN_IF_HWC_ERROR_FOR("acceptChanges", error, displayId, BAD_INDEX);
  79. return NO_ERROR;
  80. }

Output devOptRepaintFlash

调用Output的devOptRepaintFlash方法,处理显示输出设备的可选重绘闪烁:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::devOptRepaintFlash(const compositionengine::CompositionRefreshArgs& refreshArgs) {
  3. if (CC_LIKELY(!refreshArgs.devOptFlashDirtyRegionsDelay)) {
  4. return;
  5. }
  6. if (getState().isEnabled) {
  7. if (const auto dirtyRegion = getDirtyRegion(); !dirtyRegion.isEmpty()) {
  8. base::unique_fd bufferFence;
  9. std::shared_ptr<renderengine::ExternalTexture> buffer;
  10. updateProtectedContentState();
  11. dequeueRenderBuffer(&bufferFence, &buffer);
  12. static_cast<void>(composeSurfaces(dirtyRegion, refreshArgs, buffer, bufferFence));
  13. mRenderSurface->queueBuffer(base::unique_fd());
  14. }
  15. }
  16. postFramebuffer();
  17. std::this_thread::sleep_for(*refreshArgs.devOptFlashDirtyRegionsDelay);
  18. prepareFrame();
  19. }

RenderSurface queueBuffer

调用mRenderSurface(RenderSurface)的queueBuffer方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/RenderSurface.cpp
  2. void RenderSurface::queueBuffer(base::unique_fd readyFence) {
  3. auto& state = mDisplay.getState();
  4. if (state.usesClientComposition || state.flipClientTarget) {
  5. // hasFlipClientTargetRequest could return true even if we haven't
  6. // dequeued a buffer before. Try dequeueing one if we don't have a
  7. // buffer ready.
  8. if (mTexture == nullptr) {
  9. ALOGI("Attempting to queue a client composited buffer without one "
  10. "previously dequeued for display [%s]. Attempting to dequeue "
  11. "a scratch buffer now",
  12. mDisplay.getName().c_str());
  13. // We shouldn't deadlock here, since mTexture == nullptr only
  14. // after a successful call to queueBuffer, or if dequeueBuffer has
  15. // never been called.
  16. base::unique_fd unused;
  17. dequeueBuffer(&unused);
  18. }
  19. if (mTexture == nullptr) {
  20. ALOGE("No buffer is ready for display [%s]", mDisplay.getName().c_str());
  21. } else {
  22. status_t result = mNativeWindow->queueBuffer(mNativeWindow.get(),
  23. mTexture->getBuffer()->getNativeBuffer(),
  24. dup(readyFence));
  25. if (result != NO_ERROR) {
  26. ALOGE("Error when queueing buffer for display [%s]: %d", mDisplay.getName().c_str(),
  27. result);
  28. // We risk blocking on dequeueBuffer if the primary display failed
  29. // to queue up its buffer, so crash here.
  30. if (!mDisplay.isVirtual()) {
  31. LOG_ALWAYS_FATAL("ANativeWindow::queueBuffer failed with error: %d", result);
  32. } else {
  33. mNativeWindow->cancelBuffer(mNativeWindow.get(),
  34. mTexture->getBuffer()->getNativeBuffer(),
  35. dup(readyFence));
  36. }
  37. }
  38. mTexture = nullptr;
  39. }
  40. }
  41. status_t result = mDisplaySurface->advanceFrame();
  42. if (result != NO_ERROR) {
  43. ALOGE("[%s] failed pushing new frame to HWC: %d", mDisplay.getName().c_str(), result);
  44. }
  45. }
FramebufferSurface advanceFrame

调用mDisplaySurface(DisplaySurface)的advanceFrame方法,FramebufferSurface继承与DisplaySurface,调用FramebufferSurface的advanceFrame方法,FramebufferSurface的advanceFrame方法用于更新帧并将其显示在屏幕上

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
  2. status_t FramebufferSurface::advanceFrame() {
  3. uint32_t slot = 0;
  4. sp<GraphicBuffer> buf;
  5. sp<Fence> acquireFence(Fence::NO_FENCE);
  6. Dataspace dataspace = Dataspace::UNKNOWN;
  7. status_t result = nextBuffer(slot, buf, acquireFence, dataspace);
  8. mDataSpace = dataspace;
  9. if (result != NO_ERROR) {
  10. ALOGE("error latching next FramebufferSurface buffer: %s (%d)",
  11. strerror(-result), result);
  12. }
  13. return result;
  14. }

调用FramebufferSurface的nextBuffer方法:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
  2. status_t FramebufferSurface::nextBuffer(uint32_t& outSlot,
  3. sp<GraphicBuffer>& outBuffer, sp<Fence>& outFence,
  4. Dataspace& outDataspace) {
  5. Mutex::Autolock lock(mMutex);
  6. BufferItem item;
  7. status_t err = acquireBufferLocked(&item, 0);
  8. if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
  9. mHwcBufferCache.getHwcBuffer(mCurrentBufferSlot, mCurrentBuffer, &outSlot, &outBuffer);
  10. return NO_ERROR;
  11. } else if (err != NO_ERROR) {
  12. ALOGE("error acquiring buffer: %s (%d)", strerror(-err), err);
  13. return err;
  14. }
  15. // If the BufferQueue has freed and reallocated a buffer in mCurrentSlot
  16. // then we may have acquired the slot we already own. If we had released
  17. // our current buffer before we call acquireBuffer then that release call
  18. // would have returned STALE_BUFFER_SLOT, and we would have called
  19. // freeBufferLocked on that slot. Because the buffer slot has already
  20. // been overwritten with the new buffer all we have to do is skip the
  21. // releaseBuffer call and we should be in the same state we'd be in if we
  22. // had released the old buffer first.
  23. if (mCurrentBufferSlot != BufferQueue::INVALID_BUFFER_SLOT &&
  24. item.mSlot != mCurrentBufferSlot) {
  25. mHasPendingRelease = true;
  26. mPreviousBufferSlot = mCurrentBufferSlot;
  27. mPreviousBuffer = mCurrentBuffer;
  28. }
  29. mCurrentBufferSlot = item.mSlot;
  30. mCurrentBuffer = mSlots[mCurrentBufferSlot].mGraphicBuffer;
  31. mCurrentFence = item.mFence;
  32. outFence = item.mFence;
  33. mHwcBufferCache.getHwcBuffer(mCurrentBufferSlot, mCurrentBuffer, &outSlot, &outBuffer);
  34. outDataspace = static_cast<Dataspace>(item.mDataSpace);
  35. status_t result = mHwc.setClientTarget(mDisplayId, outSlot, outFence, outBuffer, outDataspace);
  36. if (result != NO_ERROR) {
  37. ALOGE("error posting framebuffer: %d", result);
  38. return result;
  39. }
  40. return NO_ERROR;
  41. }
HWComposer setClientTarget

调用mHwc(HWComposer)的setClientTarget方法:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/HWComposer.cpp
  2. std::unordered_map<HalDisplayId, DisplayData> mDisplayData;
  3. std::unique_ptr<HWC2::Display> hwcDisplay;
  4. status_t HWComposer::setClientTarget(HalDisplayId displayId, uint32_t slot,
  5. const sp<Fence>& acquireFence, const sp<GraphicBuffer>& target,
  6. ui::Dataspace dataspace) {
  7. RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
  8. ALOGV("%s for display %s", __FUNCTION__, to_string(displayId).c_str());
  9. auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
  10. auto error = hwcDisplay->setClientTarget(slot, target, acquireFence, dataspace);
  11. RETURN_IF_HWC_ERROR(error, displayId, BAD_VALUE);
  12. return NO_ERROR;
  13. }
HWC2::Display setOutputBuffer

调用HWC2::Display的setClientTarget方法,之后就是HWC的处理了。

Output finishFrame

调用Output的finishFrame方法,完成帧:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::finishFrame(const CompositionRefreshArgs& refreshArgs, GpuCompositionResult&& result) {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. const auto& outputState = getState();
  6. if (!outputState.isEnabled) {
  7. return;
  8. }
  9. std::optional<base::unique_fd> optReadyFence;
  10. std::shared_ptr<renderengine::ExternalTexture> buffer;
  11. base::unique_fd bufferFence;
  12. if (outputState.strategyPrediction == CompositionStrategyPredictionState::SUCCESS) {
  13. optReadyFence = std::move(result.fence);
  14. } else {
  15. if (result.bufferAvailable()) {
  16. buffer = std::move(result.buffer);
  17. bufferFence = std::move(result.fence);
  18. } else {
  19. updateProtectedContentState();
  20. if (!dequeueRenderBuffer(&bufferFence, &buffer)) {
  21. return;
  22. }
  23. }
  24. // Repaint the framebuffer (if needed), getting the optional fence for when
  25. // the composition completes.
  26. optReadyFence = composeSurfaces(Region::INVALID_REGION, refreshArgs, buffer, bufferFence);
  27. }
  28. if (!optReadyFence) {
  29. return;
  30. }
  31. // swap buffers (presentation)
  32. mRenderSurface->queueBuffer(std::move(*optReadyFence));
  33. }

Output postFramebuffer

调用Output的postFramebuffer方法,将帧缓冲区(framebuffer)的内容发送到显示设备进行显示:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::postFramebuffer() {
  3. ATRACE_CALL();
  4. ALOGV(__FUNCTION__);
  5. if (!getState().isEnabled) {
  6. return;
  7. }
  8. auto& outputState = editState();
  9. outputState.dirtyRegion.clear();
  10. mRenderSurface->flip();
  11. auto frame = presentAndGetFrameFences();
  12. mRenderSurface->onPresentDisplayCompleted();
  13. for (auto* layer : getOutputLayersOrderedByZ()) {
  14. // The layer buffer from the previous frame (if any) is released
  15. // by HWC only when the release fence from this frame (if any) is
  16. // signaled. Always get the release fence from HWC first.
  17. sp<Fence> releaseFence = Fence::NO_FENCE;
  18. if (auto hwcLayer = layer->getHwcLayer()) {
  19. if (auto f = frame.layerFences.find(hwcLayer); f != frame.layerFences.end()) {
  20. releaseFence = f->second;
  21. }
  22. }
  23. // If the layer was client composited in the previous frame, we
  24. // need to merge with the previous client target acquire fence.
  25. // Since we do not track that, always merge with the current
  26. // client target acquire fence when it is available, even though
  27. // this is suboptimal.
  28. // TODO(b/121291683): Track previous frame client target acquire fence.
  29. if (outputState.usesClientComposition) {
  30. releaseFence =
  31. Fence::merge("LayerRelease", releaseFence, frame.clientTargetAcquireFence);
  32. }
  33. layer->getLayerFE().onLayerDisplayed(
  34. ftl::yield<FenceResult>(std::move(releaseFence)).share());
  35. }
  36. // We've got a list of layers needing fences, that are disjoint with
  37. // OutputLayersOrderedByZ. The best we can do is to
  38. // supply them with the present fence.
  39. for (auto& weakLayer : mReleasedLayers) {
  40. if (const auto layer = weakLayer.promote()) {
  41. layer->onLayerDisplayed(ftl::yield<FenceResult>(frame.presentFence).share());
  42. }
  43. }
  44. // Clear out the released layers now that we're done with them.
  45. mReleasedLayers.clear();
  46. }

上面方法主要处理如下:

1、调用Output的presentAndGetFrameFences方法,通过presentAndGetReleaseFences显示获取releaseFences。

2、调用BufferQueueLayer的onLayerDisplayed方法。

下面分别进行分析。

Output presentAndGetFrameFences

调用Output的presentAndGetFrameFences方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. compositionengine::Output::FrameFences Output::presentAndGetFrameFences() {
  3. compositionengine::Output::FrameFences result;
  4. if (getState().usesClientComposition) {
  5. result.clientTargetAcquireFence = mRenderSurface->getClientTargetAcquireFence();
  6. }
  7. return result;
  8. }

调用mRenderSurface(RenderSurface)的getClientTargetAcquireFence方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/RenderSurface.cpp
  2. const sp<DisplaySurface> mDisplaySurface;
  3. const sp<Fence>& RenderSurface::getClientTargetAcquireFence() const {
  4. return mDisplaySurface->getClientTargetAcquireFence();
  5. }
FramebufferSurface getClientTargetAcquireFence

调用mDisplaySurface(DisplaySurface)的prepareFrame方法,FramebufferSurface 继承于DisplaySurface,因此调用FramebufferSurface的getClientTargetAcquireFence方法:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
  2. const sp<Fence>& FramebufferSurface::getClientTargetAcquireFence() const {
  3. return mCurrentFence;
  4. }

BufferQueueLayer onLayerDisplayed

调用Layer的onLayerDisplayed方法,BufferQueueLayer继承于BuffeLayer,BuffeLayer由继承于Layer,因此调用BufferQueueLayer的onLayerDisplayed方法:

Android13 BufferQueueLayer onLayerDisplayed流程分析-CSDN博客

Output renderCachedSets

调用Output的renderCachedSets方法,进行渲染缓存设置:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::renderCachedSets(const CompositionRefreshArgs& refreshArgs) {
  3. if (mPlanner) {
  4. mPlanner->renderCachedSets(getState(), refreshArgs.scheduledFrameTime);
  5. }
  6. }

Output dirtyEntireOutput

调用Output的dirtyEntireOutput方法,重置脏区:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. OutputCompositionState outputState ;
  3. Region dirtyRegion;
  4. using OutputCompositionState = compositionengine::impl::OutputCompositionState;
  5. void Output::dirtyEntireOutput() {
  6. auto& outputState = editState();
  7. outputState.dirtyRegion.set(outputState.displaySpace.getBoundsAsRect());
  8. }

Region set

调用outputState(OutputCompositionState )内成员变量dirtyRegion(Region)的set方法,设置脏区:

  1. //frameworks/native/libs/ui/Region.cpp
  2. FatVector<Rect> mStorage;
  3. void Region::set(const Rect& r)
  4. {
  5. mStorage.clear();
  6. mStorage.push_back(r);
  7. }

Output finishPrepareFrame

调用Output的finishPrepareFrame方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Output.cpp
  2. void Output::finishPrepareFrame() {
  3. const auto& state = getState();
  4. if (mPlanner) {
  5. mPlanner->reportFinalPlan(getOutputLayersOrderedByZ());
  6. }
  7. mRenderSurface->prepareFrame(state.usesClientComposition, state.usesDeviceComposition);
  8. }

Planner reportFinalPlan

调用mPlanner(Planner)的reportFinalPlan方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Planner.cpp
  2. void Planner::reportFinalPlan(
  3. compositionengine::Output::OutputLayersEnumerator<compositionengine::Output>&& layers) {
  4. ATRACE_CALL();
  5. if (!mPredictorEnabled) {
  6. return;
  7. }
  8. Plan finalPlan;
  9. const GraphicBuffer* currentOverrideBuffer = nullptr;
  10. bool hasSkippedLayers = false;
  11. for (auto layer : layers) {
  12. if (!layer->getState().overrideInfo.buffer) {
  13. continue;
  14. }
  15. const GraphicBuffer* overrideBuffer =
  16. layer->getState().overrideInfo.buffer->getBuffer().get();
  17. if (overrideBuffer != nullptr && overrideBuffer == currentOverrideBuffer) {
  18. // Skip this layer since it is part of a previous cached set
  19. hasSkippedLayers = true;
  20. continue;
  21. }
  22. currentOverrideBuffer = overrideBuffer;
  23. const bool forcedOrRequestedClient =
  24. layer->getState().forceClientComposition || layer->requiresClientComposition();
  25. finalPlan.addLayerType(
  26. forcedOrRequestedClient
  27. ? aidl::android::hardware::graphics::composer3::Composition::CLIENT
  28. : layer->getLayerFE().getCompositionState()->compositionType);
  29. }
  30. mPredictor.recordResult(mPredictedPlan, mFlattenedHash, mCurrentLayers, hasSkippedLayers,
  31. finalPlan);
  32. }

调用mPredictor(Predictor)的recordResult方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/Predictor.cpp
  2. void Predictor::recordResult(std::optional<PredictedPlan> predictedPlan,
  3. NonBufferHash flattenedHash,
  4. const std::vector<const LayerState*>& layers, bool hasSkippedLayers,
  5. Plan result) {
  6. if (predictedPlan) {
  7. recordPredictedResult(*predictedPlan, layers, std::move(result));
  8. return;
  9. }
  10. ++mMissCount;
  11. if (!hasSkippedLayers && findSimilarPrediction(layers, result)) {
  12. return;
  13. }
  14. ALOGV("[%s] Adding novel candidate %zx", __func__, flattenedHash);
  15. mCandidates.emplace_front(flattenedHash, Prediction(layers, result));
  16. if (mCandidates.size() > MAX_CANDIDATES) {
  17. mCandidates.pop_back();
  18. }
  19. }

RenderSurface prepareFrame

调用RenderSurface的prepareFrame方法:

  1. //frameworks/native/services/surfaceflinger/CompositionEngin/src/RenderSurface.cpp
  2. const sp<DisplaySurface> mDisplaySurface;
  3. void RenderSurface::prepareFrame(bool usesClientComposition, bool usesDeviceComposition) {
  4. const auto compositionType = [=] {
  5. using CompositionType = DisplaySurface::CompositionType;
  6. if (usesClientComposition && usesDeviceComposition) return CompositionType::Mixed;
  7. if (usesClientComposition) return CompositionType::Gpu;
  8. if (usesDeviceComposition) return CompositionType::Hwc;
  9. // Nothing to do -- when turning the screen off we get a frame like
  10. // this. Call it a HWC frame since we won't be doing any GPU work but
  11. // will do a prepare/set cycle.
  12. return CompositionType::Hwc;
  13. }();
  14. if (status_t result = mDisplaySurface->prepareFrame(compositionType); result != NO_ERROR) {
  15. ALOGE("updateCompositionType failed for %s: %d (%s)", mDisplay.getName().c_str(), result,
  16. strerror(-result));
  17. }
  18. }
VirtualDisplaySurface prepareFrame

调用mDisplaySurface(DisplaySurface)的prepareFrame方法,VirtualDisplaySurface继承于DisplaySurface,因此调用DisplaySurface的prepareFrame方法,DisplaySurface的prepareFrame方法用于准备帧

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
  2. status_t VirtualDisplaySurface::prepareFrame(CompositionType compositionType) {
  3. if (GpuVirtualDisplayId::tryCast(mDisplayId)) {
  4. return NO_ERROR;
  5. }
  6. VDS_LOGW_IF(mDebugState != DebugState::Begun, "Unexpected %s in %s state", __func__,
  7. ftl::enum_string(mDebugState).c_str());
  8. mDebugState = DebugState::Prepared;
  9. mCompositionType = compositionType;
  10. if (mForceHwcCopy && mCompositionType == CompositionType::Gpu) {
  11. // Some hardware can do RGB->YUV conversion more efficiently in hardware
  12. // controlled by HWC than in hardware controlled by the video encoder.
  13. // Forcing GPU-composed frames to go through an extra copy by the HWC
  14. // allows the format conversion to happen there, rather than passing RGB
  15. // directly to the consumer.
  16. //
  17. // On the other hand, when the consumer prefers RGB or can consume RGB
  18. // inexpensively, this forces an unnecessary copy.
  19. mCompositionType = CompositionType::Mixed;
  20. }
  21. if (mCompositionType != mDebugLastCompositionType) {
  22. VDS_LOGV("%s: composition type changed to %s", __func__,
  23. toString(mCompositionType).c_str());
  24. mDebugLastCompositionType = mCompositionType;
  25. }
  26. if (mCompositionType != CompositionType::Gpu &&
  27. (mOutputFormat != mDefaultOutputFormat || mOutputUsage != GRALLOC_USAGE_HW_COMPOSER)) {
  28. // We must have just switched from GPU-only to MIXED or HWC
  29. // composition. Stop using the format and usage requested by the GPU
  30. // driver; they may be suboptimal when HWC is writing to the output
  31. // buffer. For example, if the output is going to a video encoder, and
  32. // HWC can write directly to YUV, some hardware can skip a
  33. // memory-to-memory RGB-to-YUV conversion step.
  34. //
  35. // If we just switched *to* GPU-only mode, we'll change the
  36. // format/usage and get a new buffer when the GPU driver calls
  37. // dequeueBuffer().
  38. mOutputFormat = mDefaultOutputFormat;
  39. mOutputUsage = GRALLOC_USAGE_HW_COMPOSER;
  40. refreshOutputBuffer();
  41. }
  42. return NO_ERROR;
  43. }

调用VirtualDisplaySurface的refreshOutputBuffer方法:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
  2. status_t VirtualDisplaySurface::refreshOutputBuffer() {
  3. LOG_ALWAYS_FATAL_IF(GpuVirtualDisplayId::tryCast(mDisplayId).has_value());
  4. if (mOutputProducerSlot >= 0) {
  5. mSource[SOURCE_SINK]->cancelBuffer(
  6. mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot),
  7. mOutputFence);
  8. }
  9. int sslot;
  10. status_t result = dequeueBuffer(SOURCE_SINK, mOutputFormat, mOutputUsage,
  11. &sslot, &mOutputFence);
  12. if (result < 0)
  13. return result;
  14. mOutputProducerSlot = mapSource2ProducerSlot(SOURCE_SINK, sslot);
  15. // On GPU-only frames, we don't have the right output buffer acquire fence
  16. // until after GPU calls queueBuffer(). So here we just set the buffer
  17. // (for use in HWC prepare) but not the fence; we'll call this again with
  18. // the proper fence once we have it.
  19. const auto halDisplayId = HalVirtualDisplayId::tryCast(mDisplayId);
  20. LOG_FATAL_IF(!halDisplayId);
  21. result = mHwc.setOutputBuffer(*halDisplayId, Fence::NO_FENCE,
  22. mProducerBuffers[mOutputProducerSlot]);
  23. return result;
  24. }
HWComposer setOutputBuffer

调用HWComposer的setOutputBuffer方法:

  1. //frameworks/native/services/surfaceflinger/DisplayHardware/HWComposer.cpp
  2. std::unordered_map<HalDisplayId, DisplayData> mDisplayData;
  3. std::unique_ptr<HWC2::Display> hwcDisplay;
  4. status_t HWComposer::setOutputBuffer(HalVirtualDisplayId displayId, const sp<Fence>& acquireFence,
  5. const sp<GraphicBuffer>& buffer) {
  6. RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
  7. const auto& displayData = mDisplayData[displayId];
  8. auto error = displayData.hwcDisplay->setOutputBuffer(buffer, acquireFence);
  9. RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
  10. return NO_ERROR;
  11. }
HWC2::Display setOutputBuffer

调用HWC2::Display的setOutputBuffer方法,之后就是HWC的处理了。

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/827804?site
推荐阅读
相关标签
  

闽ICP备14008679号