Skip to content

Overriding media acquisition is too hard #709

Closed

Description

@nud

Is your feature request related to a problem? Please describe.
Maintainers of SIP.js have made clear in several instances (#588, #602, #696) that using a custom MediaStream as a source instead of getUserMedia() should be done through the implementation of a custom SessionDescriptionHandler. I'm fine with that.

In 0.14 however, the library has been rewritten in typescript, and most of the methods of Web.SessionDescriptionHandler are now private. This means that, to implement the rather small change from #588, one is required to reimplement the whole getDescription() method, while previously overwriting acquire() was enough.

Duplicating everything adds to the maintenance burden, as it forces to track every change to the upstream class. Bugs can easily slip through. It also means duplicating the whole class including modifier handling, ICE, etc., which are already solved problems.

Describe the solution you'd like
Because of that, would it be possible to devise a way to only override the acquisition part of Web.SessionDescriptionHandler (ideally, only the actual stream creation part)?

I can imagine two ways this could be implemented, depending on what fits the library style best, while not adding much maintenance burden to SIP.js itself:

  • through inheritance, using a protected getMediaStreams(constraints: any): Promise<MediaStream[]> method,
  • through inheritance, by splitting getDescription() into individually overridable parts,
  • though some sort of callback in the SessionDescriptionHandlerOptions interface or in events.

Also, due to the way the library uses different options in different contexts (in this case, UA sessionDescriptionHandlerFactoryOptions at creation time but constructor options at INVITE time) it might be useful to pass the options along to whatever solution is chosen.

Describe alternatives you've considered
I tried implementing a modifier that would add mediastream tracks and call createOffer() again, but this fails due to Firefox complaining that you cannot call createOffer() twice.

I could not find any other hook or overridable methods that could make this feature available easily.

Additional context
I need to create a session without requesting user device access.

Activity

  1. changed the title [-]Overriding media acquisition is too hard mediastream[/-] [+]Overriding media acquisition is too hard[/+] on Jul 5, 2019
  2. nud commented on Jul 5, 2019

    @nud
    ContributorAuthor

    For reference, my first proposal would look something like this:

    diff --git a/src/Web/SessionDescriptionHandler.ts b/src/Web/SessionDescriptionHandler.ts
    index 831abbc..190b0e9 100644
    --- a/src/Web/SessionDescriptionHandler.ts
    +++ b/src/Web/SessionDescriptionHandler.ts
    @@ -589,10 +589,7 @@ export class SessionDescriptionHandler extends EventEmitter implements SessionDe
         };
       }
     
    -  private acquire(constraints: any): any {
    -    // Default audio & video to true
    -    constraints = this.checkAndDefaultConstraints(constraints);
    -
    +  protected getMediaStreams(constraints: any): Promise<MediaStream[]> {
         return new Promise((resolve, reject) => {
           /*
            * Make the call asynchronous, so that ICCs have a chance
    @@ -624,7 +621,14 @@ export class SessionDescriptionHandler extends EventEmitter implements SessionDe
             this.logger.error(error.error);
           }
           throw error;
    -    }).then((streams) => {
    +    });
    +  }
    +
    +  private acquire(constraints: any): any {
    +    // Default audio & video to true
    +    constraints = this.checkAndDefaultConstraints(constraints);
    +
    +    return this.getMediaStreams(constraints).then((streams) => {
           this.logger.log("acquired local media streams");
           try {
             // Remove old tracks

    I'm fine with providing the pull request as soon as a solution is chosen.

  3. grischa commented on Jul 8, 2019

    @grischa

    @nud I was fighting with this, too. I agree there should be a hook to override only media acquisition.
    However, in the meantime, you could try this hack, seems to work for me:

    class MySDH extends Web.SessionDescriptionHandler {
      constructor(...) {
        this["acquire"] = this.myAcquire;
      }
      private myAcquire(...) { ... }
    }

    After all TS is just JS when you need to get work done ;)

  4. nud commented on Jul 8, 2019

    @nud
    ContributorAuthor

    @grischa that looks indeed like a solution, but I am afraid that the typescript compiler could eventually benefit from the "privateness" of the method to optimize it out / change its name.

    IMO an officially supported way is desirable, especially as the need seems to be pretty common.

    Also, some missing public types (Logger, SessionDescriptionHandlerObserver) make it hard to inherit from Web.SessionDescriptionHandler, so that part could be improved as well.

  5. nud commented on Jul 8, 2019

    @nud
    ContributorAuthor

    For reference, here is my current not-pretty-at-all implementation:

    import {
      SessionDescriptionHandler as WebSessionDescriptionHandler,
      SessionDescriptionHandlerModifiers,
      InviteClientContext,
      InviteServerContext,
    } from "sip.js";
    
    // FIXME: we need pretty intimate imports to be able to inherit from
    // SIP.Web.SessionDescriptionHandler.
    import { SessionDescriptionHandlerObserver } from "sip.js/lib/Web/SessionDescriptionHandlerObserver";
    import { WebSessionDescriptionHandlerOptions } from "sip.js/lib/Web/SessionDescriptionHandler";
    import { BodyObj } from "sip.js/lib/session-description-handler";
    import { Logger as SIPLogger } from "sip.js/lib/core/log";
    
    export interface SessionDescriptionHandlerOptions
      extends WebSessionDescriptionHandlerOptions {
      mediaStream?: Promise<MediaStream>;
    }
    
    /*
     * This SessionDescriptionHandler implements a way to provide a media stream
     * as an audio source instead of a media device.
     *
     * See https://github.com/onsip/SIP.js/pull/588
     */
    export class SessionDescriptionHandler extends WebSessionDescriptionHandler {
      public static factory(
        session: InviteClientContext | InviteServerContext,
        options: any,
      ): SessionDescriptionHandler {
        const logger = session.ua.getLogger(
          "sip.invitecontext.sessionDescriptionHandler",
          session.id,
        );
        const observer = new SessionDescriptionHandlerObserver(session, options);
        return new SessionDescriptionHandler(
          logger,
          observer,
          options as SessionDescriptionHandlerOptions,
        );
      }
    
      private defaultAcquire: (constraints: any) => any;
      private mediaStream?: Promise<MediaStream>;
    
      constructor(
        logger: SIPLogger,
        observer: SessionDescriptionHandlerObserver,
        options: SessionDescriptionHandlerOptions,
      ) {
        super(logger, observer, options);
        // If we have the "mediaStream" option, then we override the "acquire" method.
        // FIXME: use proper inheritance/overriding.
        // See https://github.com/onsip/SIP.js/issues/709
    
        this.defaultAcquire = this["acquire"];
        this["acquire"] = this.realAcquire;
      }
    
      private realAcquire(constaints: any) {
        if (this.mediaStream) {
          return this.acquireMediaStream(this.mediaStream);
        } else {
          return this.defaultAcquire.apply(this, constaints);
        }
      }
    
      private acquireMediaStream(mediaStream: Promise<MediaStream>) {
        return mediaStream.then(stream => {
          try {
            // Remove old tracks
            if (this.peerConnection.removeTrack) {
              this.peerConnection.getSenders().forEach(sender => {
                this.peerConnection.removeTrack(sender);
              });
            }
    
            // Add new tracks
            stream.getTracks().forEach(track => {
              this.peerConnection.addTrack(track, stream);
            });
    
            return Promise.resolve();
          } catch (e) {
            return Promise.reject(e);
          }
        });
      }
    
      public getDescription(
        options: WebSessionDescriptionHandlerOptions = {},
        modifiers: SessionDescriptionHandlerModifiers = [],
      ): Promise<BodyObj> {
        this.mediaStream = (options as SessionDescriptionHandlerOptions).mediaStream;
        return super.getDescription(options, modifiers);
      }
    
      public setDescription(
        sessionDescription: string,
        options: WebSessionDescriptionHandlerOptions = {},
        modifiers: SessionDescriptionHandlerModifiers = [],
      ): Promise<void> {
        this.mediaStream = (options as SessionDescriptionHandlerOptions).mediaStream;
        return super.setDescription(sessionDescription, options, modifiers);
      }
    }

    It is worth noting that:

    • we pass the media stream at invite time (not at UA initialization time) so it forces us to do some additional moving-around operations that could be avoided by passing the options to the hypothetic getMedia handler.
    • we need to import a bunch of semi-private stuff from SIP.js to be able to inhertit from the handler.

    IMO any improvement in these areas is worth taking, especially since I don't think this is such an uncommon case.

    Just off the top of my head, what about having some MediaStreamFactory class, whose default implementation would be to get the browser's user media? IT would not feel foreign to the current design and would be very flexible without requiring users to reimplement the whole SDP handling part.

  6. egreenmachine commented on Jul 8, 2019

    @egreenmachine
    Collaborator

    We just finished discussing this internally. We think that making the acquire function (and potentially others) protected is a great idea. The big issue is, once we do that, we are essentially supporting that interface moving forward. We want to take a bit of time and review these functions to make sure we like the headers and return types and then we will push an update to make them protected.

  7. nud commented on Jul 8, 2019

    @nud
    ContributorAuthor

    @egreenmachine glad to hear it! 👍

    Alternatively, providing some "mediastream" promise (that would default to getting the browser's devices) as a parameter might be a simpler and easier solution to maintain on your side, or splitting parts out as i suggested in my previous comments.

    I get that supporting inheritance is a big maintenance burden (composition is usually easier) but at the same time the Session Description Handler does way more than just "media management" at this point...

    Also, maybe some code could be shared between the react and the Web SDH? I didn't dig into the react one but I suspect the whole SDP management thing is very similar in both implementations.

  8. added a commit that references this issue on Jul 9, 2019
  9. egreenmachine commented on Jul 9, 2019

    @egreenmachine
    Collaborator

    I pushed 7caeb88 as a first pass at this. Let me know if it covers what you were looking for. We plan to do a bit more work here after the next release is settled.

  10. nud commented on Jul 9, 2019

    @nud
    ContributorAuthor

    @egreenmachine at first sight it looks nice. It certainly does the job for my own current use case. The improved typing is good. The small improvements I could suggest are:

    • passing the configuration object so that whoever implements that subclass can act according to the (maybe custom) options. Basically it could replace the constraints, as these are part of the options object.
    • export the types that are required to implement one's own factory, or make the actual class a factory option (I guess there is no need to override the constructor most of the time if you can pass extra options to getMediaStream())

    Thank you very much!

  11. egreenmachine commented on Jul 10, 2019

    @egreenmachine
    Collaborator

    export the types that are required to implement one's own factory, or make the actual class a factory option (I guess there is no need to override the constructor most of the time if you can pass extra options to getMediaStream())

    We already export the types needed to make your own factory... https://github.com/onsip/SIP.js/blob/master/src/session-description-handler-factory.ts. I am not sure what else you are asking for here.

  12. nud commented on Jul 11, 2019

    @nud
    ContributorAuthor

    @egreenmachine what I mean is this:

    if you want to inherit from Web.SessionDescriptionHandler, you will need at some point to call the constructor. It means you need access to the following types (from the code sample above):

    import { SessionDescriptionHandlerObserver } from "sip.js/lib/Web/SessionDescriptionHandlerObserver";
    import { WebSessionDescriptionHandlerOptions } from "sip.js/lib/Web/SessionDescriptionHandler";
    import { Logger } from "sip.js/lib/core/log";

    Otherwise you cannot write this:

      public static customFactory(
        session: InviteClientContext | InviteServerContext,
        options: any,
      ): SessionDescriptionHandler {
        const logger: Logger = session.ua.getLogger(
          "sip.invitecontext.sessionDescriptionHandler",
          session.id,
        );
        const observer = new SessionDescriptionHandlerObserver(session, options);
        return new MyOwnSessionDescriptionHandler(logger, observer, options);
      }

    If you want to create a new SessionDescriptionHandler subclass from scratch, you need to be able to override getDescription() and setDescription() so you need the following type:

    import { BodyObj } from "sip.js/lib/session-description-handler";

    These can be used already, but it involves looking into the library and importing the right private files.

    Most probably any type that is part of the prototype of a function that one is supposed to override should be part of the exported API.

  13. egreenmachine commented on Jul 11, 2019

    @egreenmachine
    Collaborator

    I see. You are absolutely correct that they are not exported. I do not want to export the Observer as we are moving towards a standard approach for the library with delegates. I will try and find some time to make the necessary changes and get the required interfaces public.

  14. nud commented on Jul 11, 2019

    @nud
    ContributorAuthor

    @egreenmachine if this is part of the legacy API that is going to die in 0.16 I would not spend too much time on this. Since many changes will be required anyway, importing private stuff, while bad practice, is not too bad :-)

    Thank you very much for the time you spent on this issue.

  15. john-e-riordan commented on May 27, 2020

    @john-e-riordan
    Collaborator

    Hi,

    #815 is a new implementation which I believe/hope addresses this issue.

    Media Acquisition

    The function which returns a new default SessionDescriptionHandlerFactory....

    export function defaultSessionDescriptionHandlerFactory(
      mediaStreamFactory?: (
        constraints: MediaStreamConstraints,
        sessionDescriptionHandler: SessionDescriptionHandler
      ) => Promise<MediaStream>
    ): SessionDescriptionHandlerFactory {
    

    now takes a MediaStreamFactory as a parameter...

    /**
     * Interface of factory function which produces a MediaStream.
     * @public
     */
    export type MediaStreamFactory = (
      constraints: MediaStreamConstraints,
      sessionDescriptionHandler: SessionDescriptionHandler
    ) => Promise<MediaStream>;
    

    So you may provide whatever implementation you wish to acquire a local MediaStream.

    If a MediaStreamFactory is not specified, a default which uses getUserMedia() is provided.

    This can be set via the existing UserAgentOption.sessionDescriptionHandlerFactory.

    Extending SessionDescription Handler

    I've attempt to make the new implementation extensible enough to be useful but without going so far as creating a maintenance headache. But I'm interested in feedback - particularly if it ends up resulting a "less is more" outcome.

  16. nud commented on May 28, 2020

    @nud
    ContributorAuthor

    @john-e-riordan here is what my current (0.16) implementation looks like:

    import { Session, Web } from "sip.js";
    
    export interface CustomMediaStreamConstraints extends MediaStreamConstraints {
      stream?: boolean;
    }
    
    export class SessionDescriptionHandler extends Web.SessionDescriptionHandler {
      public static factory(
        session: Session,
        options: any,
      ): SessionDescriptionHandler {
        const logger = session.userAgent.getLogger(
          "sip.SessionDescriptionHandler",
          session.id,
        );
        return new SessionDescriptionHandler(logger, options);
      }
    
      private createStream(): Promise<MediaStream> {
        // ...
      }
    
      protected getMediaStream(
        constraints: MediaStreamConstraints,
      ): Promise<MediaStream> {
        const c = constraints as CustomMediaStreamConstraints;
    
        return c.stream
          ? this.createStream()
          : super.getMediaStream(constraints);
      }
    }

    I suppose the 0.16 API already removed a bunch of obstacles. But the MediaStreamFactory sure looks nice as long as it can be set in the Invite options or receive parameters from there.

  17. nud commented on May 28, 2020

    @nud
    ContributorAuthor

    With your MR I suppose the code above will become something like this:

    import { MediaStreamFactory, Web } from "sip.js";
    
    function createStream(): Promise<MediaStream> {
       // ...
    }
    
    function customFactory(constraints: MediaStreamConstraints): Promise<MediaStream> => {
        const c = constraints as CustomMediaStreamConstraints;
    
        return c.stream ? createStream() : Web.defaultMediaStreamFactory()(constraints);
    }

    Then in the UA options:

    const options: UserAgentOptions = { 
       // ...
       mediaStreamFactory: customFactory;
       // replaces sessionDescriptionHandlerFactory: SessionDescriptionHandler.factory
    }

    Is that correct? I couldn't find the place where you set the stream factory in the MR.

  18. john-e-riordan commented on May 28, 2020

    @john-e-riordan
    Collaborator

    Hey,

    import { UserAgent, UserAgentOptions, Web } from "sip.js";
    
    // My custom media stream factory...
    const mediaStreamFactory: Web.MediaStreamFactory = (constraints: MediaStreamConstraints, sessionDescriptionHandler: Web.SessionDescriptionHandler): Promise<MediaStream> => {
      const mediaStream = new MediaStream(); 
      return Promise.resolve(mediaStream);
    }
    
    const options: UserAgentOptions = {
      sessionDescriptionHandlerFactory: Web.defaultSessionDescriptionHandlerFactory(mediaStreamFactory)
    }
    
    const myUA = new UserAgent(options);
    
  19. john-e-riordan commented on May 28, 2020

    @john-e-riordan
    Collaborator

    So you mentioned "as long as it can be set in the Invite options or receive parameters from there."

    From my prior comment above, you can see that the current constraints (from the invite options) and the sessionDescriptionHandler itself get passed to the custom mediaStreamFactory. I'd like to understand what else, if anything, you might need to pass and why?

  20. nud commented on May 28, 2020

    @nud
    ContributorAuthor

    @john-e-riordan no it's fine, currently I pass everything using the constraints object, the typing of which got relaxed in the 0.16 API.

    I just provided the code samples so that you get the use case, but I think your API proposal is fine.

  21. james-criscuolo commented on Jul 6, 2020

    @james-criscuolo
    Collaborator

    Closing this as the proposal was released in 0.17.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions