labthings_fastapi.outputs.mjpeg_stream

MJPEG Stream support.

This module defines a descriptor that allows Thing subclasses to expose an MJPEG stream. See MJPEGStreamDescriptor.

Classes

RingbufferEntry

A single entry in a ringbuffer.

MJPEGStreamResponse

A StreamingResponse that streams an MJPEG stream.

Module Contents

class labthings_fastapi.outputs.mjpeg_stream.RingbufferEntry

A single entry in a ringbuffer.

This structure comprises one frame as a JPEG, plus a timestamp and a buffer index. Each time a frame is added to the stream, it is tagged with a timestamp and index, with the index increasing by 1 each time.

frame: bytes

The frame as a bytes object, which is a JPEG image for an MJPEG stream.

timestamp: datetime.datetime

The time the frame was added to the ringbuffer.

index: int

The index of the frame within the stream.

class labthings_fastapi.outputs.mjpeg_stream.MJPEGStreamResponse(gen: AsyncGenerator[bytes, None], status_code: int = 200)

Bases: fastapi.responses.StreamingResponse

A StreamingResponse that streams an MJPEG stream.

This response uses an async generator that yields bytes objects, each of which is a JPEG file. We add the –frame markers and mime types that mark it as an MJPEG stream. This is sufficient to enable it to work in an img tag, with the src set to the MJPEG stream’s endpoint.

Set up StreamingResponse that streams an MJPEG stream.

This response is initialised with an async generator that yields bytes objects, each of which is a JPEG file. We add the –frame markers and mime types that mark it as an MJPEG stream. This is sufficient to enable it to work in an img tag, with the src set to the MJPEG stream’s endpoint.

It expects an async generator that supplies individual JPEGs to be streamed, such as the one provided by MJPEGStream.

NB the status_code argument is used by FastAPI to set the status code of the response in OpenAPI.

Parameters:
  • gen – an async generator, yielding bytes objects each of which is one image, in JPEG format.

  • status_code – The status code associated with the response, by default a 200 code is returned.

media_type = 'multipart/x-mixed-replace; boundary=frame'

The media_type used to describe the endpoint in FastAPI.

frame_async_generator
async mjpeg_async_generator() AsyncGenerator[bytes, None]

Return a generator yielding an MJPEG stream.

This async generator wraps each incoming JPEG frame with the --frame separator and content type header. It is the basis of the response sent over HTTP (see __init__).

Yield:

JPEG frames, each with a --frame marker prepended.