File: arc_screen_capture_session.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (442 lines) | stat: -rw-r--r-- 17,451 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/arc/screen_capture/arc_screen_capture_session.h"

#include <utility>

#include "ash/shell.h"
#include "base/functional/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ash/notifications/screen_capture_notification_ui_ash.h"
#include "chrome/browser/media/webrtc/desktop_capture_access_handler.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/ash/experiences/arc/mojom/screen_capture.mojom.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "components/viz/common/frame_sinks/copy_output_result.h"
#include "components/viz/common/gpu/raster_context_provider.h"
#include "components/viz/common/resources/shared_image_format_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/client_shared_image.h"
#include "gpu/command_buffer/client/context_support.h"
#include "gpu/command_buffer/client/raster_interface.h"
#include "gpu/command_buffer/client/shared_image_interface.h"
#include "gpu/command_buffer/common/shared_image_usage.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "third_party/blink/public/common/mediastream/media_stream_request.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/display/display.h"
#include "ui/display/manager/display_manager.h"
#include "ui/display/screen.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gfx/linux/client_native_pixmap_factory_dmabuf.h"

namespace arc {

namespace {
// Callback into Android to force screen updates if the queue gets this big.
constexpr size_t kQueueSizeToForceUpdate = 4;
// Drop frames if the queue gets this big.
constexpr size_t kQueueSizeToDropFrames = 8;
// Bytes per pixel, Android returns stride in pixel units, Chrome uses it in
// bytes.
constexpr size_t kBytesPerPixel = 4;

scoped_refptr<viz::RasterContextProvider> GetContextProvider() {
  return aura::Env::GetInstance()
      ->context_factory()
      ->SharedMainThreadRasterContextProvider();
}

}  // namespace

// Holds ARC++ provided buffer to copy into.
struct ArcScreenCaptureSession::PendingBuffer {
  PendingBuffer(SetOutputBufferCallback callback,
                scoped_refptr<gpu::ClientSharedImage> shared_image)
      : buffer_ready_callback_(std::move(callback)),
        shared_image_(std::move(shared_image)) {}
  SetOutputBufferCallback buffer_ready_callback_;
  scoped_refptr<gpu::ClientSharedImage> shared_image_;
};

// Holds CopyOutputResult texture.
struct ArcScreenCaptureSession::DesktopTexture {
  DesktopTexture(const gpu::Mailbox& mailbox,
                 viz::ReleaseCallback release_callback)
      : mailbox_(mailbox), release_callback_(std::move(release_callback)) {}
  const gpu::Mailbox mailbox_;
  viz::ReleaseCallback release_callback_;
};

// static
mojo::PendingRemote<mojom::ScreenCaptureSession>
ArcScreenCaptureSession::Create(
    mojo::PendingRemote<mojom::ScreenCaptureSessionNotifier> notifier,
    const std::string& display_name,
    content::DesktopMediaID desktop_id,
    const gfx::Size& size,
    bool enable_notification) {
  // This will get cleaned up when the connection error handler is called.
  ArcScreenCaptureSession* session =
      new ArcScreenCaptureSession(std::move(notifier), size);
  mojo::PendingRemote<mojom::ScreenCaptureSession> result =
      session->Initialize(desktop_id, display_name, enable_notification);
  if (!result) {
    delete session;
  }
  return result;
}

ArcScreenCaptureSession::ArcScreenCaptureSession(
    mojo::PendingRemote<mojom::ScreenCaptureSessionNotifier> notifier,
    const gfx::Size& size)
    : notifier_(std::move(notifier)),
      size_(size),
      client_native_pixmap_factory_(
          gfx::CreateClientNativePixmapFactoryDmabuf()) {}

mojo::PendingRemote<mojom::ScreenCaptureSession>
ArcScreenCaptureSession::Initialize(content::DesktopMediaID desktop_id,
                                    const std::string& display_name,
                                    bool enable_notification) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  display_root_window_ =
      content::DesktopMediaID::GetNativeWindowById(desktop_id);
  if (!display_root_window_) {
    LOG(ERROR) << "Unable to find Aura desktop window";
    return mojo::NullRemote();
  }

  auto context_provider = GetContextProvider();
  context_provider->AddObserver(this);

  display::Display display =
      display::Screen::GetScreen()->GetDisplayNearestWindow(
          display_root_window_);
  display_id_ = display.id();

