Skip to content

Comments

feat: add createDisplayMedia API#88

Merged
brycetham merged 4 commits intomainfrom
btham/create_display_media
Feb 4, 2025
Merged

feat: add createDisplayMedia API#88
brycetham merged 4 commits intomainfrom
btham/create_display_media

Conversation

@brycetham
Copy link
Collaborator

@brycetham brycetham commented Jan 31, 2025

This PR adds a new createDisplayMedia API that calls getDisplayMedia with additional options not currently possible with the existing createDisplayStream and createDisplayStreamWithAudio APIs, as part of SPARK-610118. In particular, they add the following options:

  • Video and audio device constraints.
  • Ability to specify whether to offer the current tab as the most prominent capture source.
  • Ability to specify whether to allow the user to select the current tab for capture.
  • Ability to specify whether to allow the user to dynamically switch the shared tab during screen-sharing.
  • Ability to specify whether to offer the user the option to choose display surfaces whose type is monitor.
  • Ability to specify whether to include the system audio among the possible audio sources offered to the user.
  • CaptureController to further manipulate the capture session.

I've also cleaned up some of the unit tests to remove some logic that I don't believe are necessary.

Summary by CodeRabbit

  • New Features

    • Enhanced display media capture functionality with more granular configuration options.
    • Added support for simultaneous video and system audio stream creation.
    • Introduced CaptureController for advanced media capture session management.
  • Improvements

    • Refined media stream creation methods with clearer parameter naming.
    • Improved backward compatibility for existing media stream methods.
    • Expanded test coverage for media stream functionalities, ensuring robust validation of behavior under various configurations.

@coderabbitai
Copy link

coderabbitai bot commented Jan 31, 2025

Walkthrough

The changes focus on enhancing media stream creation capabilities in the device management module. A new createDisplayMedia function replaces the previous createDisplayStream and createDisplayStreamWithAudio methods, offering more flexible configuration for display and audio stream capture. A new CaptureController interface is introduced to provide additional control over capture sessions, including focus behavior management. Comprehensive tests for the new functionality have also been added, along with updates to existing tests for clarity and correctness.

Changes

File Change Summary
src/device/device-management.ts - Added CaptureController interface with setFocusBehavior method
- Replaced createDisplayStream with enhanced createDisplayMedia
- Updated function to support more granular stream creation options
- Added backward-compatible createDisplayStream wrapper
- Renamed parameters in createCameraStream and createMicrophoneStream for clarity
src/device/device-management.spec.ts - Added comprehensive test suite for createDisplayMedia
- Updated existing test cases for media stream creation
- Simplified type assertions in mock configurations
src/media/index.ts - Added CaptureController interface
- Updated getDisplayMedia function to include new optional properties

Sequence Diagram

sequenceDiagram
    participant User
    participant DeviceManagement
    participant Browser
    participant CaptureController

    User->>DeviceManagement: createDisplayMedia(options)
    DeviceManagement->>Browser: getDisplayMedia(constraints)
    Browser-->>DeviceManagement: Display Stream
    opt Audio Capture
        DeviceManagement->>Browser: Capture System Audio
        Browser-->>DeviceManagement: System Audio Stream
    end
    opt Focus Control
        DeviceManagement->>CaptureController: setFocusBehavior
    end
    DeviceManagement-->>User: [DisplayStream, AudioStream]
Loading

Poem

🐰 A Rabbit's Ode to Media Streams 🎥
With streams so bright and capture clear,
Display and audio, now without fear!
Constraints and options, a developer's delight,
CodeRabbit's magic makes streaming just right!
Hop, hop, hurray for media's new might! 🎉

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

