操控影片串流元件。
現代的網路技術提供許多運用影片的方式。Media Stream API、Media Recording API、Media Source API 和 WebRTC API 新增了一組功能豐富的工具組,可用於錄製、傳輸及播放影片串流。解決某些高階工作時,這些 API 無法讓網頁程式設計師處理影片串流的個別元件,例如影格和未混用的編碼影片或音訊區塊等。為了取得這些基本元件的低階存取權,開發人員不斷使用 WebAssembly 將視訊和音訊轉碼器帶入瀏覽器。不過,由於新式瀏覽器已經隨附各種轉碼器 (通常會由硬體加速),因此在重新封包時,WebAssembly 似乎浪費人力和電腦資源。
WebCodecs API 讓程式設計師能使用瀏覽器中現有的媒體元件,避免出現這種效率低落的問題。詳細說明:
- 影片和音訊解碼器
- 影片和音訊編碼器
- 原始影片影格
- 圖片解碼器
WebCodecs API 適用於需要完全控管媒體內容處理方式的網頁應用程式,例如影片編輯器、視訊會議、視訊會議等。
影片處理工作流程
影格是影片處理作業的核心。因此在 WebCodecs 中,大多數的類別都會耗用或產生影格。影片編碼器會將影格轉換為編碼區塊。影片解碼器則相反。
此外,VideoFrame
也能成為 CanvasImageSource
,並具備可接受 CanvasImageSource
的建構函式,即可與其他 Web API 完美搭配。因此可用於 drawImage()
和 texImage2D()
等函式。您也可以從畫布、點陣圖、影片元素和其他影片影格中建構這個 ID。
WebCodecs API 可與 Insertable Streams API 的類別搭配使用,後者可將 WebCodecs 連結至媒體串流軌。
MediaStreamTrackProcessor
會將媒體音軌分入個別影格。MediaStreamTrackGenerator
會從影格串流建立媒體軌。
WebCodecs 和 Web 工作站
設計 WebCodecs API 時,系統會以非同步和關閉主執行緒的方式處理所有繁重的工作。不過,由於影格和區塊回呼通常每秒會多次呼叫,因此可能會讓主執行緒過於雜亂,導致網站的回應速度變慢。因此,建議您將個別影格與編碼區塊的處理程序移至網路工作站。
為此,ReadableStream 提供便利的方法,自動將所有來自媒體軌的影格轉移至工作站。舉例來說,MediaStreamTrackProcessor
可用於取得來自網路攝影機的媒體串流軌的 ReadableStream
。在串流傳輸至網路工作站後,系統會逐一讀取影格並排入 VideoEncoder
。
透過 HTMLCanvasElement.transferControlToOffscreen
,甚至可以在主執行緒外完成算繪。但如果所有高階工具都變得不方便,VideoFrame
本身可以「轉移」,且可能會在工作站之間移動。
WebCodecs 應用實例
編碼
開頭為 VideoFrame
。建構影片影格的方法有三種。
從畫布、圖片點陣圖或影片元素等圖片來源。
const canvas = document.createElement("canvas"); // Draw something on the canvas... const frameFromCanvas = new VideoFrame(canvas, { timestamp: 0 });
使用
MediaStreamTrackProcessor
從MediaStreamTrack
提取影格const stream = await navigator.mediaDevices.getUserMedia({…}); const track = stream.getTracks()[0]; const trackProcessor = new MediaStreamTrackProcessor(track); const reader = trackProcessor.readable.getReader(); while (true) { const result = await reader.read(); if (result.done) break; const frameFromCamera = result.value; }
從
BufferSource
中的二進位像素表示法建立影格const pixelSize = 4; const init = { timestamp: 0, codedWidth: 320, codedHeight: 200, format: "RGBA", }; const data = new Uint8Array(init.codedWidth * init.codedHeight * pixelSize); for (let x = 0; x < init.codedWidth; x++) { for (let y = 0; y < init.codedHeight; y++) { const offset = (y * init.codedWidth + x) * pixelSize; data[offset] = 0x7f; // Red data[offset + 1] = 0xff; // Green data[offset + 2] = 0xd4; // Blue data[offset + 3] = 0x0ff; // Alpha } } const frame = new VideoFrame(data, init);
無論影格來源為何,都可以使用 VideoEncoder
將影格編碼為 EncodedVideoChunk
物件。
編碼前,VideoEncoder
必須提供兩個 JavaScript 物件:
- 字典,其中包含兩個函式,用於處理編碼區塊和錯誤。這些函式是由開發人員定義,一旦傳送至
VideoEncoder
建構函式,即無法變更。 - 編碼器設定物件,包含輸出影片串流的參數。您稍後可以呼叫
configure()
來變更這些參數。
如果瀏覽器不支援該設定,configure()
方法將擲回 NotSupportedError
。建議您使用該設定呼叫靜態方法 VideoEncoder.isConfigSupported()
,事先檢查該設定是否受支援,並等待其承諾。
const init = {
output: handleChunk,
error: (e) => {
console.log(e.message);
},
};
const config = {
codec: "vp8",
width: 640,
height: 480,
bitrate: 2_000_000, // 2 Mbps
framerate: 30,
};
const { supported } = await VideoEncoder.isConfigSupported(config);
if (supported) {
const encoder = new VideoEncoder(init);
encoder.configure(config);
} else {
// Try another config.
}
編碼器設定完成後,即可透過 encode()
方法接受影格。configure()
和 encode()
會立即傳回,而不會等待實際工作完成。此 API 可讓多個影格同時排入編碼進行編碼,而 encodeQueueSize
則會顯示在佇列中等待先前編碼完成的要求數量。如果引數或方法呼叫的順序違反 API 合約,就會立即回報錯誤,或是針對轉碼器實作中的問題呼叫 error()
回呼,藉此回報錯誤。如果編碼成功完成,系統會以新的編碼區塊做為引數來呼叫 output()
回呼。這裡還有另一個重要的細節,就是需要呼叫 close()
時,掌握不再需要影格時的情況。
let frameCounter = 0;
const track = stream.getVideoTracks()[0];
const trackProcessor = new MediaStreamTrackProcessor(track);
const reader = trackProcessor.readable.getReader();
while (true) {
const result = await reader.read();
if (result.done) break;
const frame = result.value;
if (encoder.encodeQueueSize > 2) {
// Too many frames in flight, encoder is overwhelmed
// let's drop this frame.
frame.close();
} else {
frameCounter++;
const keyFrame = frameCounter % 150 == 0;
encoder.encode(frame, { keyFrame });
frame.close();
}
}
最後,就是藉由編寫一個函式,處理已編碼影片從編碼器送出時,用來完成編碼的程式碼。這個函式通常會透過網路傳送資料區塊,或是將資料區塊多工處理到媒體容器中儲存。
function handleChunk(chunk, metadata) {
if (metadata.decoderConfig) {
// Decoder needs to be configured (or reconfigured) with new parameters
// when metadata has a new decoderConfig.
// Usually it happens in the beginning or when the encoder has a new
// codec specific binary configuration. (VideoDecoderConfig.description).
fetch("/upload_extra_data", {
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
body: metadata.decoderConfig.description,
});
}
// actual bytes of encoded data
const chunkData = new Uint8Array(chunk.byteLength);
chunk.copyTo(chunkData);
fetch(`/upload_chunk?timestamp=${chunk.timestamp}&type=${chunk.type}`, {
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
body: chunkData,
});
}
如果您需要確保所有待處理的編碼要求均已完成,可以呼叫 flush()
並等待其承諾。
await encoder.flush();
解碼中
設定 VideoDecoder
的方式與為 VideoEncoder
完成類似:系統會在建立解碼器時傳遞兩個函式,並將轉碼器參數指派給 configure()
。
轉碼器參數集因轉碼器和轉碼器不同而有差異。例如,H.264 轉碼器可能需要 AVCC 的二進位 blob,除非編碼為 Annex B 格式 (encoderConfig.avc = { format: "annexb" }
)。
const init = {
output: handleFrame,
error: (e) => {
console.log(e.message);
},
};
const config = {
codec: "vp8",
codedWidth: 640,
codedHeight: 480,
};
const { supported } = await VideoDecoder.isConfigSupported(config);
if (supported) {
const decoder = new VideoDecoder(init);
decoder.configure(config);
} else {
// Try another config.
}
解碼器初始化後,即可使用 EncodedVideoChunk
物件開始提供動態饋給。如要建立區塊,您將需要:
- 已編碼影片資料的
BufferSource
- 區塊的開始時間戳記,以微秒為單位 (區塊中第一個編碼影格的媒體時間)
- 區塊類型,屬於以下其中一種:
key
(如果區塊可獨立於先前區塊解碼)- 如果區塊只能在一或多個先前區塊解碼後才能解碼,則為
delta
此外,編碼器產生的所有區塊也都能照常用於解碼器。對於錯誤回報,以及編碼器方法的非同步性質,同樣適用於解碼器。
const responses = await downloadVideoChunksFromServer(timestamp);
for (let i = 0; i < responses.length; i++) {
const chunk = new EncodedVideoChunk({
timestamp: responses[i].timestamp,
type: responses[i].key ? "key" : "delta",
data: new Uint8Array(responses[i].body),
});
decoder.decode(chunk);
}
await decoder.flush();
現在要示範如何在網頁上顯示新的解碼影格。建議您確保解碼器輸出回呼 (handleFrame()
) 能快速傳回。在以下範例中,系統只會將影格新增至準備好轉譯的影格佇列。轉譯程序會分開進行,其中包含兩個步驟:
- 等待適當時機顯示影格。
- 在畫布上繪製頁框。
不再需要影格後,請呼叫 close()
來在垃圾收集器取得基礎記憶體前釋出基礎記憶體,進而減少網頁應用程式使用的平均記憶體量。
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let pendingFrames = [];
let underflow = true;
let baseTime = 0;
function handleFrame(frame) {
pendingFrames.push(frame);
if (underflow) setTimeout(renderFrame, 0);
}
function calculateTimeUntilNextFrame(timestamp) {
if (baseTime == 0) baseTime = performance.now();
let mediaTime = performance.now() - baseTime;
return Math.max(0, timestamp / 1000 - mediaTime);
}
async function renderFrame() {
underflow = pendingFrames.length == 0;
if (underflow) return;
const frame = pendingFrames.shift();
// Based on the frame's timestamp calculate how much of real time waiting
// is needed before showing the next frame.
const timeUntilNextFrame = calculateTimeUntilNextFrame(frame.timestamp);
await new Promise((r) => {
setTimeout(r, timeUntilNextFrame);
});
ctx.drawImage(frame, 0, 0);
frame.close();
// Immediately schedule rendering of the next frame
setTimeout(renderFrame, 0);
}
開發人員提示
請使用 Chrome 開發人員工具的媒體面板查看媒體記錄並對 WebCodecs 偵錯。
示範
下方示範展示了畫布中的動畫影格:
MediaStreamTrackProcessor
以 25 FPS 拍攝成ReadableStream
- 已移轉至網路工作站
- 編碼為 H.264 影片格式
- 影片解碼器
- 並使用
transferControlToOffscreen()
在第二個畫布上算繪
其他示範
另請參考其他示範影片:
使用 WebCodecs API
功能偵測
如何檢查 WebCodecs 支援:
if ('VideoEncoder' in window) {
// WebCodecs API is supported.
}
請注意,WebCodecs API 僅適用於安全環境,因此如果 self.isSecureContext
為 False,偵測作業就會失敗。
意見回饋:
Chrome 團隊想瞭解您使用 WebCodecs API 的經驗。
告訴我們 API 設計
該 API 有什麼功能不如預期嗎?或是您需要實作提案的方法或屬性嗎?如果您對安全性模型有任何疑問或意見,在對應的 GitHub 存放區上提交規格問題,或是將您的想法新增至現有問題中。
回報導入問題
您在執行 Chrome 時發現錯誤了嗎?還是實作與規格不同?請前往 new.crbug.com 回報錯誤。請務必盡可能提供詳細資訊、簡單的重現操作說明,並在「元件」方塊中輸入 Blink>Media>WebCodecs
。Glitch 適合用來快速分享簡單快速的提案,
展現對 API 的支援
您打算使用 WebCodecs API 嗎?您的公開支援可協助 Chrome 團隊決定各項功能的優先順序,並讓其他瀏覽器廠商瞭解這些功能對他們的支援程度有多重要。
傳送電子郵件至 media-dev@chromium.org,或是使用主題標記 #WebCodecs
將 Tweet 傳送至 @ChromiumDev,並說明使用位置和方式。
主頁橫幅由 Denise Jans 在 Unsplash 上提供。