phoboslab / jsmpeg

MPEG1 Video Decoder in JavaScript
MIT License
6.31k stars 1.43k forks source link

Example of a custom live source #359

Open Firescar96 opened 3 years ago

Firescar96 commented 3 years ago

I didn't see an example of creating a custom source that could be used to receive data from channels that aren't websockets. Maybe the code that is here is enough, but I thought something like this would be helpful to others.

// main js script
    this.livePlayer = new JSMpeg.Player('pipe', {
      source: JSMpegPipeSource,
      canvas: document.getElementById('canvas'),
      videoBufferSize: 0,
      audioBufferSize: 0,
    });
....
  receiveData(data) {
    const message = JSON.parse(data);

    if(message.flag == 'liveStreamData' && this.streamJoined && this.streamJoined) {
      const messageData = new Uint8Array(message.data).buffer;
      this.livePlayer.source.write(messageData);
      return;
    }
}
// JSMpegPipeSource.js
class JSMpegPipeSource {
  constructor(url, options) {
    this.url = url;
    this.options = options;

    //video/audio output desination
    this.destination = null;

    //streaming tells jsmpeg to not collect timestamps and use the latest frame
    //unfortunately it also forces jsmpeg autoplay on, so we can't create the jsmpeg instance til after we want to start making noise
    this.streaming = true;
  }

  connect(destination) {
    this.destination = destination;
  }

  destroy() {
    this.running = false;
  }

  start() {
    this.running = true;
    this.established = true;
  }

  resume(secondsHeadroom) {}

  write(data) {
    if(this.destination && this.established) {
      this.destination.write(data);
    }
  }
}

export default JSMpegPipeSource;