constructor: Constructor<T>,
videoContentHint?: VideoContentHint
): Promise<T> {
export async function createDisplayMedia<
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly I'm a little iffy about the name of this API. Nothing about createDisplayMedia tells me it's a more advanced alternative to createDisplayStreamWithAudio but I'm not sure I have any better ideas.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this name for sure. It's not telling you that it's a more advanced alternative, but as an option, if we need to explain this difference to someone, we can just add an API description in README.

surfaceSwitching: options.video.surfaceSwitching,
systemAudio: options.audio?.systemAudio,
monitorTypeSurfaces: options.video.monitorTypeSurfaces,
} as any); // eslint-disable-line @typescript-eslint/no-explicit-any
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most of these additional options are experimental so TypeScript does not have the proper types yet. Casting as any is necessary here to prevent TypeScript from yelling at us.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@brycetham Could we consider having global.d.ts with the right types api getDisplayMedia for our needs instead of casting to any? I feel for this purpose having own d.ts feels right

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good call. Actually, I noticed that we use our own getDisplayMedia definition from media/index.ts, so I think I can just redefine the parameters there. That way, I don't have to mess with the global scope and it is still well defined somewhere in our repo.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/device/device-management.ts (3)

153-168: Potential overshadowing of 'constructor' property.
While using a property named constructor is valid, it can overshadow the global property. Consider renaming it to something like streamConstructor for clarity.

-    constructor: Constructor<T>;
+    streamConstructor: Constructor<T>;

173-182: Avoid using as any if possible.
Casting to any can mask type inconsistencies. A more robust type definition may help catch potential issues at compile-time.


214-214: Consider renaming the 'constructor' parameter.
Renaming avoids confusion with the global constructor property. For instance, use something like streamConstructor for clarity.

-  constructor: Constructor<T>,
+  streamConstructor: Constructor<T>,
🧰 Tools
🪛 Biome (1.9.4)

[error] 214-214: Do not shadow the global "constructor" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b9c22d and 377c902.

📒 Files selected for processing (2)
  • src/device/device-management.spec.ts (8 hunks)
  • src/device/device-management.ts (3 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/device/device-management.ts

[error] 214-214: Do not shadow the global "constructor" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🔇 Additional comments (22)
src/device/device-management.ts (8)

28-34: Interface definition is well-structured.
The CaptureController interface competently outlines the behavior options. Its typed approach for setFocusBehavior is clear and coherent.


124-147: Thorough documentation.
This docstring effectively conveys the purpose, parameters, and return value for createDisplayMedia, aiding maintainability and discoverability.


149-152: Generics usage is well designed.
The function signature accommodates typed returns for both display and system audio streams without unnecessary duplication.


170-171: Revisit default constraints assignment.
Setting these fields to true or a boolean when no explicit constraints are provided may lead to unintended defaults. Ensure this aligns with expected behavior.


186-186: Error handling is consistent.
This classification of capture errors aligns well with existing error patterns, maintaining uniformity across the codebase.


189-206: Clean separation of display and audio streams.
Returning [displayStream, null] when audio is unavailable is a straightforward approach. Good job adhering to the fail-safe pattern.


213-216: Backward-compatible helper function.
createDisplayStream delegates to createDisplayMedia while preserving the simpler API signature for existing consumers.

🧰 Tools
🪛 Biome (1.9.4)

[error] 214-214: Do not shadow the global "constructor" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)


241-244: Nice reuse of createDisplayMedia.
Pulling common logic into a single function reduces redundancy and potential maintenance overhead.

src/device/device-management.spec.ts (14)

1-1: Added import from '../errors'.
No concerns here. This simply references error classes for test usage.


11-11: Imported CaptureController.
Allows testing the newly introduced capture session manipulation.


14-14: Added createDisplayMedia import for tests.
Extends the suite to cover the new function under various scenarios.


30-30: Mocking getUserMedia for microphone tests.
Ensures reproducible and isolated test conditions.


79-79: Mocking getUserMedia for camera tests.
Ensures camera-based functionality is tested consistently without requiring actual devices.


126-126: Spy on getUserMedia for combined streams.
Remains consistent with other test mocks, providing a controlled environment.