  display_root_window_->GetHost()->compositor()->AddAnimationObserver(this);

  if (enable_notification) {
    // Show the tray notification icon now.
    std::u16string notification_text =
        l10n_util::GetStringFUTF16(IDS_MEDIA_SCREEN_CAPTURE_NOTIFICATION_TEXT,
                                   base::UTF8ToUTF16(display_name));
    notification_ui_ = ScreenCaptureNotificationUI::Create(
        notification_text, /*capturing_web_contents=*/nullptr);
    notification_ui_->OnStarted(
        base::BindOnce(&ArcScreenCaptureSession::NotificationStop,
                       weak_ptr_factory_.GetWeakPtr()),
        content::MediaStreamUI::SourceCallback(),
        std::vector<content::DesktopMediaID>{});
  }

  ash::Shell::Get()->display_manager()->inc_screen_capture_active_counter();
  ash::Shell::Get()->UpdateCursorCompositingEnabled();

  mojo::PendingRemote<mojom::ScreenCaptureSession> remote =
      receiver_.BindNewPipeAndPassRemote();
  receiver_.set_disconnect_handler(
      base::BindOnce(&ArcScreenCaptureSession::Close, base::Unretained(this)));
  return remote;
}

void ArcScreenCaptureSession::Close() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  delete this;
}

ArcScreenCaptureSession::~ArcScreenCaptureSession() {
  // This needs to be done because |buffer_queue_| might own a mojo callback and
  // the message pipe must be closed before those callbacks are destroyed.
  receiver_.reset();
  GetContextProvider()->RemoveObserver(this);

  if (!display_root_window_) {
    return;
  }

  display_root_window_->GetHost()->compositor()->RemoveAnimationObserver(this);
  ash::Shell::Get()->display_manager()->dec_screen_capture_active_counter();
  ash::Shell::Get()->UpdateCursorCompositingEnabled();
}

void ArcScreenCaptureSession::NotificationStop() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  Close();
}

void ArcScreenCaptureSession::SetOutputBufferDeprecated(
    mojo::ScopedHandle graphics_buffer,
    uint32_t stride,
    SetOutputBufferDeprecatedCallback callback) {
  // Defined locally to avoid having to add a dependency on drm_fourcc.h
  constexpr uint64_t DRM_FORMAT_MOD_LINEAR = 0;

  SetOutputBuffer(std::move(graphics_buffer), gfx::BufferFormat::RGBX_8888,
                  DRM_FORMAT_MOD_LINEAR, stride,
                  base::BindOnce(
                      [](base::OnceCallback<void()> callback) {
                        std::move(callback).Run();
                      },
                      std::move(callback)));
}

void ArcScreenCaptureSession::SetOutputBuffer(
    mojo::ScopedHandle graphics_buffer,
    gfx::BufferFormat buffer_format,
    uint64_t buffer_format_modifier,
    uint32_t stride,
    SetOutputBufferCallback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  if (!graphics_buffer.is_valid()) {
    LOG(ERROR) << "Invalid handle passed into SetOutputBuffer";
    std::move(callback).Run();
    return;
  }
  auto* ri = GetContextProvider()->RasterInterface();
  auto* sii = GetContextProvider()->SharedImageInterface();
  if (!ri || !sii) {
    LOG(ERROR) << "Unable to get the GL context or SharedImageInterface";
    return;
  }

  gfx::NativePixmapHandle native_pixmap_handle;
  native_pixmap_handle.modifier = buffer_format_modifier;
  base::ScopedPlatformFile platform_file;
  MojoResult mojo_result =
      mojo::UnwrapPlatformFile(std::move(graphics_buffer), &platform_file);
  if (mojo_result != MOJO_RESULT_OK) {
    LOG(ERROR) << "Failed unwrapping Mojo handle " << mojo_result;
    std::move(callback).Run();
    return;
  }
  native_pixmap_handle.planes.emplace_back(
      stride * kBytesPerPixel, 0, stride * kBytesPerPixel * size_.height(),
      std::move(platform_file));

  viz::SharedImageFormat si_format = viz::GetSharedImageFormat(buffer_format);

  auto client_shared_image = sii->CreateSharedImage(
      {si_format, size_, gfx::ColorSpace(),
       // NOTE: This SI will be used as the destination of a copy of the desktop
       // texture via the raster interface. Hence, it needs RASTER_WRITE usage.
       // Note that as the browser process raster interface uses
       // RasterImplementation (and not RasterImplementationGLES) as its
       // implementation, GLES2_WRITE usage is not needed.
       gpu::SHARED_IMAGE_USAGE_RASTER_WRITE, "ArcScreenCapture"},
      gfx::GpuMemoryBufferHandle(std::move(native_pixmap_handle)));
  CHECK(client_shared_image);

  std::unique_ptr<PendingBuffer> pending_buffer =
      std::make_unique<PendingBuffer>(std::move(callback),
                                      std::move(client_shared_image));
  if (texture_queue_.empty()) {
    // Put our GPU buffer into a queue so it can be used on the next callback
    // where we get a desktop texture.
    buffer_queue_.push(std::move(pending_buffer));
  } else {
    // We already have a texture from the animation callbacks, use that for
    // rendering.
    CopyDesktopTextureToGpuBuffer(std::move(texture_queue_.front()),
                                  std::move(pending_buffer));
    texture_queue_.pop();
  }
}

