File: audio_decoder_broker_test.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (387 lines) | stat: -rw-r--r-- 15,106 bytes parent folder | download | duplicates (5)
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/webcodecs/audio_decoder_broker.h"

#include <memory>
#include <optional>
#include <vector>

#include "base/files/file_util.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "media/base/audio_codecs.h"
#include "media/base/channel_layout.h"
#include "media/base/decoder_buffer.h"
#include "media/base/decoder_status.h"
#include "media/base/media_util.h"
#include "media/base/mock_filters.h"
#include "media/base/sample_format.h"
#include "media/base/test_data_util.h"
#include "media/base/test_helpers.h"
#include "media/mojo/buildflags.h"
#include "media/mojo/mojom/audio_decoder.mojom.h"
#include "media/mojo/mojom/interface_factory.mojom.h"
#include "media/mojo/services/interface_factory_impl.h"
#include "media/mojo/services/mojo_audio_decoder_service.h"
#include "media/mojo/services/mojo_cdm_service_context.h"
#include "media/mojo/services/mojo_media_client.h"
#include "mojo/public/cpp/bindings/unique_receiver_set.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/platform/testing/task_environment.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"

using ::testing::_;
using ::testing::Return;

namespace blink {

namespace {

// Constants to specify the type of audio data used.
constexpr media::AudioCodec kCodec = media::AudioCodec::kVorbis;
constexpr media::SampleFormat kSampleFormat = media::kSampleFormatPlanarF32;
constexpr media::ChannelLayout kChannelLayout = media::CHANNEL_LAYOUT_STEREO;
constexpr int kChannels = 2;
constexpr int kSamplesPerSecond = 44100;
constexpr int kInputFramesChunk = 256;

// FakeAudioDecoder is very agreeable.
// - any configuration is supported
// - all decodes immediately succeed
// - non EOS decodes produce an output
// - reset immediately succeeds.
class FakeAudioDecoder : public media::MockAudioDecoder {
 public:
  FakeAudioDecoder() : MockAudioDecoder() {}
  ~FakeAudioDecoder() override = default;

  void Initialize(const media::AudioDecoderConfig& config,
                  media::CdmContext* cdm_context,
                  InitCB init_cb,
                  const OutputCB& output_cb,
                  const media::WaitingCB& waiting_cb) override {
    output_cb_ = output_cb;
    std::move(init_cb).Run(media::DecoderStatus::Codes::kOk);
  }

  void Decode(scoped_refptr<media::DecoderBuffer> buffer,
              DecodeCB done_cb) override {
    DCHECK(output_cb_);

    std::move(done_cb).Run(media::DecoderStatus::Codes::kOk);

    if (!buffer->end_of_stream()) {
      output_cb_.Run(MakeAudioBuffer(kSampleFormat, kChannelLayout, kChannels,
                                     kSamplesPerSecond, 1.0f, 0.0f,
                                     kInputFramesChunk, buffer->timestamp()));
    }
  }

  void Reset(base::OnceClosure closure) override { std::move(closure).Run(); }

 private:
  OutputCB output_cb_;
};

class FakeMojoMediaClient : public media::MojoMediaClient {
 public:
  FakeMojoMediaClient() = default;
  FakeMojoMediaClient(const FakeMojoMediaClient&) = delete;
  FakeMojoMediaClient& operator=(const FakeMojoMediaClient&) = delete;

  std::unique_ptr<media::AudioDecoder> CreateAudioDecoder(
      scoped_refptr<base::SequencedTaskRunner> task_runner,
      std::unique_ptr<media::MediaLog> media_log) override {
    return std::make_unique<FakeAudioDecoder>();
  }
};

// Other end of remote InterfaceFactory requested by AudioDecoderBroker. Used
// to create our (fake) media::mojom::AudioDecoder.
class FakeInterfaceFactory : public media::mojom::InterfaceFactory {
 public:
  FakeInterfaceFactory() = default;
  ~FakeInterfaceFactory() override = default;

  void BindRequest(mojo::ScopedMessagePipeHandle handle) {
    receiver_.Bind(mojo::PendingReceiver<media::mojom::InterfaceFactory>(
        std::move(handle)));
    receiver_.set_disconnect_handler(WTF::BindOnce(
        &FakeInterfaceFactory::OnConnectionError, base::Unretained(this)));
  }

