I want to create a video player that can play multiple resolution, so I have to load chunks of different codecs.
I tried to append chunk of the same codec and it work. So I tried to use changeType() but when I append the new codec chunk in the video element I found this error "CHUNK_DEMUXER_ERROR_APPEND_FAILED: Append: stream parsing failed.".
const myMediaSource = new MediaSource();
var videoSourceBuffer;
var quality=480,qlast=480;
var currentSegment = 0;
var loading = false;
function videos() {
myMediaSource.addEventListener('sourceopen', sourceOpen, { once: true});
}
function sourceOpen() {
setInterval(feedVideo, 500);
}
function feedVideo() {
if (!loading) {
try {
if (myMediaSource.sourceBuffers.length == 0) {
videoSourceBuffer = myMediaSource.addSourceBuffer('video/mp4; codecs="avc1.64001E,mp4a.40.2"');
appendSegment("cinit.mp4", 0);
first = true;
} else {
if (qlast != quality) {
videoSourceBuffer = myMediaSource.sourceBuffers[0];
if (quality == 1080) {
type = 'video/mp4; codecs="avc1.640028,mp4a.40.2"';
}
else if (quality == 720) {
type = 'video/mp4; codecs="avc1.64001F,mp4a.40.2"';
}
else if (quality == 480) {
type = 'video/mp4; codecs="avc1.64001E,mp4a.40.2"';
}
else if (quality == 360) {
type = 'video/mp4; codecs="avc1.64001E,mp4a.40.2"';
}
videoSourceBuffer.changeType(type);
videoSourceBuffer.mode = "segments";
qlast = quality;
}
}
if (!first) {
appendSegment("c" + currentSegment + ".m4s", currentSegment);
}
else {
first = false;
}
} catch (error) {
console.log('Error! ' + error);
}
}
}
function appendSegment(file, resourcesIndex) {
loading = true;
fetch("http://mysite/video/" + quality + "p/" + file).then(function (response) {
return response.arrayBuffer();
}).then(function (videoData) {
videoSourceBuffer.appendBuffer(videoData);
videoSourceBuffer.addEventListener('updateend', function () {
loading = false;
}, { once: true });
});
}
How can I fix it?
You almost certainly don't need to use changeType
here, since that is typically used for changing codec (eg avc -> hevc) or container (eg mp4 -> webm), whereas you are simply switching within the same codec and container.
The problem is almost certainly that you aren't appending an initialisation segment on a quality change - you only do this for the first quality level.
Fix: insert an appropriate initialisation segment before the first media segment of each new quality.