Introduction
Most Qt Multimedia recording examples start with a camera, screen capture, or microphone. But many applications produce media on their own: a game renders frames, a visualization tool draws charts, a scientific instrument streams sensor images, or a synthesizer generates sound.
Since Qt 6.8, QMediaRecorder supports encoding such data directly through two classes, QVideoFrameInput and QAudioBufferInput, when using the FFmpeg media backend.
Qt 6.12 brings valuable improvements to video frame-rate handling, including support for variable frame rates and better handling of mismatches between source timestamps and the recording frame rate.
In this post, we'll explore how to feed custom media into the recorder, handle backpressure and media formats, and work with external buffers. We'll also examine the new frame-rate handling and current API limitations.
Getting started
Custom media inputs integrate with QMediaCaptureSession just like cameras and microphones. To record your own video frames and audio buffers, create the corresponding inputs and attach them to a capture session:
QMediaCaptureSession session;
QMediaRecorder recorder;
QVideoFrameInput videoInput;
QAudioBufferInput audioInput;
session.setRecorder(&recorder);
session.setVideoFrameInput(&videoInput);
session.setAudioBufferInput(&audioInput);
recorder.setOutputLocation(QUrl::fromLocalFile("output.mp4"));
recorder.record();
You can then submit media data using QVideoFrameInput::sendVideoFrame() and QAudioBufferInput::sendAudioBuffer().
Both functions return bool, indicating whether the input accepted the data. They return false if the recorder isn't ready, the input isn't connected to a capture session, or the recorder's internal queue is full.
When the recorder is ready to accept more data, the corresponding input emits readyToSendVideoFrame() or readyToSendAudioBuffer().
Encoding happens asynchronously, and the recorder maintains a small queue of pending frames to prevent unbounded memory growth when your application produces data faster than the encoder can process it. This backpressure leads to two ways of using custom media inputs: pull mode and push mode.
Pull mode: let the recorder set the pace
In pull mode, your application produces data on demand. Whenever the recorder signals that it's ready, you generate the next piece and submit it:
connect(&videoInput, &QVideoFrameInput::readyToSendVideoFrame, this, [&] {
videoInput.sendVideoFrame(generator.nextVideoFrame());
});
connect(&audioInput, &QAudioBufferInput::readyToSendAudioBuffer, this, [&] {
audioInput.sendAudioBuffer(generator.nextAudioBuffer());
});
Pull mode is a natural choice for offline processing, such as exporting animations or rendering timelines. The recorder processes data as fast as the encoder allows, potentially much faster than real time, without dropping frames due to backpressure or requiring application-side buffering.
If you already have several frames or buffers available, you can call the corresponding send method in a loop until it returns false. Preserve the rejected piece and retry when the next readiness signal arrives.
Push mode: let your source set the pace
Real-time sources can't always wait for the encoder. A rendering loop, network stream, or capture device produces frames on its own schedule, independently of the recorder's ability to process them.
In this push mode, the send method may return false under load: the recorder is busy, and the frame is rejected. If you ignore the return value, frames may silently disappear from your recording.
One way to handle this is to maintain a small queue in your application. Frames that the recorder can't accept immediately are stored in the queue and submitted later, when readyToSendVideoFrame() or readyToSendAudioBuffer signals that the recorder is ready for more data:
class VideoFrameInputQueue
{
public:
VideoFrameInputQueue()
{
// The recorder has room again: send as much as it accepts.
QObject::connect(&m_input, &QVideoFrameInput::readyToSendVideoFrame,
&m_input, [this] {
while (!m_queue.empty() && m_input.sendVideoFrame(m_queue.front()))
m_queue.pop();
});
}
QVideoFrameInput *videoFrameInput() { return &m_input; }
void pushVideoFrame(const QVideoFrame &frame)
{
// Send directly only if nothing is waiting, preserving frame order.
if (m_queue.empty() && m_input.sendVideoFrame(frame))
return;
static constexpr size_t maxQueueSize = 5;
if (m_queue.size() < maxQueueSize)
m_queue.push(frame);
// Otherwise, drop the frame.
}
private:
QVideoFrameInput m_input;
std::queue<QVideoFrame> m_queue;
};
The bounded queue drops new frames when full, preventing unlimited memory growth. Depending on your application's requirements, you might prefer a different policy, such as dropping the oldest frames or using an unbounded queue if you can tolerate memory growth. For example, audio encoders are usually faster than real-time audio sources, so you may prefer occasional memory growth over occasional audio dropouts.
Using the queue is straightforward:
VideoFrameInputQueue videoQueue;
session.setVideoFrameInput(videoQueue.videoFrameInput());
// Called whenever the source produces a new frame.
void onFrameProduced(const QVideoFrame &frame) { videoQueue.pushVideoFrame(frame); }
The audio queue equivalent follows the same pattern, using QAudioBufferInput, QAudioBuffer, sendAudioBuffer(), and readyToSendAudioBuffer(). Both implementations can therefore be unified into a single class template, as demonstrated by the mediaframeinputs manual test in the Qt Multimedia repository.
Defining media formats
QMediaRecorder configures its encoders based on the input formats (QVideoFrameFormat and QAudioFormat) and recorder settings, such as videoResolution and audioSampleRate, which take precedence when specified.
The recorder obtains the input formats either from the media input constructors or from the first submitted frames.
Encoder initialization can take time. In push mode, determining formats from the first frames may introduce delays and cause queues to grow. When formats are known in advance, specify them through the input constructors:
QVideoFrameFormat videoFormat(QSize(1920, 1080), QVideoFrameFormat::Format_NV12);
QVideoFrameInput videoInput(videoFormat);
QAudioFormat audioFormat;
audioFormat.setSampleRate(48000);
audioFormat.setChannelConfig(QAudioFormat::ChannelConfigStereo);
audioFormat.setSampleFormat(QAudioFormat::Float);
QAudioBufferInput audioInput(audioFormat);
Send what you have; the recorder converts
The recorder selects suitable encoding formats and performs the necessary conversions when the input formats don't match.
This convenience comes at a cost: format conversions consume CPU resources and may add processing overhead to every frame. For better performance, consider generating media in a format that the encoder can accept natively, particularly for video. For example, H.264 and HEVC encoders commonly accept NV12 or YUV 4:2:0.
Timing and frame rates
Video timestamps and frame-rate handling
You can specify a target video frame rate as a hint to the encoder through QVideoFrameFormat:
format.setStreamFrameRate(60.);
Or directly through QMediaRecorder:
recorder.setVideoFrameRate(60.);
The encoder may adjust the requested frame rate based on its capabilities. If no frame rate is specified, the recorder uses a variable frame rate when supported by the encoder. Otherwise, it provides 30 fps as the default hint.
Video frame timing is determined by QVideoFrame::startTime() and QVideoFrame::endTime(), expressed in microseconds:
frame.setStartTime(frameIndex * 1'000'000 / fps);
frame.setEndTime((frameIndex + 1) * 1'000'000 / fps);
For fixed-frame-rate recordings, you can omit frame timestamps entirely. The recorder assigns them automatically, placing each submitted frame in the next available time slot.
Regardless of the frame-rate mode, if you omit end time, the recorder assumes the frame remains valid until the next frame begins.
Qt 6.12 introduces improved handling of variable frame rates and mismatches between video frame timestamps and the configured recording frame rate. Let’s break down how it works.
For fixed-frame-rate recordings, the recorder aligns incoming frames with the target frame-rate grid, populating frames to fill missing slots or discarding superseded frames. Currently, the recorder performs no frame interpolation when mapping frames to time slots.
Two important catches::
Dropping frames due to backpressure in *push mode**may cause the recorder to duplicate preceding frames.
If the fixed recording frame rate is lower than the source frame rate, some frames will be discarded without any notification.
The diagram below illustrates how the recorder handles frames with irregular timestamps when recording at a fixed frame rate:
[image: 8a70b579-68d3-4d39-8340-f4524a5a0009.png]
In this example:
Frame 1 spans several time slots, so the recorder duplicates it to populate the corresponding positions in the fixed-frame-rate grid.
Frame 2 has no explicit end time, so it remains active until the next frame begins and is used to fill the corresponding slots.
Frame 3 is superseded by Frame 4 before reaching the next recording time slot, so it is ignored.
Frame 4 starts at a recording time slot and is recorded normally.
For variable-frame-rate recordings, the recorder preserves the supplied timestamps without aligning them to a fixed grid.
Audio follows the samples
Audio timing works differently. Its position in the recording is determined by the number of samples submitted, rather than the timestamps of individual audio buffers.
Your audio data must therefore be continuous. If the source contains gaps, fill them with silence. Otherwise, subsequent audio samples will shift earlier in the recording, potentially causing audio and video to fall out of sync.
Wrapping your own buffers
If your frames already reside in memory you manage, for example, frames from a camera SDK, you can subclass QAbstractVideoBuffer and wrap them in a QVideoFrame:
class SdkFrameBuffer : public QAbstractVideoBuffer
{
public:
SdkFrameBuffer(SdkFrameHandle handle, QVideoFrameFormat format)
: m_handle(std::move(handle)), m_format(std::move(format)) { }
MapData map(QVideoFrame::MapMode) override
{
MapData data;
data.planeCount = 2; // NV12: Y plane + interleaved UV plane
for (int i = 0; i < data.planeCount; ++i) {
data.data[i] = m_handle.planeData(i);
data.bytesPerLine[i] = m_handle.planeStride(i);
data.dataSize[i] = m_handle.planeSize(i);
}
return data;
}
QVideoFrameFormat format() const override { return m_format; }
private:
SdkFrameHandle m_handle; // Returns the buffer to the SDK when destroyed
QVideoFrameFormat m_format;
};
QVideoFrame frame(std::make_unique<SdkFrameBuffer>(std::move(handle), format));
videoInput.sendVideoFrame(frame);
Audio doesn't currently have an equivalent buffer abstraction, so you need to copy the SDK data:
// you implement the format conversion
QAudioFormat toQAudioFormat(const SdkFrame &frame);
QAudioBuffer buffer(QByteArray(sdkFrame.data(), sdkFrame.size()),
toQAudioFormat(sdkFrame));
A few things to keep in mind:
The recorder reads your video frame from an internal encoding thread and keeps the frame alive until it has been encoded. Therefore, map() must be thread-safe, and the underlying memory must remain valid for the buffer's lifetime.
GPU textures can't be passed directly to the encoder. A custom buffer exposes its data as CPU-accessible memory through map(). The public API doesn't currently provide a way to pass a GPU texture or surface (Direct3D, Metal, Vulkan, OpenGL, VA-API) directly to a hardware encoder. This may be relevant if, for example, you receive frames from an SDK, preprocess them using shaders or other GPU operations, and then want to record them.
End of stream
Empty QVideoFrame and QAudioBuffer objects represent the end of a stream.
When the QMediaRecorder::autoStop property is set to true, the recorder automatically stops once all streams have received their end-of-stream markers. Listen for recorderStateChanged() and wait for StoppedState to know when recording is complete.
This simplifies the recording workflow by eliminating the need to call QMediaRecorder::stop() explicitly from your frame generation slots.
recorder.setAutoStop(true);
connect(&recorder, &QMediaRecorder::recorderStateChanged, this,
[](QMediaRecorder::RecorderState state) {
if (state == QMediaRecorder::StoppedState)
qInfo() << "Recording has been completed";
});
// ... later, when the sources are exhausted and the inputs are ready to accept more data:
videoInput.sendVideoFrame(QVideoFrame());
audioInput.sendAudioBuffer(QAudioBuffer());
Limitations
Designing a high-level, scalable, and backward-compatible API comes with certain limitations. Let's go through those relevant to the topics discussed above.
One custom video and audio stream per recording. However, the current recording implementation has an undocumented feature: if you attach other media inputs to QMediaCaptureSession, such as QAudioInput, QCamera, or screen/window capture, and activate them before starting the recording, they will be recorded as separate streams. Until this feature is officially documented, don't rely on its availability across major Qt releases.
No zero-copy GPU input. Custom frames go through CPU-accessible memory, as described above.
Audio timestamps aren't used. Audio timing follows the sample count, so the application must fill any gaps with silence.
No zero-copy audio input. Copying audio data usually doesn't cause significant performance overhead, but it's worth keeping in mind.
CPU-based video frame scaling. Currently, conversions rely on FFmpeg's software scaling. Replacing it with shader-based scaling could be a future improvement.
Rejected frames are yours to handle. In push mode, the recorder rejects data when it's busy. Without application-side buffering, those frames are lost.
Limited access to recorder capabilities. For example, the QMediaRecorder API doesn't expose whether variable-frame-rate recording is supported.
No subtitle stream recording. Setting subtitles on a QVideoFrame has no effect on the recording.
No QML API. QVideoFrame, QAudioBuffer, and their corresponding inputs represent raw media data and don't have QML equivalents.
FFmpeg backend only. The custom media inputs discussed above, and autoStop are supported only by the FFmpeg media backend, which is the default on many platforms.
Which of these limitations affect your applications? What's keeping you from using custom media inputs? Let us know!