  void OnConnectionError() { receiver_.reset(); }

  // Implement this one interface from mojom::InterfaceFactory. Using the real
  // MojoAudioDecoderService allows us to reuse buffer conversion code. The
  // FakeMojoMediaClient will create a FakeGpuAudioDecoder.
  void CreateAudioDecoder(
      mojo::PendingReceiver<media::mojom::AudioDecoder> receiver) override {
    audio_decoder_receivers_.Add(
        std::make_unique<media::MojoAudioDecoderService>(
            &mojo_media_client_, &cdm_service_context_,
            base::SingleThreadTaskRunner::GetCurrentDefault()),
        std::move(receiver));
  }
  void CreateAudioEncoder(
      mojo::PendingReceiver<media::mojom::AudioEncoder> receiver) override {}

  // Stub out other mojom::InterfaceFactory interfaces.
  void CreateVideoDecoder(
      mojo::PendingReceiver<media::mojom::VideoDecoder> receiver,
      mojo::PendingRemote<media::mojom::VideoDecoder> dst_video_decoder)
      override {}
#if BUILDFLAG(ALLOW_OOP_VIDEO_DECODER)
  void CreateVideoDecoderWithTracker(
      mojo::PendingReceiver<media::mojom::VideoDecoder> receiver,
      mojo::PendingRemote<media::mojom::VideoDecoderTracker> tracker) override {
  }
#endif  // BUILDFLAG(ALLOW_OOP_VIDEO_DECODER)
  void CreateDefaultRenderer(
      const std::string& audio_device_id,
      mojo::PendingReceiver<media::mojom::Renderer> receiver) override {}
#if BUILDFLAG(ENABLE_CAST_RENDERER)
  void CreateCastRenderer(
      const base::UnguessableToken& overlay_plane_id,
      mojo::PendingReceiver<media::mojom::Renderer> receiver) override {}
#endif
#if BUILDFLAG(IS_ANDROID)
  void CreateFlingingRenderer(
      const std::string& presentation_id,
      mojo::PendingRemote<media::mojom::FlingingRendererClientExtension>
          client_extension,
      mojo::PendingReceiver<media::mojom::Renderer> receiver) override {}
#endif  // BUILDFLAG(IS_ANDROID)
  void CreateCdm(const media::CdmConfig& cdm_config,
                 CreateCdmCallback callback) override {
    std::move(callback).Run(mojo::NullRemote(), nullptr,
                            media::CreateCdmStatus::kCdmNotSupported);
  }
#if BUILDFLAG(IS_WIN)
  void CreateMediaFoundationRenderer(
      mojo::PendingRemote<media::mojom::MediaLog> media_log_remote,
      mojo::PendingReceiver<media::mojom::Renderer> receiver,
      mojo::PendingReceiver<media::mojom::MediaFoundationRendererExtension>
          renderer_extension_receiver,
      mojo::PendingRemote<
          ::media::mojom::MediaFoundationRendererClientExtension>
          client_extension_remote) override {}
#endif  // BUILDFLAG(IS_WIN)

 private:
  FakeMojoMediaClient mojo_media_client_;
  media::MojoCdmServiceContext cdm_service_context_;
  mojo::Receiver<media::mojom::InterfaceFactory> receiver_{this};
  mojo::UniqueReceiverSet<media::mojom::AudioDecoder> audio_decoder_receivers_;
};

}  // namespace

class AudioDecoderBrokerTest : public testing::Test {
 public:
  AudioDecoderBrokerTest() = default;
  ~AudioDecoderBrokerTest() override = default;

  void OnInitWithClosure(base::RepeatingClosure done_cb,
                         media::DecoderStatus status) {
    OnInit(status);
    done_cb.Run();
  }
  void OnDecodeDoneWithClosure(base::RepeatingClosure done_cb,
                               media::DecoderStatus status) {
    OnDecodeDone(std::move(status));
    done_cb.Run();
  }

  void OnResetDoneWithClosure(base::RepeatingClosure done_cb) {
    OnResetDone();
    done_cb.Run();
  }

  MOCK_METHOD1(OnInit, void(media::DecoderStatus status));
  MOCK_METHOD1(OnDecodeDone, void(media::DecoderStatus));
  MOCK_METHOD0(OnResetDone, void());

