js mjpeg buffer stream
專案要求使用http和mjpeg在頁面實作實時展示視頻流
基礎知識
流操作:ReadableStream
- 流操作API中的
ReadableStream介面呈現了一個可讀取的二進制流操作,Fetch API 通過Response的body屬性提供了一個具體的ReadableStream物件; ReadableStream.getReader()方法創建一個讀取器并將流鎖定于其上,一旦流被鎖定,其他讀取器不能讀取它,直到它被釋放
Uint8Array && ArrayBuffer
Uint8Array陣列型別表示一個8位無符號整型陣列,創建時內容被初始化為0,創建完后,可以以物件的方式或使用陣列下標索引的方式參考陣列中的元素;ArrayBuffer物件用來表示 「通用的、固定長度的」原始二進制資料緩沖區,ArrayBuffer 不能直接操作,而是要通過型別陣列物件 或 DataView 物件來操作 ,它們會將緩沖區中的資料表示為特定的格式,并通過這些格式來讀寫緩沖區的內容,new Uint8Array(new ArrayBuffer(imageLength)):創建初始化為0,包含imageLength位元組個元素的無符號整型陣列
Blob
Blob(Binary Large Object)表示二進制型別的大物件,在資料庫管理系統中,將二進制資料存盤為一個單一個體的集合,Blob 通常是影像、聲音或多媒體檔案,Blob建構式的語法為:var aBlob = newBlob(blobParts, options);blobParts:它是一個由 ArrayBuffer,ArrayBufferView,Blob,DOMString 等物件構成的陣列,DOMStrings 會被編碼為 UTF-8, options:一個可選的物件- 在瀏覽器中,我們使用
URL.createObjectURL方法來創建 Blob URL,該方法接收一個 Blob 物件,并為其創建一個唯一的 URL,瀏覽器內部為每個通過 URL.createObjectURL 生成的 URL 存盤了一個 「URL → Blob」映射,因此,此類 URL 較短,但可以訪問 Blob , - 這里我們先把回應物件轉換為 ArrayBuffer 物件,然后通過呼叫 Blob 建構式,把 ArrayBuffer 物件轉換為 Blob 物件,再利用 createObjectURL 方法創建 Object URL,最終實作圖片預覽
Canvas
- 在畫布上定位影像—> context.drawImage(img,x,y);
- 在畫布上定位影像,并規定影像的寬度和高度—> context.drawImage(img,x,y,width,height);
- 剪切影像,并在畫布上定位被剪切的部分—> context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
- 繪制一個描邊矩形,直接繪制,不需要手動呼叫stroke():ctx.strokeRect( 起點x軸坐標,起點y軸坐標,寬,高 )
本示例中,我們要不斷地從后端讀取視頻流,(我們讀到的本質上是一幀一幀的圖片),然后在頁面中通過img標簽展示出來,動態變化的圖片即形成視頻,
在拿到url后,我們使用ReadableStream.getReader()方法創建一個讀取器,因為需要對視頻流進行操作;讀出每一幀圖片所攜帶的資訊:圖片本身的資訊和json資料,這個json資料就是我們要畫出的點的位置,但是在這里我只做一個演示,json中存放了一個鍵值對,我們把鍵值對讀出來動態展示到畫布上即可,
js 決議 mjpeg 視頻流代碼:
點擊查看代碼
<style>
.container{
width: 800px;
height: 600px;
position: relative;
}
#canvas{
position: absolute;
top: 0;
left: 0;
}
</style>
<body>
<div >
<canvas id="canvas" height="600"></canvas>
<img id="image" height="600" />
</div>
<script>
const url = 'mjpegurl';
fetch(url).then((res) => {
const reader = res.body.getReader();
let lineLength = 0;
let lineBuffer = new Uint8Array(new ArrayBuffer(1000))
let headers = "";
let contentLength = -1;
let contentType = "";
let imageLength = -1;
let imageBuffer = null;
let jsonLength = -1;
let jsonDatahttps://www.cnblogs.com/rain111/archive/2022/08/12/= "";
let bytesRead = 0;
const read = () => {
reader.read().then(({done, value}) => {
if(done) return
for(let index = 0,len = value.length; index < len; index++) {
//先讀取分段的頭部塊,按行讀取,當資料塊長度未有效時,表示正在讀取頭部塊,
if(contentLength <= 0) {
lineBuffer[lineLength++] = value[index];
//每行字符長度最小為2位元組,
if(lineLength < 2) continue;
//如果行首尾不是\r\n則本行未結束,繼續讀,
if(lineBuffer[lineLength - 2] != 0x0d || lineBuffer[lineLength - 1] != 0x0a) continue;
//成功讀取一行,轉換為String型別,同時把本行資料拼接到頭部的字串變數中,
for(let i = 0; i < lineLength; i++){
headers += String.fromCharCode(lineBuffer[i])
}
//檢查本行是否為結束行,當行首為\r\n時頭部結束,
if(lineBuffer[0] === 0x0d && lineBuffer[1] === 0x0a) {
//以下是決議頭部資料,
contentType = getValue(headers, "Content-Type");
contentLength = getValue(headers, "Content-length");
imageLength = getValue(headers, "Content-image-length");
jsonLength = getValue(headers, "Content-json-length");
imageBuffer = new Uint8Array(new ArrayBuffer(imageLength));
}
//清空行長度,用于讀取下一行,
lineLength = 0;
}
//讀取分段的資料塊,按資料塊的長度讀取,
else if(bytesRead < contentLength) {
let tempLength = imageLength + jsonLength;
//先讀取圖片資料,
if(bytesRead < imageLength){
imageBuffer[bytesRead] = value[index]
}
//圖片資料后緊接著是json資料,
else if(bytesRead < tempLength) {
jsonData += String.fromCharCode(value[index])
}
bytesRead++;
}else{
//把影像更新到img控制元件上,
let img = document.getElementById("image")
img.src = https://www.cnblogs.com/rain111/archive/2022/08/12/URL.createObjectURL(new Blob([imageBuffer], {type: contentType}))
//把影像更新到canvas控制元件上,
let ctx = document.getElementById("canvas").getContext("2d")
ctx.drawImage(img, 0, 0, 800, 600);
var obj = {}
try {
obj = JSON.parse(jsonData)
} catch (error) {
console.log("obj parse error", error);
}
for(var key in obj){
ctx.font = "24px Arial"
ctx.fillStyle = "#ca0c16"
ctx.fillText(`${key}:${obj[key]}`, 115, 140)
}
contentLength = 0;
imageLength = 0;
jsonLength = 0;
bytesRead = 0 ;
headers = '';
jsonDatahttps://www.cnblogs.com/rain111/archive/2022/08/12/= '';
}
}
read();
}).catch((error) => {
console.log("read error", error);
})
}
read()
}).catch((error) => {
console.error(error);
})
const getValue = https://www.cnblogs.com/rain111/archive/2022/08/12/(headers, key) => {
let value =''
headers.split("\n").forEach((item) => {
const itemArr = item.split(":")
if(itemArr[0] === key) value = https://www.cnblogs.com/rain111/archive/2022/08/12/itemArr[1]
})
if(key.includes('length')) {
return Number(value)
}else{
return value;
}
}
</script>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/501744.html
標籤:其他
