summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler_unittest.cc
blob: 046eaa1a11ba39e0737a30e268d464929bccaffb (plain)
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>

#include <string>

#include "base/macros.h"
#include "base/run_loop.h"
#include "base/test/gmock_callback_support.h"
#include "base/time/time.h"
#include "media/audio/simple_sources.h"
#include "media/base/audio_bus.h"
#include "media/base/video_color_space.h"
#include "media/base/video_frame.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "third_party/blink/public/web/web_heap.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/core/testing/scoped_mock_overlay_scrollbars.h"
#include "third_party/blink/renderer/modules/mediarecorder/fake_encoded_video_frame.h"
#include "third_party/blink/renderer/modules/mediarecorder/media_recorder.h"
#include "third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h"
#include "third_party/blink/renderer/modules/mediastream/mock_media_stream_registry.h"
#include "third_party/blink/renderer/modules/mediastream/mock_media_stream_video_source.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
#include "third_party/blink/renderer/platform/testing/io_task_runner_testing_platform_support.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"

using base::test::RunOnceClosure;
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Ge;
using ::testing::Gt;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::Lt;
using ::testing::Mock;
using ::testing::Return;
using ::testing::TestWithParam;
using ::testing::ValuesIn;

namespace blink {

static const std::string kTestVideoTrackId = "video_track_id";
static const std::string kTestAudioTrackId = "audio_track_id";
static const int kTestAudioChannels = 2;
static const int kTestAudioSampleRate = 48000;
static const int kTestAudioBufferDurationMs = 10;
// Opus works with 60ms buffers, so 6 MediaStreamAudioTrack Buffers are needed
// to encode one output buffer.
static const int kRatioOpusToTestAudioBuffers = 6;

struct MediaRecorderTestParams {
  const bool has_video;
  const bool has_audio;
  const char* const mime_type;
  const char* const codecs;
  const bool encoder_supports_alpha;
};

// Array of valid combinations of video/audio/codecs and expected collected
// encoded sizes to use for parameterizing MediaRecorderHandlerTest.
static const MediaRecorderTestParams kMediaRecorderTestParams[] = {
    {true, false, "video/webm", "vp8", true},
    {true, false, "video/webm", "vp9", true},
#if BUILDFLAG(RTC_USE_H264)
    {true, false, "video/x-matroska", "avc1", false},
#endif
    {false, true, "audio/webm", "opus", true},
    {false, true, "audio/webm", "", true},  // Should default to opus.
    {false, true, "audio/webm", "pcm", true},
    {true, true, "video/webm", "vp9,opus", true},
};

MediaStream* CreateMediaStream(V8TestingScope& scope) {
  auto* source = MakeGarbageCollected<MediaStreamSource>(
      "sourceId", MediaStreamSource::kTypeAudio, "sourceName", false);
  auto* component =
      MakeGarbageCollected<MediaStreamComponent>("audioTrack", source);

  auto* track = MakeGarbageCollected<MediaStreamTrack>(
      scope.GetExecutionContext(), component);

  HeapVector<Member<MediaStreamTrack>> tracks;
  tracks.push_back(track);

  MediaStream* stream =
      MediaStream::Create(scope.GetExecutionContext(), tracks);

  return stream;
}

class MockMediaRecorder : public MediaRecorder {
 public:
  MockMediaRecorder(V8TestingScope& scope)
      : MediaRecorder(scope.GetExecutionContext(),
                      CreateMediaStream(scope),
                      MediaRecorderOptions::Create(),
                      scope.GetExceptionState()) {}
  virtual ~MockMediaRecorder() = default;

  MOCK_METHOD4(WriteData, void(const char*, size_t, bool, double));
  MOCK_METHOD1(OnError, void(const String& message));
};

class MediaRecorderHandlerFixture : public ScopedMockOverlayScrollbars {
 public:
  MediaRecorderHandlerFixture(bool has_video, bool has_audio)
      : has_video_(has_video),
        has_audio_(has_audio),
        media_recorder_handler_(MakeGarbageCollected<MediaRecorderHandler>(
            scheduler::GetSingleThreadTaskRunnerForTesting())),
        audio_source_(kTestAudioChannels,
                      440 /* freq */,
                      kTestAudioSampleRate) {
    EXPECT_FALSE(media_recorder_handler_->recording_);

    registry_.Init();
  }