void ArcScreenCaptureSession::QueryCompleted(
    uint32_t query_id,
    std::unique_ptr<DesktopTexture> desktop_texture,
    std::unique_ptr<PendingBuffer> pending_buffer) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  auto* ri = GetContextProvider()->RasterInterface();
  auto* sii = GetContextProvider()->SharedImageInterface();
  if (!ri || !sii) {
    LOG(ERROR) << "Unable to get RasterInterface or SharedImageInterface";
    return;
  }

  // Return CopyOutputResult resources after texture copy happens.
  gpu::SyncToken sync_token;
  ri->GenSyncTokenCHROMIUM(sync_token.GetData());
  std::move(desktop_texture->release_callback_).Run(sync_token, false);

  // Notify ARC++ that the buffer is ready.
  std::move(pending_buffer->buffer_ready_callback_).Run();

  ri->DeleteQueriesEXT(1, &query_id);

  // Return resources for ARC++ buffer.
  sii->DestroySharedImage(gpu::SyncToken(),
                          std::move(pending_buffer->shared_image_));
}

void ArcScreenCaptureSession::OnDesktopCaptured(
    std::unique_ptr<viz::CopyOutputResult> result) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (result->IsEmpty() || result->size().width() < size_.width() - 1 ||
      result->size().width() > size_.width() + 1 ||
      result->size().height() < size_.height() - 1 ||
      result->size().height() > size_.height() + 1) {
    // If the display size changed after the CopyOutputRequest was issued the
    // scale ratio might not produce the right sized output. Drop this result
    // since it's not usable. The next CopyOutputRequest to be issued will know
    // the new display size and have the correct scale ratio.
    // Note that result->size() is computed, and so may be a +/- one pixel from
    // the expected size_ value due to rounding and truncation of floating
    // point values. See b/322075216.
    LOG(WARNING)
        << "Ignoring screen capture result due to size mismatch. Expected "
        << size_.ToString() << " but received " << result->size().ToString();
    return;
  }

  DCHECK_EQ(result->format(), viz::CopyOutputResult::Format::RGBA);
  DCHECK_EQ(result->destination(),
            viz::CopyOutputResult::Destination::kNativeTextures);

  auto* ri = GetContextProvider()->RasterInterface();
  if (!ri) {
    LOG(ERROR) << "Unable to get RasterInterface";
    return;
  }
  // Get the source texture - RGBA format is guaranteed to have 1 valid texture
  // if the CopyOutputRequest succeeded:
  gpu::Mailbox result_mailbox = result->GetTextureResult()->mailbox;
  CHECK(!result_mailbox.IsZero());

  viz::CopyOutputResult::ReleaseCallbacks release_callbacks =
      result->TakeTextureOwnership();
  CHECK_EQ(1u, release_callbacks.size());

  std::unique_ptr<DesktopTexture> desktop_texture =
      std::make_unique<DesktopTexture>(result_mailbox,
                                       std::move(release_callbacks[0]));
  if (buffer_queue_.empty()) {
    // We don't have a GPU buffer to render to, so put this in a queue to use
    // when we have one.
    texture_queue_.emplace(std::move(desktop_texture));
  } else {
    // Take the first GPU buffer from the queue and render to that.
    CopyDesktopTextureToGpuBuffer(std::move(desktop_texture),
                                  std::move(buffer_queue_.front()));
    buffer_queue_.pop();
  }
}

