summaryrefslogtreecommitdiffstats
path: root/content/renderer/media/media_stream_video_capturer_source_unittest.cc
blob: b7eb656a83da26d70c372660f00033b99acb4a99 (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
// Copyright 2014 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 "base/bind.h"
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "content/child/child_process.h"
#include "content/public/renderer/media_stream_video_sink.h"
#include "content/renderer/media/media_stream_video_capturer_source.h"
#include "content/renderer/media/media_stream_video_track.h"
#include "content/renderer/media/mock_media_constraint_factory.h"
#include "media/base/bind_to_current_loop.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/web/WebHeap.h"

using ::testing::_;

namespace content {

class MockVideoCapturerDelegate : public VideoCapturerDelegate {
 public:
  explicit MockVideoCapturerDelegate(const StreamDeviceInfo& device_info)
      : VideoCapturerDelegate(device_info) {}

  MOCK_METHOD4(StartCapture,
               void(const media::VideoCaptureParams& params,
                    const VideoCaptureDeliverFrameCB& new_frame_callback,
                    scoped_refptr<base::SingleThreadTaskRunner>
                        frame_callback_task_runner,
                    const RunningCallback& running_callback));
  MOCK_METHOD0(StopCapture, void());
};

class MediaStreamVideoCapturerSourceTest : public testing::Test {
 public:
  MediaStreamVideoCapturerSourceTest()
      : child_process_(new ChildProcess()),
        source_(NULL),
        delegate_(NULL),
        source_stopped_(false) {}

  void TearDown() override {
    webkit_source_.reset();
    blink::WebHeap::collectAllGarbageForTesting();
  }

  void InitWithDeviceInfo(const StreamDeviceInfo& device_info) {
    scoped_ptr<MockVideoCapturerDelegate> delegate(
        new MockVideoCapturerDelegate(device_info));
    delegate_ = delegate.get();
    source_ = new MediaStreamVideoCapturerSource(
        base::Bind(&MediaStreamVideoCapturerSourceTest::OnSourceStopped,
                   base::Unretained(this)),
        delegate.Pass());
    source_->SetDeviceInfo(device_info);

    webkit_source_.initialize(base::UTF8ToUTF16("dummy_source_id"),
                              blink::WebMediaStreamSource::TypeVideo,
                              base::UTF8ToUTF16("dummy_source_name"),
                              false /* remote */, true /* readonly */);
    webkit_source_.setExtraData(source_);
    webkit_source_id_ = webkit_source_.id();
  }

  MockMediaConstraintFactory* constraint_factory() {
    return &constraint_factory_;
  }

  blink::WebMediaStreamTrack StartSource() {
    bool enabled = true;
    // CreateVideoTrack will trigger OnConstraintsApplied.
    return MediaStreamVideoTrack::CreateVideoTrack(
        source_, constraint_factory_.CreateWebMediaConstraints(),
        base::Bind(&MediaStreamVideoCapturerSourceTest::OnConstraintsApplied,
                   base::Unretained(this)),
        enabled);
  }

  MockVideoCapturerDelegate& mock_delegate() { return *delegate_; }

  void OnSourceStopped(const blink::WebMediaStreamSource& source) {
    source_stopped_ = true;
    EXPECT_EQ(source.id(), webkit_source_id_);
  }

 protected:
  void OnConstraintsApplied(MediaStreamSource* source,
                            MediaStreamRequestResult result,
                            const blink::WebString& result_name) {}

  base::MessageLoopForUI message_loop_;
  scoped_ptr<ChildProcess> child_process_;
  blink::WebMediaStreamSource webkit_source_;
  MediaStreamVideoCapturerSource* source_;  // owned by |webkit_source_|.
  MockVideoCapturerDelegate* delegate_;     // owned by |source|.
  blink::WebString webkit_source_id_;
  bool source_stopped_;
  MockMediaConstraintFactory constraint_factory_;
};

TEST_F(MediaStreamVideoCapturerSourceTest, TabCaptureFixedResolutionByDefault) {
  StreamDeviceInfo device_info;
  device_info.device.type = MEDIA_TAB_VIDEO_CAPTURE;
  InitWithDeviceInfo(device_info);

  // No constraints are being provided to the implementation, so expect only
  // default values.
  media::VideoCaptureParams expected_params;
  expected_params.requested_format.frame_size.SetSize(
      MediaStreamVideoSource::kDefaultWidth,
      MediaStreamVideoSource::kDefaultHeight);
  expected_params.requested_format.frame_rate =
      MediaStreamVideoSource::kDefaultFrameRate;
  expected_params.requested_format.pixel_format =
      media::VIDEO_CAPTURE_PIXEL_FORMAT_I420;
  expected_params.resolution_change_policy =
      media::RESOLUTION_POLICY_FIXED_RESOLUTION;

  EXPECT_CALL(mock_delegate(), StartCapture(expected_params, _, _, _)).Times(1);
  blink::WebMediaStreamTrack track = StartSource();
  // When the track goes out of scope, the source will be stopped.
  EXPECT_CALL(mock_delegate(), StopCapture());
}

TEST_F(MediaStreamVideoCapturerSourceTest,
       DesktopCaptureAllowAnyResolutionChangeByDefault) {
  StreamDeviceInfo device_info;
  device_info.device.type = MEDIA_DESKTOP_VIDEO_CAPTURE;
  InitWithDeviceInfo(device_info);

  // No constraints are being provided to the implementation, so expect only
  // default values.
  media::VideoCaptureParams expected_params;
  expected_params.requested_format.frame_size.SetSize(
      MediaStreamVideoSource::kDefaultWidth,
      MediaStreamVideoSource::kDefaultHeight);
  expected_params.requested_format.frame_rate =
      MediaStreamVideoSource::kDefaultFrameRate;
  expected_params.requested_format.pixel_format =
      media::VIDEO_CAPTURE_PIXEL_FORMAT_I420;
  expected_params.resolution_change_policy =
      media::RESOLUTION_POLICY_ANY_WITHIN_LIMIT;

  EXPECT_CALL(mock_delegate(), StartCapture(expected_params, _, _, _)).Times(1);
  blink::WebMediaStreamTrack track = StartSource();
  // When the track goes out of scope, the source will be stopped.
  EXPECT_CALL(mock_delegate(), StopCapture());
}

TEST_F(MediaStreamVideoCapturerSourceTest,
       TabCaptureConstraintsImplyFixedAspectRatio) {
  StreamDeviceInfo device_info;
  device_info.device.type = MEDIA_TAB_VIDEO_CAPTURE;
  InitWithDeviceInfo(device_info);

  // Specify max and min size constraints that have the same ~16:9 aspect ratio.
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMaxWidth, 1920);
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMaxHeight, 1080);
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMinWidth, 854);
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMinHeight, 480);
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMaxFrameRate,
                                     60.0);

  media::VideoCaptureParams expected_params;
  expected_params.requested_format.frame_size.SetSize(1920, 1080);
  expected_params.requested_format.frame_rate = 60.0;
  expected_params.requested_format.pixel_format =
      media::VIDEO_CAPTURE_PIXEL_FORMAT_I420;
  expected_params.resolution_change_policy =
      media::RESOLUTION_POLICY_FIXED_ASPECT_RATIO;

  EXPECT_CALL(
      mock_delegate(),
      StartCapture(
          testing::Field(&media::VideoCaptureParams::resolution_change_policy,
                         media::RESOLUTION_POLICY_FIXED_ASPECT_RATIO),
          _, _, _))
      .Times(1);
  blink::WebMediaStreamTrack track = StartSource();
  // When the track goes out of scope, the source will be stopped.
  EXPECT_CALL(mock_delegate(), StopCapture());
}