  ~MediaRecorderHandlerFixture() {
    registry_.reset();
    ThreadState::Current()->CollectAllGarbageForTesting();
  }

  bool recording() const { return media_recorder_handler_->recording_; }
  bool hasVideoRecorders() const {
    return !media_recorder_handler_->video_recorders_.IsEmpty();
  }
  bool hasAudioRecorders() const {
    return !media_recorder_handler_->audio_recorders_.IsEmpty();
  }

  void OnVideoFrameForTesting(scoped_refptr<media::VideoFrame> frame) {
    media_recorder_handler_->OnVideoFrameForTesting(std::move(frame),
                                                    base::TimeTicks::Now());
  }

  void OnEncodedVideoForTesting(const media::WebmMuxer::VideoParameters& params,
                                std::string encoded_data,
                                std::string encoded_alpha,
                                base::TimeTicks timestamp,
                                bool is_key_frame) {
    media_recorder_handler_->OnEncodedVideo(params, encoded_data, encoded_alpha,
                                            timestamp, is_key_frame);
  }

  void OnAudioBusForTesting(const media::AudioBus& audio_bus) {
    media_recorder_handler_->OnAudioBusForTesting(audio_bus,
                                                  base::TimeTicks::Now());
  }
  void SetAudioFormatForTesting(const media::AudioParameters& params) {
    media_recorder_handler_->SetAudioFormatForTesting(params);
  }

  void AddVideoTrack() {
    video_source_ = registry_.AddVideoTrack(kTestVideoTrackId);
  }

  void AddTracks() {
    // Avoid issues with non-parameterized tests by calling this outside of ctr.
    if (has_video_)
      AddVideoTrack();
    if (has_audio_)
      registry_.AddAudioTrack(kTestAudioTrackId);
  }

  void ForceOneErrorInWebmMuxer() {
    media_recorder_handler_->webm_muxer_->ForceOneLibWebmErrorForTesting();
  }

  std::unique_ptr<media::AudioBus> NextAudioBus() {
    std::unique_ptr<media::AudioBus> bus(media::AudioBus::Create(
        kTestAudioChannels,
        kTestAudioSampleRate * kTestAudioBufferDurationMs / 1000));
    audio_source_.OnMoreData(base::TimeDelta(), base::TimeTicks::Now(), 0,
                             bus.get());
    return bus;
  }

  ScopedTestingPlatformSupport<IOTaskRunnerTestingPlatformSupport> platform_;

  MockMediaStreamRegistry registry_;

  bool has_video_;

  bool has_audio_;

  // The Class under test. Needs to be scoped_ptr to force its destruction.
  Persistent<MediaRecorderHandler> media_recorder_handler_;

  // For generating test AudioBuses
  media::SineWaveAudioSource audio_source_;

  MockMediaStreamVideoSource* video_source_ = nullptr;

 private:
  DISALLOW_COPY_AND_ASSIGN(MediaRecorderHandlerFixture);
};

class MediaRecorderHandlerTest : public TestWithParam<MediaRecorderTestParams>,
                                 public MediaRecorderHandlerFixture {
 public:
  MediaRecorderHandlerTest()
      : MediaRecorderHandlerFixture(GetParam().has_video,
                                    GetParam().has_audio) {}

 private:
  DISALLOW_COPY_AND_ASSIGN(MediaRecorderHandlerTest);
};

// Checks that canSupportMimeType() works as expected, by sending supported
// combinations and unsupported ones.
TEST_P(MediaRecorderHandlerTest, CanSupportMimeType) {
  const String unsupported_mime_type("video/mpeg");
  EXPECT_FALSE(media_recorder_handler_->CanSupportMimeType(
      unsupported_mime_type, String()));

  const String mime_type_video("video/webm");
  EXPECT_TRUE(
      media_recorder_handler_->CanSupportMimeType(mime_type_video, String()));
  const String mime_type_video_uppercase("video/WEBM");
  EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(
      mime_type_video_uppercase, String()));
  const String example_good_codecs_1("vp8");
  EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(
      mime_type_video, example_good_codecs_1));
  const String example_good_codecs_2("vp9,opus");
  EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(
      mime_type_video, example_good_codecs_2));
  const String example_good_codecs_3("VP9,opus");
  EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(
      mime_type_video, example_good_codecs_3));
  const String example_good_codecs_4("H264");