172-192: Initial tests for createDisplayMedia.
Verifies standard usage, including video-only and video+audio capture. This covers essential use cases thoroughly.


194-214: Ensuring constraints and content hints are honored.
These test cases confirm that custom constraints are passed to getDisplayMedia and content hints are correctly assigned to the resulting stream.


216-297: Robust coverage of advanced capture options.
The suite tests preferCurrentTab, selfBrowserSurface, surfaceSwitching, systemAudio, and CaptureController, providing comprehensive confidence in the new logic.


300-300: Mock setup for createDisplayStream.
Demonstrates consistent mocking of getDisplayMedia just as in the other display-related tests.


306-306: Verifying getDisplayMedia invocation arguments.
Ensures only video is requested with no audio track for createDisplayStream.


310-310: Assertion count check.
expect.assertions(1) helps ensure the test is verifying the correct number of expectations.


325-325: Mocking getDisplayMedia for audio-inclusive tests.
Maintains a uniform approach in all display-stream test scenarios.


356-356: Selective mocking ensures audio track presence.
This approach is essential for testing audio track logic distinctly.

bbaldino
bbaldino previously approved these changes Jan 31, 2025
Copy link
Collaborator

@bbaldino bbaldino left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm 👍

edvujic
edvujic previously approved these changes Feb 3, 2025
Copy link
Contributor

@edvujic edvujic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

k-wasniowski
k-wasniowski previously approved these changes Feb 3, 2025
szotrabh
szotrabh previously approved these changes Feb 3, 2025
// So we define the interface ourselves here.
// See https://developer.mozilla.org/en-US/docs/Web/API/CaptureController.
export interface CaptureController {
setFocusBehavior(behavior: 'auto' | 'always' | 'never'): Promise<void>;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question about these behavior states should we keep wording from the spec?

enum CaptureStartFocusBehavior {
"focus-capturing-application",
"focus-captured-surface",
"no-focus-change"
};

https://www.w3.org/TR/screen-capture/#dom-capturestartfocusbehavior:~:text=5.4.2%20CaptureStartFocusBehavior

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, thanks for catching that. Admittedly, I think I tried using copilot here but didn't verify that the types were correct. Lesson learned 😅

@brycetham brycetham dismissed stale reviews from szotrabh, k-wasniowski, and edvujic via de695d1 February 3, 2025 18:12
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/media/index.ts (1)

9-16: Add JSDoc documentation for the CaptureController interface.

The interface is well-defined, but adding JSDoc documentation would improve code maintainability and IDE support.

 // CaptureController is experimental so TypeScript doesn't have a type for it yet.
 // So we define the interface ourselves here.
 // See https://developer.mozilla.org/en-US/docs/Web/API/CaptureController.
+/**
+ * Experimental interface for controlling capture behavior.
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/CaptureController
+ */
 export interface CaptureController {
+  /**
+   * Sets the focus behavior for the capture session.
+   * @param behavior - The desired focus behavior.
+   * @returns A promise that resolves when the behavior is set.
+   */
   setFocusBehavior(
     behavior: 'focus-capturing-application' | 'focus-captured-surface' | 'no-focus-change'
   ): Promise<void>;
 }
src/device/device-management.spec.ts (1)

172-300: Consider adding error handling test cases.

The test suite is comprehensive for successful scenarios, but could benefit from additional test cases:

  • Error handling when getDisplayMedia fails
  • Edge cases with invalid option combinations

Example test case:

it('should handle getDisplayMedia failure', async () => {
  expect.assertions(1);
  
  jest.spyOn(media, 'getDisplayMedia').mockRejectedValueOnce(new Error('Permission denied'));
  
  await expect(createDisplayMedia({
    video: { displayStreamConstructor: LocalDisplayStream }
  })).rejects.toThrow('Permission denied');
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee85f18 and de695d1.

📒 Files selected for processing (3)
  • src/device/device-management.spec.ts (8 hunks)
  • src/device/device-management.ts (6 hunks)
  • src/media/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/device/device-management.ts
🔇 Additional comments (4)
src/media/index.ts (2)

31-40: LGTM!

The documentation is clear and properly references the experimental options.


41-51: LGTM!

The function signature is well-structured with proper typing for all experimental options.

src/device/device-management.spec.ts (2)

1-26: LGTM!

The test setup is well-organized with proper imports and mocking configuration.


30-34: LGTM!

The mock implementations are well-documented and correctly configured.

Also applies to: 303-303, 328-328

antsukanova
antsukanova previously approved these changes Feb 4, 2025
Copy link
Contributor

@antsukanova antsukanova left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks

edvujic
edvujic previously approved these changes Feb 4, 2025
SomeBody16
SomeBody16 previously approved these changes Feb 4, 2025
Copy link

@SomeBody16 SomeBody16 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, with one comment

jest
.spyOn(media, 'getUserMedia')
.mockReturnValue(Promise.resolve(mockStream as unknown as MediaStream));
jest.spyOn(media, 'getUserMedia').mockReturnValue(Promise.resolve(mockStream));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://jestjs.io/docs/mock-function-api#mockfnmockresolvedvaluevalue

mockFn.mockResolvedValue(value)

Shorthand for:

jest.fn().mockImplementation(() => Promise.resolve(value));

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@brycetham brycetham dismissed stale reviews from SomeBody16, edvujic, and antsukanova via a59db52 February 4, 2025 13:32
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/device/device-management.spec.ts (2)

172-300: Comprehensive test coverage for createDisplayMedia API.

The test suite thoroughly covers all aspects of the new API:

  • Basic video-only and video+audio scenarios
  • Constraint handling
  • Content hint preservation
  • Advanced options (preferCurrentTab, selfBrowserSurface, etc.)
  • CaptureController integration

One suggestion to improve test maintainability:

Consider extracting common test setup into a beforeEach block:

 describe('createDisplayMedia', () => {
   jest.spyOn(media, 'getDisplayMedia').mockResolvedValue(mockStream);
+
+  const defaultVideoOptions = {
+    displayStreamConstructor: LocalDisplayStream,
+  };
+
+  const defaultAudioOptions = {
+    systemAudioStreamConstructor: LocalSystemAudioStream,
+  };

This would reduce repetition in test cases and make them more focused on the specific scenarios being tested.


288-289: Consider adding type assertion alternatives.

Instead of using type assertion with as, consider creating a proper mock object:

-const fakeController: CaptureController = {} as CaptureController;
+const fakeController: Partial<CaptureController> = {
+  // Add minimum required properties based on CaptureController interface
+};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between de695d1 and a59db52.

📒 Files selected for processing (1)
  • src/device/device-management.spec.ts (8 hunks)
🔇 Additional comments (4)
src/device/device-management.spec.ts (4)

1-19: LGTM! Clean import organization.

The imports are well-organized, with the new CaptureController import properly placed among other media-related imports.


29-30: Great improvement in mock setup!

The change from mockReturnValue(Promise.resolve(...)) to mockResolvedValue makes the test code more concise and readable.

Also applies to: 79-80, 126-127, 173-174, 303-304, 328-329, 357-358


308-309: LGTM! Proper test expectations.

The test correctly verifies that getDisplayMedia is called with audio: false for video-only streams.


338-340: LGTM! Proper test expectations.

The test correctly verifies that getDisplayMedia is called with audio: true when audio is requested.

@brycetham brycetham merged commit 329d98d into main Feb 4, 2025
2 checks passed
@brycetham brycetham deleted the btham/create_display_media branch February 4, 2025 19:15
mickelr pushed a commit to mickelr/webrtc-core that referenced this pull request Feb 12, 2025
# [2.12.0](webex/webrtc-core@v2.11.0...v2.12.0) (2025-02-04)

### Features

* add createDisplayMedia API ([webex#88](webex#88)) ([329d98d](webex@329d98d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants