files/en-us/web/api/videoencoder/encode/index.md
{{APIRef("WebCodecs API")}}{{SecureContext_Header}}{{AvailableInWorkers("window_and_dedicated")}}
The encode() method of the {{domxref("VideoEncoder")}} interface asynchronously encodes a {{domxref("VideoFrame")}}.
Encoded data ({{domxref("EncodedVideoChunk")}}) or an error will eventually be returned via the callbacks provided to the {{domxref("VideoEncoder")}} constructor.
encode(frame)
encode(frame, options)
frame
options {{optional_inline}}
keyFrame {{optional_inline}}
false giving the user agent flexibility to decide if this frame should be encoded as a key frame. If true this indicates that the given frame must be encoded as a key frame.vp9 {{optional_inline}}
quantizer
quantizer bitrate mode.av1 {{optional_inline}}
quantizer
quantizer bitrate mode.avc {{optional_inline}}
quantizer
quantizer bitrate mode.hevc {{optional_inline}}
quantizer
quantizer bitrate mode.None ({{jsxref("undefined")}}).
InvalidStateError {{domxref("DOMException")}}
"configured".DataError {{domxref("DOMException")}}
frame object's rotation and flip do not match the rotation and flip of the first {{domxref("VideoFrame")}} passed to encode() (the "active orientation").In the following example encode is passed a VideoFrame, and the options parameter indicating that this frame should be considered a keyframe.
encoder.encode(frame, { keyFrame: true });
Setting per-frame QP value for encoding individual frames.
const encoder = new VideoEncoder(init);
const encoderConfig = {
codec: "vp09.00.10.08",
width: 800,
height: 600,
bitrateMode: "quantizer",
framerate: 30,
latencyMode: "realtime",
};
encoder.configure(encoderConfig);
const encodeOptions = { keyFrame: false };
const qp = calculateQp(codec, frame);
if (codec.includes("vp09")) {
encodeOptions.vp9 = { quantizer: qp };
} else if (codec.includes("av01")) {
encodeOptions.av1 = { quantizer: qp };
} else if (codec.includes("avc")) {
encodeOptions.avc = { quantizer: qp };
} else if (codec.includes("hvc1") || codec.includes("hev1")) {
encodeOptions.hevc = { quantizer: qp };
}
encoder.encode(frame, encodeOptions);
{{Specifications}}
{{Compat}}