#if BUILDFLAG(RTC_USE_H264)
  EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(
      mime_type_video, example_good_codecs_4));
#else
  EXPECT_FALSE(media_recorder_handler_->CanSupportMimeType(
      mime_type_video, example_good_codecs_4));
#endif

  const String example_unsupported_codecs_1("daala");
  EXPECT_FALSE(media_recorder_handler_->CanSupportMimeType(
      mime_type_video, example_unsupported_codecs_1));

  const String mime_type_audio("audio/webm");
  EXPECT_TRUE(
      media_recorder_handler_->CanSupportMimeType(mime_type_audio, String()));
  const String example_good_codecs_5("opus");
  EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(
      mime_type_audio, example_good_codecs_5));
  const String example_good_codecs_6("OpUs");
  EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(
      mime_type_audio, example_good_codecs_6));
  const String example_good_codecs_7("pcm");
  EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(
      mime_type_audio, example_good_codecs_7));

  const String example_unsupported_codecs_2("vorbis");
  EXPECT_FALSE(media_recorder_handler_->CanSupportMimeType(
      mime_type_audio, example_unsupported_codecs_2));
}

// Checks that the initialization-destruction sequence works fine.
TEST_P(MediaRecorderHandlerTest, InitializeStartStop) {
  AddTracks();
  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);
  const String mime_type(GetParam().mime_type);
  const String codecs(GetParam().codecs);
  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), mime_type, codecs, 0, 0));
  EXPECT_FALSE(recording());
  EXPECT_FALSE(hasVideoRecorders());
  EXPECT_FALSE(hasAudioRecorders());

  EXPECT_TRUE(media_recorder_handler_->Start(0));
  EXPECT_TRUE(recording());

  EXPECT_TRUE(hasVideoRecorders() || !GetParam().has_video);
  EXPECT_TRUE(hasAudioRecorders() || !GetParam().has_audio);

  media_recorder_handler_->Stop();
  EXPECT_FALSE(recording());
  EXPECT_FALSE(hasVideoRecorders());
  EXPECT_FALSE(hasAudioRecorders());

  // Expect a last call on destruction.
  EXPECT_CALL(*recorder, WriteData(_, _, true, _)).Times(1);
  media_recorder_handler_ = nullptr;
}

