import { AliRtcPlugin, LocalStreamInfo } from 'aliyun-rtc-sdk';
export default class UserNamePlugin extends AliRtcPlugin {
private canvas: HTMLCanvasElement;
private requestId?: number;
constructor(text: string) {
super('UserNamePlugin');
this.options = { text };
this.canvas = document.createElement('canvas');
}
isSupported(): boolean {
return true;
}
setOptions(options: { text: string }): void {
this.options = options;
}
shouldUpdate(): boolean {
return true;
}
process(streamInfo: LocalStreamInfo): Promise<void> {
if (streamInfo.currentVideoTrack) {
const videoTrack = streamInfo.currentVideoTrack as MediaStreamVideoTrack;
const settings = videoTrack.getSettings();
this.canvas.width = settings.width!;
this.canvas.height = settings.height!;
const stream = new MediaStream([videoTrack]);
const videoElement = document.createElement('video');
videoElement.srcObject = stream;
videoElement.play();
const ctx = this.canvas.getContext('2d')!;
const drawFrame = () => {
if (videoElement.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
ctx.drawImage(videoElement, 0, 0, this.canvas.width, this.canvas.height);
ctx.fillStyle = 'white';
ctx.font = '40px Arial';
ctx.textAlign = 'right';
ctx.fillText(this.options.text, this.canvas.width - 20, this.canvas.height - 20);
}
this.requestId = requestAnimationFrame(drawFrame);
}
this.requestId = requestAnimationFrame(drawFrame);
const newStream = this.canvas.captureStream(settings.frameRate);
const newVideoTrack = newStream.getVideoTracks()[0];
streamInfo.updateVideoTrack(newVideoTrack);
} else if (this.requestId) {
cancelAnimationFrame(this.requestId);
}
return Promise.resolve();
}
}