TEST_F(MediaStreamVideoCapturerSourceTest,
       TabCaptureConstraintsImplyAllowingAnyResolutionChange) {
  StreamDeviceInfo device_info;
  device_info.device.type = MEDIA_TAB_VIDEO_CAPTURE;
  InitWithDeviceInfo(device_info);

  // Specify max and min size constraints with different aspect ratios.
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMaxWidth, 1920);
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMaxHeight, 1080);
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMinWidth, 0);
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMinHeight, 0);
  constraint_factory()->AddMandatory(MediaStreamVideoSource::kMaxFrameRate,
                                     60.0);

  media::VideoCaptureParams expected_params;
  expected_params.requested_format.frame_size.SetSize(1920, 1080);
  expected_params.requested_format.frame_rate = 60.0;
  expected_params.requested_format.pixel_format =
      media::VIDEO_CAPTURE_PIXEL_FORMAT_I420;
  expected_params.resolution_change_policy =
      media::RESOLUTION_POLICY_ANY_WITHIN_LIMIT;

  EXPECT_CALL(mock_delegate(), StartCapture(expected_params, _, _, _)).Times(1);
  blink::WebMediaStreamTrack track = StartSource();
  // When the track goes out of scope, the source will be stopped.
  EXPECT_CALL(mock_delegate(), StopCapture());
}