// Sends 2 opaque frames and 1 transparent frame and expects them as WebM
// contained encoded data in writeData().
TEST_P(MediaRecorderHandlerTest, EncodeVideoFrames) {
  // Video-only test.
  if (GetParam().has_audio)
    return;

  AddTracks();

  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);
  const String mime_type(GetParam().mime_type);
  const String codecs(GetParam().codecs);
  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), mime_type, codecs, 0, 0));
  EXPECT_TRUE(media_recorder_handler_->Start(0));

  InSequence s;
  const scoped_refptr<media::VideoFrame> video_frame =
      media::VideoFrame::CreateBlackFrame(gfx::Size(160, 80));

  {
    const size_t kEncodedSizeThreshold = 16;
    base::RunLoop run_loop;
    // writeData() is pinged a number of times as the WebM header is written;
    // the last time it is called it has the encoded data.
    EXPECT_CALL(*recorder, WriteData(_, Lt(kEncodedSizeThreshold), _, _))
        .Times(AtLeast(1));
    EXPECT_CALL(*recorder, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
        .Times(1)
        .WillOnce(RunOnceClosure(run_loop.QuitClosure()));

    OnVideoFrameForTesting(video_frame);
    run_loop.Run();
  }
  Mock::VerifyAndClearExpectations(this);

  {
    const size_t kEncodedSizeThreshold = 12;
    base::RunLoop run_loop;
    // The second time around writeData() is called a number of times to write
    // the WebM frame header, and then is pinged with the encoded data.
    EXPECT_CALL(*recorder, WriteData(_, Lt(kEncodedSizeThreshold), _, _))
        .Times(AtLeast(1));
    EXPECT_CALL(*recorder, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
        .Times(1)
        .WillOnce(RunOnceClosure(run_loop.QuitClosure()));

    OnVideoFrameForTesting(video_frame);
    run_loop.Run();
  }
  Mock::VerifyAndClearExpectations(this);

  {
    const scoped_refptr<media::VideoFrame> alpha_frame =
        media::VideoFrame::CreateTransparentFrame(gfx::Size(160, 80));
    const size_t kEncodedSizeThreshold = 16;
    EXPECT_EQ(4u, media::VideoFrame::NumPlanes(alpha_frame->format()));
    base::RunLoop run_loop;
    // The second time around writeData() is called a number of times to write
    // the WebM frame header, and then is pinged with the encoded data.
    EXPECT_CALL(*recorder, WriteData(_, Lt(kEncodedSizeThreshold), _, _))
        .Times(AtLeast(1));
    EXPECT_CALL(*recorder, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
        .Times(1)
        .WillOnce(RunOnceClosure(run_loop.QuitClosure()));
    if (GetParam().encoder_supports_alpha) {
      EXPECT_CALL(*recorder, WriteData(_, Lt(kEncodedSizeThreshold), _, _))
          .Times(AtLeast(1));
      EXPECT_CALL(*recorder, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
          .Times(1)
          .WillOnce(RunOnceClosure(run_loop.QuitClosure()));
    }

    OnVideoFrameForTesting(alpha_frame);
    run_loop.Run();
  }

  media_recorder_handler_->Stop();

  // Expect a last call on destruction.
  EXPECT_CALL(*recorder, WriteData(_, _, true, _)).Times(1);
  media_recorder_handler_ = nullptr;
}

INSTANTIATE_TEST_SUITE_P(All,
                         MediaRecorderHandlerTest,
                         ValuesIn(kMediaRecorderTestParams));

// Sends 2 frames and expect them as WebM (or MKV) contained encoded audio data
// in writeData().
TEST_P(MediaRecorderHandlerTest, OpusEncodeAudioFrames) {
  // Audio-only test.
  if (GetParam().has_video)
    return;

  AddTracks();

  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);

  const String mime_type(GetParam().mime_type);
  const String codecs(GetParam().codecs);
  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), mime_type, codecs, 0, 0));
  EXPECT_TRUE(media_recorder_handler_->Start(0));

  InSequence s;
  const std::unique_ptr<media::AudioBus> audio_bus1 = NextAudioBus();
  const std::unique_ptr<media::AudioBus> audio_bus2 = NextAudioBus();

  media::AudioParameters params(
      media::AudioParameters::AUDIO_PCM_LINEAR, media::CHANNEL_LAYOUT_STEREO,
      kTestAudioSampleRate,
      kTestAudioSampleRate * kTestAudioBufferDurationMs / 1000);
  SetAudioFormatForTesting(params);

  const size_t kEncodedSizeThreshold = 24;
  {
    base::RunLoop run_loop;
    // writeData() is pinged a number of times as the WebM header is written;
    // the last time it is called it has the encoded data.
    EXPECT_CALL(*recorder, WriteData(_, Lt(kEncodedSizeThreshold), _, _))
        .Times(AtLeast(1));
    EXPECT_CALL(*recorder, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
        .Times(1)
        .WillOnce(RunOnceClosure(run_loop.QuitClosure()));

    for (int i = 0; i < kRatioOpusToTestAudioBuffers; ++i)
      OnAudioBusForTesting(*audio_bus1);
    run_loop.Run();
  }
  Mock::VerifyAndClearExpectations(this);

  {
    base::RunLoop run_loop;
    // The second time around writeData() is called a number of times to write
    // the WebM frame header, and then is pinged with the encoded data.
    EXPECT_CALL(*recorder, WriteData(_, Lt(kEncodedSizeThreshold), _, _))
        .Times(AtLeast(1));
    EXPECT_CALL(*recorder, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
        .Times(1)
        .WillOnce(RunOnceClosure(run_loop.QuitClosure()));

    for (int i = 0; i < kRatioOpusToTestAudioBuffers; ++i)
      OnAudioBusForTesting(*audio_bus2);
    run_loop.Run();
  }

  media_recorder_handler_->Stop();

  // Expect a last call on destruction.
  EXPECT_CALL(*recorder, WriteData(_, _, true, _)).Times(1);
  media_recorder_handler_ = nullptr;
}

// Starts up recording and forces a WebmMuxer's libwebm error.
TEST_P(MediaRecorderHandlerTest, WebmMuxerErrorWhileEncoding) {
  // Video-only test: Audio would be very similar.
  if (GetParam().has_audio)
    return;

  AddTracks();

  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);

  const String mime_type(GetParam().mime_type);
  const String codecs(GetParam().codecs);
  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), mime_type, codecs, 0, 0));
  EXPECT_TRUE(media_recorder_handler_->Start(0));

  InSequence s;
  const scoped_refptr<media::VideoFrame> video_frame =
      media::VideoFrame::CreateBlackFrame(gfx::Size(160, 80));

  {
    const size_t kEncodedSizeThreshold = 16;
    base::RunLoop run_loop;
    EXPECT_CALL(*recorder, WriteData(_, _, _, _)).Times(AtLeast(1));
    EXPECT_CALL(*recorder, WriteData(_, Gt(kEncodedSizeThreshold), _, _))
        .Times(1)
        .WillOnce(RunOnceClosure(run_loop.QuitClosure()));

    OnVideoFrameForTesting(video_frame);
    run_loop.Run();
  }

  ForceOneErrorInWebmMuxer();

  {
    base::RunLoop run_loop;
    EXPECT_CALL(*recorder, WriteData(_, _, _, _)).Times(0);
    EXPECT_CALL(*recorder, OnError(_))
        .Times(1)
        .WillOnce(RunOnceClosure(run_loop.QuitClosure()));

    OnVideoFrameForTesting(video_frame);
    run_loop.Run();
  }

  // Expect a last call on destruction.
  EXPECT_CALL(*recorder, WriteData(_, _, true, _)).Times(1);
  media_recorder_handler_ = nullptr;
}

