# Better support custom MediaStreams in openvidu-browser

**URL:** <https://openvidu.discourse.group/t/better-support-custom-mediastreams-in-openvidu-browser/4680>\
**Category:** Request for enhancement\
**Created:** [June 29, 2023, 11:26am UTC](https://openvidu.discourse.group/t/better-support-custom-mediastreams-in-openvidu-browser/4680 "2023-06-29T11:26:58Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Semmel](https://yyz2.discourse-cdn.com/free1/user_avatar/openvidu.discourse.group/semmel/32/140_2.png) [@Semmel](https://openvidu.discourse.group/u/Semmel)\
**Post date:** [June 29, 2023, 11:26am UTC](https://openvidu.discourse.group/t/better-support-custom-mediastreams-in-openvidu-browser/4680/1 "2023-06-29T11:26:58Z")

</div>

TLDR; To help detecting disposal of local MediaStreamTracks fire an [`"ended"` event](https://w3c.github.io/mediacapture-main/getusermedia.html#event-mediastreamtrack-ended) every time openvidu-browser calls [`track.stop()`](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/stop).

With _Custom MediaStreams_ I mean such which are created (`navigator.mediaDevices.getUserMedia()`) and _disposed_ locally by my browser application or the local operating system.

Usually, I hand the MediaStreamTracks of my Custom MediaStream to OpenVidu by `OpenVidu.initPublisher(null, {audioSource: audioTrack, videoSource: videoTrack});`. So far so good.

Sometimes OpenVidu _disposes_ my local tracks (e.g. in `Stream.disposeMediaStream()`) and that’s fine too. However in these cases I need to _indirectly detect the disposal_ by subscribing for `"streamDestroyed"` or other Publisher events. (Reason is that [`track.stop() does not fire "ended"`](https://stackoverflow.com/questions/55953038/why-is-the-ended-event-not-firing-for-this-mediastreamtrack)). That indirect detection process adds IMO unnecessary dependencies in my code.

Also [discussed on SOW](https://stackoverflow.com/questions/55953038/why-is-the-ended-event-not-firing-for-this-mediastreamtrack), I find that the standard is flawed:

- Sure I know when I my code calls `track.stop()`, but that can be in many places. Wiring cleanup code every time is no good style. Better use events to support loose coupling and write the cleanup code once.
- The standard clearly fails if I hand my MediaStreamTracks to a library (like OpenVidu) which then has the liberty to `track.stop()` without me getting a notification for that.

Do you see any danger if openvidu-browser adds a `track.dispatchEvent(new Event("ended"))` to `track.stop()`?

If not, I’d file a PR.

Btw. Firefox has [a bug in their MediaStreamTrack implementation](https://bugzilla.mozilla.org/show_bug.cgi?id=1473457) as an EventTarget so that you cannot use `track.addEventListener("ended", …)` to handle `track.dispatchEvent(new Event("ended"))` events. You’ll need to work around that with `track.onended`.