  void OnOutput(scoped_refptr<media::AudioBuffer> buffer) {
    output_buffers_.push_back(std::move(buffer));
  }

  void SetupMojo(ExecutionContext& execution_context) {
    // Register FakeInterfaceFactory as impl for media::mojom::InterfaceFactory
    // required by MojoAudioDecoder. The factory will vend FakeGpuAudioDecoders
    // that simulate gpu-accelerated decode.
    interface_factory_ = std::make_unique<FakeInterfaceFactory>();
    EXPECT_TRUE(
        Platform::Current()->GetBrowserInterfaceBroker()->SetBinderForTesting(
            media::mojom::InterfaceFactory::Name_,
            WTF::BindRepeating(&FakeInterfaceFactory::BindRequest,
                               base::Unretained(interface_factory_.get()))));
  }

  void ConstructDecoder(ExecutionContext& execution_context) {
    decoder_broker_ = std::make_unique<AudioDecoderBroker>(&null_media_log_,
                                                           execution_context);
  }

  void InitializeDecoder(media::AudioDecoderConfig config) {
    base::RunLoop run_loop;
    EXPECT_CALL(*this, OnInit(media::SameStatusCode(media::DecoderStatus(
                           media::DecoderStatus::Codes::kOk))));
    decoder_broker_->Initialize(
        config, nullptr /* cdm_context */,
        WTF::BindOnce(&AudioDecoderBrokerTest::OnInitWithClosure,
                      WTF::Unretained(this), run_loop.QuitClosure()),
        WTF::BindRepeating(&AudioDecoderBrokerTest::OnOutput,
                           WTF::Unretained(this)),
        media::WaitingCB());
    run_loop.Run();
    testing::Mock::VerifyAndClearExpectations(this);
  }

  void DecodeBuffer(scoped_refptr<media::DecoderBuffer> buffer,
                    media::DecoderStatus::Codes expected_status =
                        media::DecoderStatus::Codes::kOk) {
    base::RunLoop run_loop;
    EXPECT_CALL(*this, OnDecodeDone(HasStatusCode(expected_status)));
    decoder_broker_->Decode(
        buffer, WTF::BindOnce(&AudioDecoderBrokerTest::OnDecodeDoneWithClosure,
                              WTF::Unretained(this), run_loop.QuitClosure()));
    run_loop.Run();
    testing::Mock::VerifyAndClearExpectations(this);
  }

  void ResetDecoder() {
    base::RunLoop run_loop;
    EXPECT_CALL(*this, OnResetDone());
    decoder_broker_->Reset(
        WTF::BindOnce(&AudioDecoderBrokerTest::OnResetDoneWithClosure,
                      WTF::Unretained(this), run_loop.QuitClosure()));
    run_loop.Run();
    testing::Mock::VerifyAndClearExpectations(this);
  }

  media::AudioDecoderType GetDecoderType() {
    return decoder_broker_->GetDecoderType();
  }

  bool IsPlatformDecoder() { return decoder_broker_->IsPlatformDecoder(); }
  bool SupportsDecryption() { return decoder_broker_->SupportsDecryption(); }