void ArcScreenCaptureSession::CopyDesktopTextureToGpuBuffer(
    std::unique_ptr<DesktopTexture> desktop_texture,
    std::unique_ptr<PendingBuffer> pending_buffer) {
  auto context_provider = GetContextProvider();
  auto* ri = context_provider->RasterInterface();

  if (!ri) {
    LOG(ERROR) << "Unable to get RasterInterface";
    return;
  }
  uint32_t query_id;
  ri->GenQueriesEXT(1, &query_id);
  ri->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM, query_id);
  scoped_refptr<gpu::ClientSharedImage> si = pending_buffer->shared_image_;
  std::unique_ptr<gpu::RasterScopedAccess> ri_access =
      si->BeginRasterAccess(ri, si->creation_sync_token(), /*readonly=*/false);
  ri->CopySharedImage(desktop_texture->mailbox_,
                      pending_buffer->shared_image_->mailbox(), 0, 0, 0, 0,
                      size_.width(), size_.height());
  gpu::RasterScopedAccess::EndAccess(std::move(ri_access));
  ri->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM);

  // The query will be signalled after the copy operation has finished on the
  // GPU and ARC++ can safely read from the buffer.
  context_provider->ContextSupport()->SignalQuery(
      query_id,
      base::BindOnce(&ArcScreenCaptureSession::QueryCompleted,
                     weak_ptr_factory_.GetWeakPtr(), query_id,
                     std::move(desktop_texture), std::move(pending_buffer)));
}

void ArcScreenCaptureSession::OnAnimationStep(base::TimeTicks timestamp) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  CompositorAnimationObserver::ResetIfActive();
  if (texture_queue_.size() >= kQueueSizeToForceUpdate) {
    DVLOG(3) << "AnimationStep callback forcing update due to texture queue "
                "size "
             << texture_queue_.size();
    notifier_->ForceUpdate();
  }
  if (texture_queue_.size() >= kQueueSizeToDropFrames) {
    DVLOG(3) << "AnimationStep callback dropping frame due to texture queue "
                "size "
             << texture_queue_.size();
    return;
  }

  ui::Layer* layer = display_root_window_->layer();
  if (!layer) {
    LOG(ERROR) << "Unable to find layer for the desktop window";
    return;
  }

  // TODO(kylechar): Ideally this would add `BlitRequest` to `request` so
  // readback happens directly into the final texture rather than making
  // an extra copy in CopyDesktopTextureToGpuBuffer().
  std::unique_ptr<viz::CopyOutputRequest> request =
      std::make_unique<viz::CopyOutputRequest>(
          viz::CopyOutputRequest::ResultFormat::RGBA,
          viz::CopyOutputRequest::ResultDestination::kNativeTextures,
          base::BindOnce(&ArcScreenCaptureSession::OnDesktopCaptured,
                         weak_ptr_factory_.GetWeakPtr()));
  // Clip the requested area to the desktop area. See b/118675936.
  gfx::Size desktop_size = display_root_window_->bounds().size();
  request->set_area(gfx::Rect(desktop_size));

  // Unconditionally set the scaling ratio, even if the two sizes are identical.
  // What may be identical here may not be identical further down when the scale
  // is transformed for the surface. Note that desktop_size is is not in
  // physical pixels, and a scale factor is applied to adjust to them.
  request->SetScaleRatio(
      gfx::Vector2d(desktop_size.width(), desktop_size.height()),
      gfx::Vector2d(size_.width(), size_.height()));

  // Ensure we get the result size we want, and not +/- one pixel due to
  // clamping or rounding.
  request->set_result_selection(gfx::Rect(size_));

  layer->RequestCopyOfOutput(std::move(request));
}

void ArcScreenCaptureSession::OnCompositingShuttingDown(
    ui::Compositor* compositor) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  compositor->RemoveAnimationObserver(this);
}

void ArcScreenCaptureSession::OnContextLost() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  Close();
}

void ArcScreenCaptureSession::OnWillRemoveDisplays(
    const display::Displays& removed_displays) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  bool removed = false;
  for (const auto& display : removed_displays) {
    removed |= (display.id() == display_id_);
  }
  if (removed) {
    Close();
  }
}

}  // namespace arc