File: buffer_unittest.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (761 lines) | stat: -rw-r--r-- 29,193 bytes parent folder | download
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/exo/buffer.h"

#include <GLES2/gl2extchromium.h>

#include "base/barrier_closure.h"
#include "base/functional/callback_helpers.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "cc/mojo_embedder/async_layer_tree_frame_sink.h"
#include "components/exo/shell_surface.h"
#include "components/exo/surface_tree_host.h"
#include "components/exo/test/exo_test_base.h"
#include "components/exo/test/exo_test_helper.h"
#include "components/exo/test/shell_surface_builder.h"
#include "components/exo/test/surface_tree_host_test_util.h"
#include "components/viz/test/test_in_process_context_provider.h"
#include "gpu/command_buffer/client/raster_interface.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/env.h"
#include "ui/compositor/compositor.h"
#include "ui/gfx/color_space.h"
#include "ui/gfx/gpu_fence_handle.h"
#include "ui/gfx/gpu_memory_buffer.h"

namespace exo {
namespace {

class BufferTest
    : public test::ExoTestBase,
      public testing::WithParamInterface<test::FrameSubmissionType> {
 public:
  BufferTest()
      : test::ExoTestBase(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {
    test::SetFrameSubmissionFeatureFlags(&feature_list_, GetParam());
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

base::RepeatingClosure CreateReleaseBufferClosure(
    int* release_buffer_call_count,
    base::RepeatingClosure closure) {
  return base::BindLambdaForTesting(
      [release_buffer_call_count, closure = std::move(closure)]() {
        if (release_buffer_call_count) {
          (*release_buffer_call_count)++;
        }
        closure.Run();
      });
}

base::OnceCallback<void(gfx::GpuFenceHandle)> CreateExplicitReleaseCallback(
    int* release_call_count,
    base::RepeatingClosure closure) {
  return base::BindLambdaForTesting(
      [release_call_count,
       closure = std::move(closure)](gfx::GpuFenceHandle release_fence) {
        if (release_call_count) {
          (*release_call_count)++;
        }
        closure.Run();
      });
}

void VerifySyncTokensInCompositorFrame(viz::CompositorFrame* frame) {
  std::vector<GLbyte*> sync_tokens;
  for (auto& resource : frame->resource_list)
    sync_tokens.push_back(resource.mailbox_holder.sync_token.GetData());
  gpu::raster::RasterInterface* ri =
      aura::Env::GetInstance()
          ->context_factory()
          ->SharedMainThreadRasterContextProvider()
          ->RasterInterface();
  ri->VerifySyncTokensCHROMIUM(sync_tokens.data(), sync_tokens.size());
}

viz::CompositorFrame CreateCompositorFrame(
    SurfaceTreeHost* surface_tree_host,
    const gfx::Rect& output_rect,
    const gfx::Rect& damage_rect,
    std::vector<viz::TransferableResource> resources) {
  viz::CompositorFrame frame;
  frame.metadata.begin_frame_ack.frame_id =
      viz::BeginFrameId(viz::BeginFrameArgs::kManualSourceId,
                        viz::BeginFrameArgs::kStartingFrameNumber);
  frame.metadata.begin_frame_ack.has_damage = true;
  frame.metadata.frame_token = surface_tree_host->GenerateNextFrameToken();
  frame.metadata.device_scale_factor = 1;
  auto pass = viz::CompositorRenderPass::Create();
  pass->SetNew(viz::CompositorRenderPassId{1}, output_rect, damage_rect,
               gfx::Transform());
  frame.render_pass_list.push_back(std::move(pass));
  frame.resource_list = std::move(resources);
  if (!frame.resource_list.empty()) {
    VerifySyncTokensInCompositorFrame(&frame);
  }
  return frame;
}

// Instantiate the values of frame submission types in the parameterized tests.
INSTANTIATE_TEST_SUITE_P(
    All,
    BufferTest,
    testing::Values(test::FrameSubmissionType::kNoReactive,
                    test::FrameSubmissionType::kReactive_NoAutoNeedsBeginFrame,
                    test::FrameSubmissionType::kReactive_AutoNeedsBeginFrame));

TEST_P(BufferTest, ReleaseCallback) {
  gfx::Size buffer_size(256, 256);
  auto buffer = std::make_unique<Buffer>(
      exo_test_helper()->CreateGpuMemoryBuffer(buffer_size));
  auto surface_tree_host = std::make_unique<SurfaceTreeHost>("BufferTest");
  LayerTreeFrameSinkHolder* frame_sink_holder =
      surface_tree_host->layer_tree_frame_sink_holder();

  // Remove wait time for efficiency.
  buffer->set_wait_for_release_delay_for_testing(base::TimeDelta());

  // Set the release callback.
  int release_call_count = 0;
  base::RunLoop run_loop_1;
  buffer->set_release_callback(CreateReleaseBufferClosure(
      &release_call_count, run_loop_1.QuitClosure()));

  buffer->OnAttach();
  viz::TransferableResource resource;
  // Produce a transferable resource for the contents of the buffer.
  int release_resource_count = 0;
  base::RunLoop run_loop_2;
  bool rv = buffer->ProduceTransferableResource(
      frame_sink_holder->resource_manager(), nullptr, false, &resource,
      gfx::ColorSpace::CreateSRGB(), nullptr,
      CreateExplicitReleaseCallback(&release_resource_count,
                                    run_loop_2.QuitClosure()));
  ASSERT_TRUE(rv);

  // Release buffer.
  std::vector<viz::ReturnedResource> resources;
  resources.emplace_back(resource.id, resource.mailbox_holder.sync_token,
                         /*release_fence=*/gfx::GpuFenceHandle(),
                         /*count=*/0, /*lost=*/false);
  frame_sink_holder->ReclaimResources(std::move(resources));

  run_loop_2.Run();

  ASSERT_EQ(release_call_count, 0);
  // The resource should have been released even if the whole buffer hasn't.
  ASSERT_EQ(release_resource_count, 1);

  buffer->OnDetach();

  run_loop_1.Run();
  // Release() should have been called exactly once.
  ASSERT_EQ(release_call_count, 1);
}

TEST_P(BufferTest, SolidColorReleaseCallback) {
  gfx::Size buffer_size(256, 256);
  auto buffer = std::make_unique<SolidColorBuffer>(SkColors::kRed, buffer_size);
  auto surface_tree_host = std::make_unique<SurfaceTreeHost>("BufferTest");
  LayerTreeFrameSinkHolder* frame_sink_holder =
      surface_tree_host->layer_tree_frame_sink_holder();

  // Remove wait time for efficiency.
  buffer->set_wait_for_release_delay_for_testing(base::TimeDelta());

  // Set the release callback.
  int release_call_count = 0;
  base::RunLoop run_loop;
  buffer->set_release_callback(
      CreateReleaseBufferClosure(&release_call_count, run_loop.QuitClosure()));

  buffer->OnAttach();
  viz::TransferableResource resource;
  // Produce a transferable resource for the contents of the buffer.
  int release_resource_count = 0;
  bool rv = buffer->ProduceTransferableResource(
      frame_sink_holder->resource_manager(), nullptr, false, &resource,
      gfx::ColorSpace::CreateSRGB(), nullptr,
      CreateExplicitReleaseCallback(&release_resource_count,
                                    base::DoNothing()));
  // Solid color buffer is immediately released after commit.
  EXPECT_EQ(release_resource_count, 1);
  EXPECT_FALSE(rv);

  // Release buffer.
  std::vector<viz::ReturnedResource> resources;
  resources.emplace_back(resource.id, resource.mailbox_holder.sync_token,
                         /*release_fence=*/gfx::GpuFenceHandle(),
                         /*count=*/0, /*lost=*/false);
  frame_sink_holder->ReclaimResources(std::move(resources));

  // We expect that Release() is not called, no matter whether we have a wait
  // here or how long the wait is. An arbitrary time period is added here so
  // that if the event mistakenly happens, it is more likely to find out.
  task_environment()->FastForwardBy(base::Seconds(1));

  EXPECT_EQ(release_call_count, 0);

  buffer->OnDetach();

  run_loop.Run();
  // Release() should have been called exactly once.
  EXPECT_EQ(release_call_count, 1);
}

TEST_P(BufferTest, IsLost) {
  gfx::Size buffer_size(256, 256);
  auto buffer = std::make_unique<Buffer>(
      exo_test_helper()->CreateGpuMemoryBuffer(buffer_size));
  auto surface_tree_host = std::make_unique<SurfaceTreeHost>("BufferTest");
  LayerTreeFrameSinkHolder* frame_sink_holder =
      surface_tree_host->layer_tree_frame_sink_holder();

  buffer->OnAttach();
  {
    // Acquire a texture transferable resource for the contents of the buffer.
    viz::TransferableResource resource;
    base::RunLoop run_loop_1;
    bool rv = buffer->ProduceTransferableResource(
        frame_sink_holder->resource_manager(), nullptr, false, &resource,
        gfx::ColorSpace::CreateSRGB(), nullptr,
        CreateExplicitReleaseCallback(nullptr, run_loop_1.QuitClosure()));
    ASSERT_TRUE(rv);

    scoped_refptr<viz::RasterContextProvider> context_provider =
        aura::Env::GetInstance()
            ->context_factory()
            ->SharedMainThreadRasterContextProvider();
    if (context_provider) {
      gpu::raster::RasterInterface* ri = context_provider->RasterInterface();
      ri->LoseContextCHROMIUM(GL_GUILTY_CONTEXT_RESET_ARB,
                              GL_INNOCENT_CONTEXT_RESET_ARB);
    }

    // Release buffer.
    std::vector<viz::ReturnedResource> resources;
    resources.emplace_back(resource.id, gpu::SyncToken(),
                           /*release_fence=*/gfx::GpuFenceHandle(),
                           /*count=*/0, /*lost=*/true);
    frame_sink_holder->ReclaimResources(std::move(resources));
    run_loop_1.Run();
  }

  {
    // Producing a new texture transferable resource for the contents of the
    // buffer.
    viz::TransferableResource new_resource;
    base::RunLoop run_loop_2;
    bool rv = buffer->ProduceTransferableResource(
        frame_sink_holder->resource_manager(), nullptr, false, &new_resource,
        gfx::ColorSpace::CreateSRGB(), nullptr,
        CreateExplicitReleaseCallback(nullptr, run_loop_2.QuitClosure()));
    ASSERT_TRUE(rv);
    buffer->OnDetach();

    std::vector<viz::ReturnedResource> resources2;
    resources2.emplace_back(new_resource.id, gpu::SyncToken(),
                            /*release_fence=*/gfx::GpuFenceHandle(),
                            /*count=*/0, /*lost=*/false);
    frame_sink_holder->ReclaimResources(std::move(resources2));
    run_loop_2.Run();
  }
}

// Buffer::Texture::OnLostResources is called when the gpu crashes. This test
// verifies that the Texture is collected properly in such event.
TEST_P(BufferTest, OnLostResources) {
  // Create a Buffer and use it to produce a Texture.
  constexpr gfx::Size buffer_size(256, 256);
  auto buffer = std::make_unique<Buffer>(
      exo_test_helper()->CreateGpuMemoryBuffer(buffer_size));
  auto surface_tree_host = std::make_unique<SurfaceTreeHost>("BufferTest");
  LayerTreeFrameSinkHolder* frame_sink_holder =
      surface_tree_host->layer_tree_frame_sink_holder();

  buffer->OnAttach();
  // Acquire a texture transferable resource for the contents of the buffer.
  viz::TransferableResource resource;
  bool rv = buffer->ProduceTransferableResource(
      frame_sink_holder->resource_manager(), nullptr, false, &resource,
      gfx::ColorSpace::CreateSRGB(), nullptr, base::DoNothing());
  ASSERT_TRUE(rv);

  viz::RasterContextProvider* context_provider =
      aura::Env::GetInstance()
          ->context_factory()
          ->SharedMainThreadRasterContextProvider()
          .get();
  static_cast<viz::TestInProcessContextProvider*>(context_provider)
      ->SendOnContextLost();
}

TEST_P(BufferTest, SurfaceTreeHostDestruction) {
  gfx::Size buffer_size(256, 256);

  // We need to setup shell surface and commit the surface, which properly
  // registers frame sink hierarchy and attaches begin frame source. Otherwise
  // OnBeginFrame requests won't be sent.
  auto shell_surface =
      test::ShellSurfaceBuilder(buffer_size).BuildShellSurface();
  test::WaitForLastFrameAck(shell_surface.get());

  LayerTreeFrameSinkHolder* frame_sink_holder =
      shell_surface->layer_tree_frame_sink_holder();

  auto buffer = std::make_unique<Buffer>(
      exo_test_helper()->CreateGpuMemoryBuffer(buffer_size));

  // Remove wait time for efficiency.
  buffer->set_wait_for_release_delay_for_testing(base::TimeDelta());

  int release_call_count = 0;

  base::RunLoop run_loop;
  auto combined_quit_closure = BarrierClosure(2, run_loop.QuitClosure());

  buffer->set_release_callback(
      CreateReleaseBufferClosure(&release_call_count, combined_quit_closure));

  buffer->OnAttach();
  viz::TransferableResource resource;
  // Produce a transferable resource for the contents of the buffer.
  int release_resource_count = 0;
  bool rv = buffer->ProduceTransferableResource(
      frame_sink_holder->resource_manager(), nullptr, false, &resource,
      gfx::ColorSpace::CreateSRGB(), nullptr,
      CreateExplicitReleaseCallback(&release_resource_count,
                                    combined_quit_closure));
  ASSERT_TRUE(rv);

  // Submit frame with resource.
  shell_surface->SubmitCompositorFrameForTesting(
      CreateCompositorFrame(shell_surface.get(), gfx::Rect(buffer_size),
                            gfx::Rect(buffer_size), {resource}));
  test::WaitForLastFrameAck(shell_surface.get());

  buffer->OnDetach();

  // We expect that the buffer and resource should not be released yet, no
  // matter whether we have a wait here or how long the wait is. An arbitrary
  // time period is added here so that if the event mistakenly happens, it is
  // more likely to find out.
  task_environment()->FastForwardBy(base::Seconds(1));
  ASSERT_EQ(release_call_count, 0);
  ASSERT_EQ(release_resource_count, 0);

  shell_surface.reset();
  run_loop.Run();
  ASSERT_EQ(release_call_count, 1);
  ASSERT_EQ(release_resource_count, 1);
}

TEST_P(BufferTest, SurfaceTreeHostLastFrame) {
  gfx::Size buffer_size(256, 256);

  // We need to setup shell surface and commit the surface, which properly
  // registers frame sink hierarchy and attaches begin frame source. Otherwise
  // OnBeginFrame requests won't be sent.
  auto shell_surface =
      test::ShellSurfaceBuilder(buffer_size).BuildShellSurface();
  test::WaitForLastFrameAck(shell_surface.get());

  LayerTreeFrameSinkHolder* frame_sink_holder =
      shell_surface->layer_tree_frame_sink_holder();

  auto buffer = std::make_unique<Buffer>(
      exo_test_helper()->CreateGpuMemoryBuffer(buffer_size));

  // Remove wait time for efficiency.
  buffer->set_wait_for_release_delay_for_testing(base::TimeDelta());

  int release_call_count = 0;

  base::RunLoop run_loop;
  auto combined_quit_closure = BarrierClosure(2, run_loop.QuitClosure());

  buffer->set_release_callback(
      CreateReleaseBufferClosure(&release_call_count, combined_quit_closure));

  buffer->OnAttach();
  viz::TransferableResource resource;
  // Produce a transferable resource for the contents of the buffer.
  int release_resource_count = 0;
  bool rv = buffer->ProduceTransferableResource(
      frame_sink_holder->resource_manager(), nullptr, false, &resource,
      gfx::ColorSpace::CreateSRGB(), nullptr,
      CreateExplicitReleaseCallback(&release_resource_count,
                                    combined_quit_closure));
  ASSERT_TRUE(rv);

  // Submit frame with resource.
  {
    shell_surface->SubmitCompositorFrameForTesting(
        CreateCompositorFrame(shell_surface.get(), gfx::Rect(buffer_size),
                              gfx::Rect(buffer_size), {resource}));
    test::WaitForLastFrameAck(shell_surface.get());

    // Try to release buffer in last frame. This can happen during a resize
    // when frame sink id changes.
    std::vector<viz::ReturnedResource> resources;
    resources.emplace_back(resource.id, resource.mailbox_holder.sync_token,
                           /*release_fence=*/gfx::GpuFenceHandle(),
                           /*count=*/0, /*lost=*/false);
    frame_sink_holder->ReclaimResources(std::move(resources));
  }

  buffer->OnDetach();

  // We expect that the buffer and resource should not be released yet, no
  // matter whether we have a wait here or how long the wait is. An arbitrary
  // time period is added here so that if the event mistakenly happens, it is
  // more likely to find out.
  task_environment()->FastForwardBy(base::Seconds(1));
  // Release() should not have been called as resource is used by last frame.
  ASSERT_EQ(release_call_count, 0);
  ASSERT_EQ(release_resource_count, 0);

  // Submit frame without resource. This should cause buffer to be released.
  shell_surface->SubmitCompositorFrameForTesting(CreateCompositorFrame(
      shell_surface.get(), gfx::Rect(buffer_size), gfx::Rect(buffer_size), {}));

  run_loop.Run();
  // Release() should have been called exactly once.
  ASSERT_EQ(release_call_count, 1);
  ASSERT_EQ(release_resource_count, 1);
}

// Tests that only apply if ExoReactiveFrameSubmission is enabled.
class ReactiveFrameSubmissionBufferTest
    : public test::ExoTestBase,
      public testing::WithParamInterface<test::FrameSubmissionType> {
 public:
  ReactiveFrameSubmissionBufferTest()
      : test::ExoTestBase(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {
    test::SetFrameSubmissionFeatureFlags(&feature_list_, GetParam());
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

class TestLayerTreeFrameSinkHolder : public LayerTreeFrameSinkHolder {
 public:
  TestLayerTreeFrameSinkHolder(
      SurfaceTreeHost* surface_tree_host,
      std::unique_ptr<cc::mojo_embedder::AsyncLayerTreeFrameSink> frame_sink)
      : LayerTreeFrameSinkHolder(surface_tree_host, std::move(frame_sink)) {}
  ~TestLayerTreeFrameSinkHolder() override = default;

  using PreReclaimCallback =
      base::RepeatingCallback<void(const std::vector<viz::ReturnedResource>&)>;
  void set_pre_reclaim_callback(PreReclaimCallback callback) {
    pre_reclaim_callback_ = std::move(callback);
  }

  void set_post_reclaim_callback(base::RepeatingClosure callback) {
    post_reclaim_callback_ = std::move(callback);
  }

  void ReclaimResources(std::vector<viz::ReturnedResource> resources) override {
    if (pre_reclaim_callback_) {
      pre_reclaim_callback_.Run(resources);
    }

    LayerTreeFrameSinkHolder::ReclaimResources(std::move(resources));

    if (post_reclaim_callback_) {
      post_reclaim_callback_.Run();
    }
  }

 private:
  PreReclaimCallback pre_reclaim_callback_;
  base::RepeatingClosure post_reclaim_callback_;
};

// Instantiate the values of frame submission types in the parameterized tests.
INSTANTIATE_TEST_SUITE_P(
    All,
    ReactiveFrameSubmissionBufferTest,
    testing::Values(test::FrameSubmissionType::kReactive_NoAutoNeedsBeginFrame,
                    test::FrameSubmissionType::kReactive_AutoNeedsBeginFrame));

TEST_P(ReactiveFrameSubmissionBufferTest,
       SurfaceTreeHostNotReclaimCachedFrameResources) {
  gfx::Size buffer_size(256, 256);

  auto shell_surface =
      test::ShellSurfaceBuilder(buffer_size).SetNoCommit().BuildShellSurface();
  test::SetLayerTreeFrameSinkHolderFactory<TestLayerTreeFrameSinkHolder>(
      shell_surface.get());
  shell_surface->root_surface()->Commit();
  test::WaitForLastFrameAck(shell_surface.get());

  TestLayerTreeFrameSinkHolder* frame_sink_holder =
      static_cast<TestLayerTreeFrameSinkHolder*>(
          shell_surface->layer_tree_frame_sink_holder());

  auto buffer = std::make_unique<Buffer>(
      exo_test_helper()->CreateGpuMemoryBuffer(buffer_size));

  // Remove wait time for efficiency.
  buffer->set_wait_for_release_delay_for_testing(base::TimeDelta());

  int release_call_count = 0;

  base::RunLoop run_loop1;
  auto combined_quit_closure = BarrierClosure(2, run_loop1.QuitClosure());

  buffer->set_release_callback(
      CreateReleaseBufferClosure(&release_call_count, combined_quit_closure));

  buffer->OnAttach();
  viz::TransferableResource resource;
  // Produce a transferable resource for the contents of the buffer.
  int release_resource_count = 0;
  bool rv = buffer->ProduceTransferableResource(
      frame_sink_holder->resource_manager(), nullptr, false, &resource,
      gfx::ColorSpace::CreateSRGB(), nullptr,
      CreateExplicitReleaseCallback(&release_resource_count,
                                    combined_quit_closure));
  ASSERT_TRUE(rv);

  // Submit frame with `resource`.
  shell_surface->SubmitCompositorFrameForTesting(
      CreateCompositorFrame(shell_surface.get(), gfx::Rect(buffer_size),
                            gfx::Rect(buffer_size), {resource}));
  test::WaitForLastFrameAck(shell_surface.get());

  base::RunLoop run_loop2;
  // Set a callback that will be called when the remote side notify
  // ReclaimResources for `resource`.
  frame_sink_holder->set_pre_reclaim_callback(base::BindLambdaForTesting(
      [&](const std::vector<viz::ReturnedResource>& resources) {
        // Skip if it is not a notification for reclaiming `resource`.
        if (!base::Contains(
                resources, resource.id,
                [](const viz::ReturnedResource& r) { return r.id; })) {
          return;
        }

        run_loop2.Quit();
        // Make sure that this callback is only used once.
        frame_sink_holder->set_pre_reclaim_callback({});

        frame_sink_holder->ClearPendingBeginFramesForTesting();
        // Cause a frame with `resource` is cached. This should hold off
        // reclaming `resource`.
        shell_surface->SubmitCompositorFrameForTesting(
            CreateCompositorFrame(shell_surface.get(), gfx::Rect(buffer_size),
                                  gfx::Rect(buffer_size), {resource}));
      }));

  // Submit a new frame without resource to cause the remote side to stop using
  // `resource` and notify ReclaimResources. The callback set by
  // set_pre_reclaim_callback() above should be run as a result.
  shell_surface->SubmitCompositorFrameForTesting(CreateCompositorFrame(
      shell_surface.get(), gfx::Rect(buffer_size), gfx::Rect(buffer_size), {}));
  run_loop2.Run();

  // Ensure the cached frame is submitted.
  test::WaitForLastFrameAck(shell_surface.get());

  // We expect that Release() is not called, no matter whether we have a wait
  // here or how long the wait is. An arbitrary time period is added here so
  // that if the event mistakenly happens, it is more likely to find out.
  task_environment()->FastForwardBy(base::Seconds(1));

  // Release() should not have been called.
  ASSERT_EQ(release_call_count, 0);
  ASSERT_EQ(release_resource_count, 0);

  buffer->OnDetach();

  // Submit a new frame without resource. This will cause buffer to be released.
  shell_surface->SubmitCompositorFrameForTesting(CreateCompositorFrame(
      shell_surface.get(), gfx::Rect(buffer_size), gfx::Rect(buffer_size), {}));

  run_loop1.Run();
  // Release() should have been called exactly once.
  ASSERT_EQ(release_call_count, 1);
  ASSERT_EQ(release_resource_count, 1);
}

TEST_P(ReactiveFrameSubmissionBufferTest,
       SurfaceTreeHostDiscardFrameNotReclaimNewFrameResources) {
  gfx::Size buffer_size(256, 256);

  auto shell_surface =
      test::ShellSurfaceBuilder(buffer_size).BuildShellSurface();
  test::WaitForLastFrameAck(shell_surface.get());

  LayerTreeFrameSinkHolder* frame_sink_holder =
      shell_surface->layer_tree_frame_sink_holder();

  auto buffer = std::make_unique<Buffer>(
      exo_test_helper()->CreateGpuMemoryBuffer(buffer_size));

  // Remove wait time for efficiency.
  buffer->set_wait_for_release_delay_for_testing(base::TimeDelta());

  int release_call_count = 0;

  base::RunLoop run_loop;
  auto combined_quit_closure = BarrierClosure(2, run_loop.QuitClosure());

  buffer->set_release_callback(
      CreateReleaseBufferClosure(&release_call_count, combined_quit_closure));

  buffer->OnAttach();
  viz::TransferableResource resource;
  // Produce a transferable resource for the contents of the buffer.
  int release_resource_count = 0;
  bool rv = buffer->ProduceTransferableResource(
      frame_sink_holder->resource_manager(), nullptr, false, &resource,
      gfx::ColorSpace::CreateSRGB(), nullptr,
      CreateExplicitReleaseCallback(&release_resource_count,
                                    combined_quit_closure));
  ASSERT_TRUE(rv);

  frame_sink_holder->ClearPendingBeginFramesForTesting();

  // Submit a frame with `resource`, which will be cached.
  shell_surface->SubmitCompositorFrameForTesting(
      CreateCompositorFrame(shell_surface.get(), gfx::Rect(buffer_size),
                            gfx::Rect(buffer_size), {resource}));

  // Submit another frame with `resource`. It will cause the previously cached
  // frame to be evicted.
  shell_surface->SubmitCompositorFrameForTesting(
      CreateCompositorFrame(shell_surface.get(), gfx::Rect(buffer_size),
                            gfx::Rect(buffer_size), {resource}));

  buffer->OnDetach();

  // Ensure the cached frame is submitted.
  test::WaitForLastFrameAck(shell_surface.get());

  // We expect that Release() is not called, no matter whether we have a wait
  // here or how long the wait is. An arbitrary time period is added here so
  // that if the event mistakenly happens, it is more likely to find out.
  task_environment()->FastForwardBy(base::Seconds(1));

  // Release() should not have been called.
  ASSERT_EQ(release_call_count, 0);
  ASSERT_EQ(release_resource_count, 0);

  // Submit another frame without resource.
  shell_surface->SubmitCompositorFrameForTesting(CreateCompositorFrame(
      shell_surface.get(), gfx::Rect(buffer_size), gfx::Rect(buffer_size), {}));
  test::WaitForLastFrameAck(shell_surface.get());

  run_loop.Run();

  // Release() should have been called exactly once.
  ASSERT_EQ(release_call_count, 1);
  ASSERT_EQ(release_resource_count, 1);
}

TEST_P(ReactiveFrameSubmissionBufferTest,
       SurfaceTreeHostDiscardFrameNotReclaimInUseResources) {
  gfx::Size buffer_size(256, 256);

  auto shell_surface =
      test::ShellSurfaceBuilder(buffer_size).SetNoCommit().BuildShellSurface();
  test::SetLayerTreeFrameSinkHolderFactory<TestLayerTreeFrameSinkHolder>(
      shell_surface.get());
  shell_surface->root_surface()->Commit();
  test::WaitForLastFrameAck(shell_surface.get());

  TestLayerTreeFrameSinkHolder* frame_sink_holder =
      static_cast<TestLayerTreeFrameSinkHolder*>(
          shell_surface->layer_tree_frame_sink_holder());

  auto buffer = std::make_unique<Buffer>(
      exo_test_helper()->CreateGpuMemoryBuffer(buffer_size));

  // Remove wait time for efficiency.
  buffer->set_wait_for_release_delay_for_testing(base::TimeDelta());

  int release_call_count = 0;

  base::RunLoop run_loop1;
  auto combined_quit_closure = BarrierClosure(2, run_loop1.QuitClosure());

  buffer->set_release_callback(
      CreateReleaseBufferClosure(&release_call_count, combined_quit_closure));

  buffer->OnAttach();
  viz::TransferableResource resource;
  // Produce a transferable resource for the contents of the buffer.
  int release_resource_count = 0;
  bool rv = buffer->ProduceTransferableResource(
      frame_sink_holder->resource_manager(), nullptr, false, &resource,
      gfx::ColorSpace::CreateSRGB(), nullptr,
      CreateExplicitReleaseCallback(&release_resource_count,
                                    combined_quit_closure));
  ASSERT_TRUE(rv);

  // Submit frame with `resource`.
  shell_surface->SubmitCompositorFrameForTesting(
      CreateCompositorFrame(shell_surface.get(), gfx::Rect(buffer_size),
                            gfx::Rect(buffer_size), {resource}));
  test::WaitForLastFrameAck(shell_surface.get());

  base::RunLoop run_loop2;
  // Set a callback that will be called when the remote side notify
  // ReclaimResources for `resource`.
  frame_sink_holder->set_pre_reclaim_callback(base::BindLambdaForTesting(
      [&](const std::vector<viz::ReturnedResource>& resources) {
        // Skip if it is not a notification for reclaiming `resource`.
        if (!base::Contains(
                resources, resource.id,
                [](const viz::ReturnedResource& r) { return r.id; })) {
          return;
        }

        run_loop2.Quit();
        // Make sure that this callback is only used once.
        frame_sink_holder->set_pre_reclaim_callback({});

        // The evicted cached frame with `resource` shouldn't have caused
        // Release() to be called.
        ASSERT_EQ(release_call_count, 0);
        ASSERT_EQ(release_resource_count, 0);
      }));

  frame_sink_holder->ClearPendingBeginFramesForTesting();

  // Cause a frame with `resource` is cached.
  shell_surface->SubmitCompositorFrameForTesting(
      CreateCompositorFrame(shell_surface.get(), gfx::Rect(buffer_size),
                            gfx::Rect(buffer_size), {resource}));

  buffer->OnDetach();

  // Submit a new frame without resource to evict the previously cached frame.
  // It shouldn't cause `resource` to be reclaimed because it is still in use at
  // the remote side.
  shell_surface->SubmitCompositorFrameForTesting(CreateCompositorFrame(
      shell_surface.get(), gfx::Rect(buffer_size), gfx::Rect(buffer_size), {}));

  // Wait for the remote site to notify ReclaimResources for `resource`.
  run_loop2.Run();

  run_loop1.Run();

  // Release() should have been called exactly once.
  ASSERT_EQ(release_call_count, 1);
  ASSERT_EQ(release_resource_count, 1);
}

}  // namespace
}  // namespace exo