// Checks the ActualMimeType() versus the expected.
TEST_P(MediaRecorderHandlerTest, ActualMimeType) {
  AddTracks();

  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);

  const String mime_type(GetParam().mime_type);
  const String codecs(GetParam().codecs);
  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), mime_type, codecs, 0, 0));

  StringBuilder actual_mime_type;
  actual_mime_type.Append(GetParam().mime_type);
  actual_mime_type.Append(";codecs=");
  if (strlen(GetParam().codecs) != 0u)
    actual_mime_type.Append(GetParam().codecs);
  else if (GetParam().has_video)
    actual_mime_type.Append("vp8");
  else if (GetParam().has_audio)
    actual_mime_type.Append("opus");

  EXPECT_EQ(media_recorder_handler_->ActualMimeType(),
            actual_mime_type.ToString());

  // Expect a last call on destruction.
  EXPECT_CALL(*recorder, WriteData(_, _, true, _)).Times(1);
  media_recorder_handler_ = nullptr;
}

TEST_P(MediaRecorderHandlerTest, PauseRecorderForVideo) {
  // Video-only test: Audio would be very similar.
  if (GetParam().has_audio)
    return;

  AddTracks();

  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);

  const String mime_type(GetParam().mime_type);
  const String codecs(GetParam().codecs);

  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), mime_type, codecs, 0, 0));
  EXPECT_TRUE(media_recorder_handler_->Start(0));

  Mock::VerifyAndClearExpectations(recorder);
  media_recorder_handler_->Pause();

  EXPECT_CALL(*recorder, WriteData).Times(AtLeast(1));
  media::WebmMuxer::VideoParameters params(gfx::Size(), 1, media::kCodecVP9,
                                           gfx::ColorSpace());
  OnEncodedVideoForTesting(params, "vp9 frame", "", base::TimeTicks::Now(),
                           true);

  // Expect a last call on destruction.
  EXPECT_CALL(*recorder, WriteData(_, _, true, _)).Times(1);
  media_recorder_handler_ = nullptr;
}