TEST_F(MediaStreamVideoCapturerSourceTest,
       DeviceCaptureConstraintsSupportPowerLineFrequency) {
  for (int frequency = -100; frequency < 100; ++frequency) {
    StreamDeviceInfo device_info;
    device_info.device.type = MEDIA_DEVICE_VIDEO_CAPTURE;
    InitWithDeviceInfo(device_info);
    constraint_factory_ = MockMediaConstraintFactory();
    constraint_factory()->AddOptional(
        VideoCapturerDelegate::kPowerLineFrequency, frequency);

    media::VideoCaptureParams expected_params;
    expected_params.requested_format.frame_size.SetSize(
        MediaStreamVideoSource::kDefaultWidth,
        MediaStreamVideoSource::kDefaultHeight);
    expected_params.requested_format.frame_rate =
        MediaStreamVideoSource::kDefaultFrameRate;
    expected_params.requested_format.pixel_format =
        media::VIDEO_CAPTURE_PIXEL_FORMAT_I420;
    expected_params.resolution_change_policy =
        media::RESOLUTION_POLICY_FIXED_RESOLUTION;
    if (frequency == 50) {
      expected_params.power_line_frequency =
          media::PowerLineFrequency::FREQUENCY_50HZ;
    } else if (frequency == 60) {
      expected_params.power_line_frequency =
          media::PowerLineFrequency::FREQUENCY_60HZ;
    } else {
      expected_params.power_line_frequency =
          media::PowerLineFrequency::FREQUENCY_DEFAULT;
    }

    EXPECT_CALL(mock_delegate(), StartCapture(expected_params, _, _, _))
        .Times(1);
    blink::WebMediaStreamTrack track = StartSource();
    // When the track goes out of scope, the source will be stopped.
    EXPECT_CALL(mock_delegate(), StopCapture());
  }
}

TEST_F(MediaStreamVideoCapturerSourceTest,
       InvalidPowerLineFrequencyHandledProperly) {
  // Test out other varieties of invalid input, like non-numeric strings.
  StreamDeviceInfo device_info;
  device_info.device.type = MEDIA_DEVICE_VIDEO_CAPTURE;
  InitWithDeviceInfo(device_info);
  constraint_factory_ = MockMediaConstraintFactory();
  constraint_factory()->AddOptional(VideoCapturerDelegate::kPowerLineFrequency,
                                    std::string("this is not a frequency"));

  media::VideoCaptureParams expected_params;
  expected_params.requested_format.frame_size.SetSize(
      MediaStreamVideoSource::kDefaultWidth,
      MediaStreamVideoSource::kDefaultHeight);
  expected_params.requested_format.frame_rate =
      MediaStreamVideoSource::kDefaultFrameRate;
  expected_params.requested_format.pixel_format =
      media::VIDEO_CAPTURE_PIXEL_FORMAT_I420;
  expected_params.resolution_change_policy =
      media::RESOLUTION_POLICY_FIXED_RESOLUTION;
  // Invalid frequencies should result in default setting.
  expected_params.power_line_frequency =
      media::PowerLineFrequency::FREQUENCY_DEFAULT;

  EXPECT_CALL(mock_delegate(), StartCapture(expected_params, _, _, _)).Times(1);
  blink::WebMediaStreamTrack track = StartSource();
  // When the track goes out of scope, the source will be stopped.
  EXPECT_CALL(mock_delegate(), StopCapture());
}