 protected:
  test::TaskEnvironment task_environment_;
  media::NullMediaLog null_media_log_;
  std::unique_ptr<AudioDecoderBroker> decoder_broker_;
  std::vector<scoped_refptr<media::AudioBuffer>> output_buffers_;
  std::unique_ptr<FakeInterfaceFactory> interface_factory_;
};

TEST_F(AudioDecoderBrokerTest, Decode_Uninitialized) {
  V8TestingScope v8_scope;

  ConstructDecoder(*v8_scope.GetExecutionContext());
  EXPECT_EQ(GetDecoderType(), media::AudioDecoderType::kBroker);

  // No call to Initialize. Other APIs should fail gracefully.

  DecodeBuffer(media::ReadTestDataFile("vorbis-packet-0"),
               media::DecoderStatus::Codes::kNotInitialized);
  DecodeBuffer(media::DecoderBuffer::CreateEOSBuffer(),
               media::DecoderStatus::Codes::kNotInitialized);
  ASSERT_EQ(0U, output_buffers_.size());

  ResetDecoder();
}

media::AudioDecoderConfig MakeVorbisConfig() {
  std::string extradata_name = "vorbis-extradata";
  base::FilePath extradata_path = media::GetTestDataFilePath(extradata_name);
  std::optional<int64_t> tmp = base::GetFileSize(extradata_path);
  CHECK(tmp.has_value()) << "Failed to get file size for '" << extradata_name
                         << "'";
  int file_size = base::checked_cast<int>(tmp.value());
  std::vector<uint8_t> extradata(file_size);
  CHECK_EQ(file_size,
           base::ReadFile(extradata_path,
                          reinterpret_cast<char*>(&extradata[0]), file_size))
      << "Failed to read '" << extradata_name << "'";

  return media::AudioDecoderConfig(kCodec, kSampleFormat, kChannelLayout,
                                   kSamplesPerSecond, std::move(extradata),
                                   media::EncryptionScheme::kUnencrypted);
}

TEST_F(AudioDecoderBrokerTest, Decode_NoMojoDecoder) {
  V8TestingScope v8_scope;

  ConstructDecoder(*v8_scope.GetExecutionContext());
  EXPECT_EQ(GetDecoderType(), media::AudioDecoderType::kBroker);

  InitializeDecoder(MakeVorbisConfig());
  EXPECT_EQ(GetDecoderType(), media::AudioDecoderType::kFFmpeg);

  DecodeBuffer(
      media::ReadTestDataFile("vorbis-packet-0", base::Milliseconds(0)));
  DecodeBuffer(
      media::ReadTestDataFile("vorbis-packet-1", base::Milliseconds(1)));
  DecodeBuffer(
      media::ReadTestDataFile("vorbis-packet-2", base::Milliseconds(2)));
  DecodeBuffer(media::DecoderBuffer::CreateEOSBuffer());
  // 2, not 3, because the first frame doesn't generate an output.
  ASSERT_EQ(2U, output_buffers_.size());

  ResetDecoder();

  DecodeBuffer(
      media::ReadTestDataFile("vorbis-packet-0", base::Milliseconds(0)));
  DecodeBuffer(
      media::ReadTestDataFile("vorbis-packet-1", base::Milliseconds(1)));
  DecodeBuffer(
      media::ReadTestDataFile("vorbis-packet-2", base::Milliseconds(2)));
  DecodeBuffer(media::DecoderBuffer::CreateEOSBuffer());
  // 2 more than last time.
  ASSERT_EQ(4U, output_buffers_.size());

  ResetDecoder();
}

#if BUILDFLAG(ENABLE_MOJO_AUDIO_DECODER)
TEST_F(AudioDecoderBrokerTest, Decode_WithMojoDecoder) {
  V8TestingScope v8_scope;
  ExecutionContext* execution_context = v8_scope.GetExecutionContext();

  SetupMojo(*execution_context);
  ConstructDecoder(*execution_context);
  EXPECT_EQ(GetDecoderType(), media::AudioDecoderType::kBroker);
  EXPECT_FALSE(IsPlatformDecoder());
  EXPECT_FALSE(SupportsDecryption());

  // Use an MpegH config to prevent FFmpeg from being selected.
  InitializeDecoder(media::AudioDecoderConfig(
      media::AudioCodec::kMpegHAudio, kSampleFormat, kChannelLayout,
      kSamplesPerSecond, media::EmptyExtraData(),
      media::EncryptionScheme::kUnencrypted));
  EXPECT_EQ(GetDecoderType(), media::AudioDecoderType::kTesting);

  // Using vorbis buffer here because its easy and the fake decoder generates
  // output regardless of the input details.
  DecodeBuffer(media::ReadTestDataFile("vorbis-packet-0"));
  DecodeBuffer(media::DecoderBuffer::CreateEOSBuffer());
  // Our fake decoder immediately generates output for any input.
  ASSERT_EQ(1U, output_buffers_.size());

  // True for MojoAudioDecoder.
  EXPECT_TRUE(IsPlatformDecoder());
  // True for for MojoVideoDecoder on Android, but WebCodecs doesn't do
  // decryption, so this is hard-coded to false.
  EXPECT_FALSE(SupportsDecryption());

  ResetDecoder();
}
#endif  // BUILDFLAG(ENABLE_MOJO_AUDIO_DECODER)
}  // namespace blink