TEST_P(MediaRecorderHandlerTest, StartStopStartRecorderForVideo) {
  // Video-only test: Audio would be very similar.
  if (GetParam().has_audio)
    return;

  AddTracks();

  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);

  const String mime_type(GetParam().mime_type);
  const String codecs(GetParam().codecs);

  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), mime_type, codecs, 0, 0));
  EXPECT_TRUE(media_recorder_handler_->Start(0));
  media_recorder_handler_->Stop();

  Mock::VerifyAndClearExpectations(recorder);
  EXPECT_TRUE(media_recorder_handler_->Start(0));

  EXPECT_CALL(*recorder, WriteData).Times(AtLeast(1));
  media::WebmMuxer::VideoParameters params(gfx::Size(), 1, media::kCodecVP9,
                                           gfx::ColorSpace());
  OnEncodedVideoForTesting(params, "vp9 frame", "", base::TimeTicks::Now(),
                           true);

  // Expect a last call on destruction.
  EXPECT_CALL(*recorder, WriteData(_, _, true, _)).Times(1);
  media_recorder_handler_ = nullptr;
}

#if BUILDFLAG(RTC_USE_H264)

struct H264ProfileTestParams {
  const bool has_audio;
  const char* const mime_type;
  const char* const codecs;
};

static const H264ProfileTestParams kH264ProfileTestParams[] = {
    {false, "video/x-matroska", "avc1.42000c"},  // H264PROFILE_BASELINE
    {false, "video/x-matroska", "avc1.4d000c"},  // H264PROFILE_MAIN
    {false, "video/x-matroska", "avc1.64000c"},  // H264PROFILE_HIGH
    {false, "video/x-matroska", "avc1.640029"},
    {false, "video/x-matroska", "avc1.640034"},
    {true, "video/x-matroska", "avc1.64000c,pcm"},
};

class MediaRecorderHandlerH264ProfileTest
    : public TestWithParam<H264ProfileTestParams>,
      public MediaRecorderHandlerFixture {
 public:
  MediaRecorderHandlerH264ProfileTest()
      : MediaRecorderHandlerFixture(true, GetParam().has_audio) {}

 private:
  DISALLOW_COPY_AND_ASSIGN(MediaRecorderHandlerH264ProfileTest);
};

TEST_P(MediaRecorderHandlerH264ProfileTest, ActualMimeType) {
  AddTracks();

  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);

  const String mime_type(GetParam().mime_type);
  const String codecs(GetParam().codecs);
  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), mime_type, codecs, 0, 0));

  String actual_mime_type =
      String(GetParam().mime_type) + ";codecs=" + GetParam().codecs;

  EXPECT_EQ(media_recorder_handler_->ActualMimeType(), actual_mime_type);

  media_recorder_handler_ = nullptr;
}

INSTANTIATE_TEST_SUITE_P(All,
                         MediaRecorderHandlerH264ProfileTest,
                         ValuesIn(kH264ProfileTestParams));

#endif

struct MediaRecorderPassthroughTestParams {
  const char* mime_type;
  media::VideoCodec codec;
};

static const MediaRecorderPassthroughTestParams
    kMediaRecorderPassthroughTestParams[] = {
        {"video/webm;codecs=vp8", media::kCodecVP8},
        {"video/webm;codecs=vp9", media::kCodecVP9},
#if BUILDFLAG(RTC_USE_H264)
        {"video/x-matroska;codecs=avc1", media::kCodecH264},
#endif
};

class MediaRecorderHandlerPassthroughTest
    : public TestWithParam<MediaRecorderPassthroughTestParams>,
      public ScopedMockOverlayScrollbars {
 public:
  MediaRecorderHandlerPassthroughTest() {
    registry_.Init();
    video_source_ = registry_.AddVideoTrack(kTestVideoTrackId);
    ON_CALL(*video_source_, SupportsEncodedOutput).WillByDefault(Return(true));
    media_recorder_handler_ = MakeGarbageCollected<MediaRecorderHandler>(
        scheduler::GetSingleThreadTaskRunnerForTesting());
    EXPECT_FALSE(media_recorder_handler_->recording_);
  }

  ~MediaRecorderHandlerPassthroughTest() {
    registry_.reset();
    media_recorder_handler_ = nullptr;
    WebHeap::CollectAllGarbageForTesting();
  }

  void OnVideoFrameForTesting(scoped_refptr<EncodedVideoFrame> frame) {
    media_recorder_handler_->OnEncodedVideoFrameForTesting(
        std::move(frame), base::TimeTicks::Now());
  }

  ScopedTestingPlatformSupport<IOTaskRunnerTestingPlatformSupport> platform_;
  MockMediaStreamRegistry registry_;
  MockMediaStreamVideoSource* video_source_ = nullptr;
  Persistent<MediaRecorderHandler> media_recorder_handler_;

 private:
  DISALLOW_COPY_AND_ASSIGN(MediaRecorderHandlerPassthroughTest);
};