TEST_F(MediaStreamVideoCapturerSourceTest, Ended) {
  StreamDeviceInfo device_info;
  device_info.device.type = MEDIA_DESKTOP_VIDEO_CAPTURE;
  scoped_ptr<VideoCapturerDelegate> delegate(
      new VideoCapturerDelegate(device_info));
  VideoCapturerDelegate* delegate_ptr = delegate.get();
  source_ = new MediaStreamVideoCapturerSource(
      base::Bind(&MediaStreamVideoCapturerSourceTest::OnSourceStopped,
                 base::Unretained(this)),
      delegate.Pass());
  source_->SetDeviceInfo(device_info);
  webkit_source_.initialize(base::UTF8ToUTF16("dummy_source_id"),
                            blink::WebMediaStreamSource::TypeVideo,
                            base::UTF8ToUTF16("dummy_source_name"),
                            false /* remote */, true /* readonly */);
  webkit_source_.setExtraData(source_);
  webkit_source_id_ = webkit_source_.id();
  blink::WebMediaStreamTrack track = StartSource();
  message_loop_.RunUntilIdle();

  delegate_ptr->OnStateUpdate(VIDEO_CAPTURE_STATE_STARTED);
  message_loop_.RunUntilIdle();
  EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateLive,
            webkit_source_.readyState());

  EXPECT_FALSE(source_stopped_);
  delegate_ptr->OnStateUpdate(VIDEO_CAPTURE_STATE_ERROR);
  message_loop_.RunUntilIdle();
  EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateEnded,
            webkit_source_.readyState());
  // Verify that MediaStreamSource::SourceStoppedCallback has been triggered.
  EXPECT_TRUE(source_stopped_);
}

class FakeMediaStreamVideoSink : public MediaStreamVideoSink {
 public:
  FakeMediaStreamVideoSink(base::TimeTicks* capture_time,
                           media::VideoFrameMetadata* metadata,
                           base::Closure got_frame_cb)
      : capture_time_(capture_time),
        metadata_(metadata),
        got_frame_cb_(got_frame_cb) {}

  void OnVideoFrame(const scoped_refptr<media::VideoFrame>& frame,
                    base::TimeTicks capture_time) {
    *capture_time_ = capture_time;
    metadata_->Clear();
    base::DictionaryValue tmp;
    frame->metadata()->MergeInternalValuesInto(&tmp);
    metadata_->MergeInternalValuesFrom(tmp);
    base::ResetAndReturn(&got_frame_cb_).Run();
  }

 private:
  base::TimeTicks* const capture_time_;
  media::VideoFrameMetadata* const metadata_;
  base::Closure got_frame_cb_;
};

TEST_F(MediaStreamVideoCapturerSourceTest, CaptureTimeAndMetadataPlumbing) {
  StreamDeviceInfo device_info;
  device_info.device.type = MEDIA_DESKTOP_VIDEO_CAPTURE;
  InitWithDeviceInfo(device_info);

  VideoCaptureDeliverFrameCB deliver_frame_cb;
  VideoCapturerDelegate::RunningCallback running_cb;

  EXPECT_CALL(mock_delegate(), StartCapture(_, _, _, _))
      .Times(1)
      .WillOnce(testing::DoAll(testing::SaveArg<1>(&deliver_frame_cb),
                               testing::SaveArg<3>(&running_cb)));
  EXPECT_CALL(mock_delegate(), StopCapture());
  blink::WebMediaStreamTrack track = StartSource();
  running_cb.Run(true);

  base::RunLoop run_loop;
  base::TimeTicks reference_capture_time =
      base::TimeTicks::FromInternalValue(60013);
  base::TimeTicks capture_time;
  media::VideoFrameMetadata metadata;
  FakeMediaStreamVideoSink fake_sink(
      &capture_time, &metadata,
      media::BindToCurrentLoop(run_loop.QuitClosure()));
  FakeMediaStreamVideoSink::AddToVideoTrack(
      &fake_sink, base::Bind(&FakeMediaStreamVideoSink::OnVideoFrame,
                             base::Unretained(&fake_sink)),
      track);
  const scoped_refptr<media::VideoFrame> frame =
      media::VideoFrame::CreateBlackFrame(gfx::Size(2, 2));
  frame->metadata()->SetDouble(media::VideoFrameMetadata::FRAME_RATE, 30.0);
  child_process_->io_task_runner()->PostTask(
      FROM_HERE, base::Bind(deliver_frame_cb, frame, reference_capture_time));
  run_loop.Run();
  FakeMediaStreamVideoSink::RemoveFromVideoTrack(&fake_sink, track);
  EXPECT_EQ(reference_capture_time, capture_time);
  double metadata_value;
  EXPECT_TRUE(metadata.GetDouble(media::VideoFrameMetadata::FRAME_RATE,
                                 &metadata_value));
  EXPECT_EQ(30.0, metadata_value);
}

}  // namespace content