phoboslab / jsmpeg

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

Problem switching videos #424

Open TXMengXue opened 4 months ago

TXMengXue commented 4 months ago

const canvas = document.getElementById('videoCanvas');

if (player) { 
    player.destroy();
}
player = new JSMpeg.Player(url, {canvas: canvas}); 

image

TXMengXue commented 4 months ago
var elementCanvas = document.getElementById('videoCanvas');
if (player) {
    player.destroy();
    var ctx = elementCanvas.getContext("2d");
    ctx.fillStyle = "black"; 
    ctx.fillRect(0, 0, elementCanvas.width, elementCanvas.height); 
}
player = new JSMpeg.Player('ws://localhost:8083/', {canvas: elementCanvas}); 

image

phoboslab commented 4 months ago

Works for me™

Tested with

html:

<canvas id="video-canvas"></canvas>
<script type="text/javascript" src="jsmpeg.min.js"></script>
<script type="text/javascript">
    let player = null;
    let port = '8082';
    let canvas = document.getElementById('video-canvas');
    let toggleStreams = function() {
        port = port === '8082' ? '8084' : '8082';
        if (player) {
            player.destroy();
        }
        let url = 'ws://'+document.location.hostname+':'+port;
        player = new JSMpeg.Player(url, {canvas: canvas});
    }
    toggleStreams();
</script>
<button onclick="toggleStreams()">switch</button>

Terminal 1:

node websocket-relay.js zomg 8081 8082

Terminal 2:

ffmpeg -stream_loop -1 -re -i video.mp4 -f mpegts -codec:v mpeg1video -codec:a mp2 -b 0 http://127.0.0.1:8081/zomg

Terminal 3:

node websocket-relay.js zomg 8083 8084

Terminal 4:

# same input video but different size (`-s wxh`)
ffmpeg -stream_loop -1 -re -i video.mp4 -f mpegts -codec:v mpeg1video -codec:a mp2 -s 320x180 -b 0 http://127.0.0.1:8083/zomg

https://github.com/phoboslab/jsmpeg/assets/443987/ba47caf7-c386-4f17-a08b-3b3564c3997c

It's curious that you were able to do canvas.getContext("2d");, because the default canvas context will be WebGL, if disableGl:true is not specified.