TEST_P(MediaRecorderHandlerPassthroughTest, PassesThrough) {
  // Setup the mock video source to allow for passthrough recording.
  EXPECT_CALL(*video_source_, OnEncodedSinkEnabled);
  EXPECT_CALL(*video_source_, OnEncodedSinkDisabled);

  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);
  media_recorder_handler_->Initialize(recorder, registry_.test_stream(), "", "",
                                      0, 0);
  media_recorder_handler_->Start(0);

  const size_t kFrameSize = 42;
  auto frame = FakeEncodedVideoFrame::Builder()
                   .WithKeyFrame(true)
                   .WithCodec(GetParam().codec)
                   .WithData(std::string(kFrameSize, 'P'))
                   .BuildRefPtr();
  {
    base::RunLoop run_loop;
    EXPECT_CALL(*recorder, WriteData(_, _, _, _)).Times(AtLeast(1));
    EXPECT_CALL(*recorder, WriteData(_, Ge(kFrameSize), _, _))
        .Times(1)
        .WillOnce(RunOnceClosure(run_loop.QuitClosure()));
    OnVideoFrameForTesting(frame);
    run_loop.Run();
  }
  EXPECT_EQ(media_recorder_handler_->ActualMimeType(), GetParam().mime_type);
  Mock::VerifyAndClearExpectations(this);

  media_recorder_handler_->Stop();

  // Expect a last call on destruction.
  EXPECT_CALL(*recorder, WriteData(_, _, true, _)).Times(1);
  media_recorder_handler_ = nullptr;
}

TEST_F(MediaRecorderHandlerPassthroughTest, ErrorsOutOnCodecSwitch) {
  V8TestingScope scope;
  auto* recorder = MakeGarbageCollected<MockMediaRecorder>(scope);
  EXPECT_TRUE(media_recorder_handler_->Initialize(
      recorder, registry_.test_stream(), "", "", 0, 0));
  EXPECT_TRUE(media_recorder_handler_->Start(0));

  // NOTE, Asan: the prototype of WriteData which has a const char* as data
  // ptr plays badly with gmock which tries to interpret it as a null-terminated
  // string. However, it points to binary data which causes gmock to overrun the
  // bounds of buffers and this manifests as an ASAN crash.
  // The expectation here works around this issue.
  EXPECT_CALL(*recorder, WriteData).Times(AtLeast(1));

  EXPECT_CALL(*recorder, OnError).WillOnce(Invoke([&](const String&) {
    // Simulate MediaRecorder behavior which is to Stop() the handler on error.
    media_recorder_handler_->Stop();
  }));
  OnVideoFrameForTesting(FakeEncodedVideoFrame::Builder()
                             .WithKeyFrame(true)
                             .WithCodec(media::kCodecVP8)
                             .WithData(std::string("vp8 frame"))
                             .BuildRefPtr());
  // Switch to VP9 frames. This is expected to cause the call to OnError
  // above.
  OnVideoFrameForTesting(FakeEncodedVideoFrame::Builder()
                             .WithKeyFrame(true)
                             .WithCodec(media::kCodecVP9)
                             .WithData(std::string("vp9 frame"))
                             .BuildRefPtr());
  // Send one more frame to verify that continued frame of different codec
  // transfer doesn't crash the media recorder.
  OnVideoFrameForTesting(FakeEncodedVideoFrame::Builder()
                             .WithKeyFrame(true)
                             .WithCodec(media::kCodecVP8)
                             .WithData(std::string("vp8 frame"))
                             .BuildRefPtr());
  platform_->RunUntilIdle();
}

INSTANTIATE_TEST_SUITE_P(All,
                         MediaRecorderHandlerPassthroughTest,
                         ValuesIn(kMediaRecorderPassthroughTestParams));

}  // namespace blink