Class VideoEncoder
- Direct Known Subclasses:
VideoEncoder.VideoEncoderImpl
GstVideoEncoder and subclass should cooperate as follows.
Configuration
- Initially, GstVideoEncoder calls
start
when the encoder element is activated, which allows subclass to perform any global setup. - GstVideoEncoder calls
setFormat
to inform subclass of the format of input video data that it is about to receive. Subclass should setup for encoding and configure base class as appropriate (e.g. latency). While unlikely, it might be called more than once, if changing input parameters require reconfiguration. Baseclass will ensure that processing of current configuration is finished. - GstVideoEncoder calls
stop
at end of all processing.
Data processing
- Base class collects input data and metadata into a frame and hands
this to subclass'
handleFrame
.
- If codec processing results in encoded data, subclass should call
gstVideoEncoderFinishFrame
to have encoded data pushed downstream.
- If implemented, baseclass calls subclass
prePush
just prior to pushing to allow subclasses to modify some metadata on the buffer. If it returns GST_FLOW_OK, the buffer is pushed downstream.
- GstVideoEncoderClass will handle both srcpad and sinkpad events.
Sink events will be passed to subclass if
event
callback has been provided.
Shutdown phase
- GstVideoEncoder class calls
stop
to inform the subclass that data parsing will be stopped.
Subclass is responsible for providing pad template caps for
source and sink pads. The pads need to be named "sink" and "src". It should
also be able to provide fixed src pad caps in getcaps
by the time it calls
gstVideoEncoderFinishFrame
.
Things that subclass need to take care of:
- Provide pad templates
- Provide source pad caps before pushing the first buffer
- Accept data in
handleFrame
and provide encoded results togstVideoEncoderFinishFrame
.
The GstVideoEncoder
:qos property will enable the Quality-of-Service
features of the encoder which gather statistics about the real-time
performance of the downstream elements. If enabled, subclasses can
use gst_video_encoder_get_max_encode_time() to check if input frames
are already late and drop them right away to give a chance to the
pipeline to catch up.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
VideoEncoder.Builder<B extends VideoEncoder.Builder<B>>
Inner class implementing a builder pattern to construct a GObject with properties.static class
Subclasses can override any of the available virtual methods or not, as needed.static class
The VideoEncoderImpl type represents a native instance of the abstract VideoEncoder class.Nested classes/interfaces inherited from class org.freedesktop.gstreamer.gst.Element
Element.ElementClass, Element.ElementImpl, Element.NoMorePadsCallback, Element.PadAddedCallback, Element.PadRemovedCallback
Nested classes/interfaces inherited from class org.freedesktop.gstreamer.gst.GstObject
GstObject.DeepNotifyCallback, GstObject.ObjectClass, GstObject.ObjectImpl
Nested classes/interfaces inherited from class org.gnome.gobject.InitiallyUnowned
InitiallyUnowned.InitiallyUnownedClass
Nested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback
Nested classes/interfaces inherited from interface org.freedesktop.gstreamer.gst.Preset
Preset.PresetImpl, Preset.PresetInterface
-
Constructor Summary
ConstructorDescriptionVideoEncoder
(MemorySegment address) Create a VideoEncoder proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionallocateOutputBuffer
(long size) Helper function that allocates a buffer to hold an encoded video frame for this VideoEncoder's currentGstVideoCodecState
.allocateOutputFrame
(VideoCodecFrame frame, long size) Helper function that allocates a buffer to hold an encoded video frame for this VideoEncoder's currentGstVideoCodecState
.protected VideoEncoder
asParent()
Returns this instance as if it were its parent type.static VideoEncoder.Builder
<? extends VideoEncoder.Builder> builder()
AVideoEncoder.Builder
object constructs aVideoEncoder
with the specified properties.protected boolean
close()
Optional.protected boolean
decideAllocation
(Query query) Optional.protected FlowReturn
finish()
Optional.finishFrame
(VideoCodecFrame frame) frame
must have a valid encoded data buffer, whose metadata fields are then appropriately set according to frame data or no buffer at all if the frame should be dropped.finishSubframe
(VideoCodecFrame frame) If multiple subframes are produced for one input frame then use this method for each subframe, except for the last one.protected boolean
flush()
Optional.void
getAllocator
(@Nullable Out<Allocator> allocator, @Nullable AllocationParams params) LetsGstVideoEncoder
sub-classes to know the memoryallocator
used by the base class and itsparams
.protected Caps
Optional.getFrame
(int frameNumber) Get a pending unfinishedGstVideoCodecFrame
Get all pending unfinishedGstVideoCodecFrame
void
getLatency
(@Nullable ClockTime minLatency, @Nullable ClockTime maxLatency) Query the configured encoding latency.getMaxEncodeTime
(VideoCodecFrame frame) Determines maximum possible encoding time forframe
that will allow it to encode and arrive in time (as determined by QoS events).static MemoryLayout
The memory layout of the native struct.Returns the minimum force-keyunit interval, see gst_video_encoder_set_min_force_key_unit_interval() for more details.Get the oldest unfinished pendingGstVideoCodecFrame
Get the currentGstVideoCodecState
static Type
getType()
Get the GType of the VideoEncoder classprotected FlowReturn
handleFrame
(VideoCodecFrame frame) Provides input frame to subclass.boolean
Checks if this VideoEncoder is currently configured to handle Quality-of-Service events from downstream.void
mergeTags
(@Nullable TagList tags, TagMergeMode mode) Sets the video encoder tags and how they should be merged with any upstream stream tags.boolean
Negotiate with downstream elements to currently configuredGstVideoCodecState
.protected boolean
open()
Optional.protected FlowReturn
prePush
(VideoCodecFrame frame) Optional.protected boolean
proposeAllocation
(Query query) Optional.proxyGetcaps
(@Nullable Caps caps, @Nullable Caps filter) Returns caps that expresscaps
(or sink template caps ifcaps
== NULL) restricted to resolution/format/...protected boolean
reset
(boolean hard) Optional.protected boolean
setFormat
(VideoCodecState state) Optional.void
setHeaders
(List<Buffer> headers) Set the codec headers to be sent downstream whenever requested.void
setLatency
(ClockTime minLatency, ClockTime maxLatency) Informs baseclass of encoding latency.void
setMinForceKeyUnitInterval
(ClockTime interval) Sets the minimum interval for requesting keyframes based on force-keyunit events.void
Request minimal value for PTS passed to handle_frame.setOutputState
(Caps caps, @Nullable VideoCodecState reference) Creates a newGstVideoCodecState
with the specified caps as the output state for the encoder.void
setQosEnabled
(boolean enabled) Configures this VideoEncoder to handle Quality-of-Service events from downstream.protected boolean
Optional.protected boolean
Optional.protected boolean
Optional.protected boolean
Optional.protected boolean
start()
Optional.protected boolean
stop()
Optional.protected boolean
transformMeta
(VideoCodecFrame frame, Meta meta) Optional.Methods inherited from class org.freedesktop.gstreamer.gst.Element
abortState, addPad, addPropertyDeepNotifyWatch, addPropertyNotifyWatch, callAsync, changeState, continueState, createAllPads, decorateStreamId, decorateStreamIdPrintf, emitNoMorePads, emitPadAdded, emitPadRemoved, foreachPad, foreachSinkPad, foreachSrcPad, getBaseTime, getBus, getClock, getCompatiblePad, getCompatiblePadTemplate, getContext, getContexts, getContextUnlocked, getCurrentClockTime, getCurrentRunningTime, getFactory, getMetadata, getPadTemplate, getPadTemplateList, getRequestPad, getStartTime, getState, getStaticPad, isLockedState, iteratePads, iterateSinkPads, iterateSrcPads, link, linkFiltered, linkMany, linkPads, linkPadsFiltered, linkPadsFull, linkPadsFull, lostState, makeFromUri, messageFull, messageFull, messageFullWithDetails, messageFullWithDetails, noMorePads, onNoMorePads, onPadAdded, onPadRemoved, padAdded, padRemoved, postMessage, provideClock, query, queryConvert, queryDuration, queryPosition, register, releasePad, releaseRequestPad, removePad, removePropertyNotifyWatch, requestPad, requestPadSimple, seek, seek, seekSimple, seekSimple, sendEvent, setBaseTime, setBus, setClock, setContext, setLockedState, setStartTime, setState, stateChanged, stateChangeReturnGetName, stateGetName, syncStateWithParent, typeSetSkipDocumentation, unlink, unlinkMany, unlinkPads
Methods inherited from class org.freedesktop.gstreamer.gst.GstObject
addControlBinding, checkUniqueness, deepNotify, defaultDeepNotify, defaultError, emitDeepNotify, getControlBinding, getControlRate, getGValueArray, getName, getParent, getPathString, getValue, getValueArray, hasActiveControlBindings, hasAncestor, hasAsAncestor, hasAsParent, onDeepNotify, ref, refSink, removeControlBinding, replace, setControlBindingDisabled, setControlBindingsDisabled, setControlRate, setName, setParent, suggestNextSync, syncValues, unparent, unref
Methods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newInstance, newInstance, newv, notify_, notify_, notifyByPspec, onNotify, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, watchClosure, weakRef, weakUnref, withProperties
Methods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, getPrivate, readGClass, writeGClass
Methods inherited from class io.github.jwharm.javagi.base.ProxyInstance
equals, handle, hashCode
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.freedesktop.gstreamer.gst.Preset
deletePreset, getMeta, getPresetNames, getPropertyNames, isEditable, loadPreset, renamePreset, savePreset, setMeta
-
Constructor Details
-
VideoEncoder
Create a VideoEncoder proxy instance for the provided memory address.- Parameters:
address
- the memory address of the native object
-
-
Method Details
-
getType
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuper
keyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()
doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName()
. This will call the native function pointer of this virtual method in the typeclass of the parent type. -
allocateOutputBuffer
Helper function that allocates a buffer to hold an encoded video frame for this VideoEncoder's currentGstVideoCodecState
.- Parameters:
size
- size of the buffer- Returns:
- allocated buffer
-
allocateOutputFrame
Helper function that allocates a buffer to hold an encoded video frame for this VideoEncoder's currentGstVideoCodecState
. Subclass should already have configured video state and set src pad caps.The buffer allocated here is owned by the frame and you should only keep references to the frame, not the buffer.
- Parameters:
frame
- aGstVideoCodecFrame
size
- size of the buffer- Returns:
FlowReturn.OK
if an output buffer could be allocated
-
finishFrame
frame
must have a valid encoded data buffer, whose metadata fields are then appropriately set according to frame data or no buffer at all if the frame should be dropped. It is subsequently pushed downstream or provided toprePush
. In any case, the frame is considered finished and released.After calling this function the output buffer of the frame is to be considered read-only. This function will also change the metadata of the buffer.
- Parameters:
frame
- an encodedGstVideoCodecFrame
- Returns:
- a
GstFlowReturn
resulting from sending data downstream
-
finishSubframe
If multiple subframes are produced for one input frame then use this method for each subframe, except for the last one. Before calling this function, you need to fill frame->output_buffer with the encoded buffer to push.You must call
gst_video_encoder_finish_frame
() for the last sub-frame to tell the encoder that the frame has been fully encoded.This function will change the metadata of
frame
and frame->output_buffer will be pushed downstream.- Parameters:
frame
- aGstVideoCodecFrame
being encoded- Returns:
- a
GstFlowReturn
resulting from pushing the buffer downstream.
-
getAllocator
public void getAllocator(@Nullable @Nullable Out<Allocator> allocator, @Nullable @Nullable AllocationParams params) LetsGstVideoEncoder
sub-classes to know the memoryallocator
used by the base class and itsparams
.Unref the
allocator
after use it.- Parameters:
allocator
- theGstAllocator
usedparams
- theGstAllocationParams
ofallocator
-
getFrame
Get a pending unfinishedGstVideoCodecFrame
- Parameters:
frameNumber
- system_frame_number of a frame- Returns:
- pending unfinished
GstVideoCodecFrame
identified byframeNumber
.
-
getFrames
Get all pending unfinishedGstVideoCodecFrame
- Returns:
- pending unfinished
GstVideoCodecFrame
.
-
getLatency
public void getLatency(@Nullable @Nullable ClockTime minLatency, @Nullable @Nullable ClockTime maxLatency) Query the configured encoding latency. Results will be returned viaminLatency
andmaxLatency
.- Parameters:
minLatency
- address of variable in which to store the configured minimum latency, ornull
maxLatency
- address of variable in which to store the configured maximum latency, ornull
-
getMaxEncodeTime
Determines maximum possible encoding time forframe
that will allow it to encode and arrive in time (as determined by QoS events). In particular, a negative result means encoding in time is no longer possible and should therefore occur as soon/skippy as possible.If no QoS events have been received from downstream, or if
GstVideoEncoder
:qos is disabled this function returnsG_MAXINT64
.- Parameters:
frame
- aGstVideoCodecFrame
- Returns:
- max decoding time.
-
getMinForceKeyUnitInterval
Returns the minimum force-keyunit interval, see gst_video_encoder_set_min_force_key_unit_interval() for more details.- Returns:
- the minimum force-keyunit interval
-
getOldestFrame
Get the oldest unfinished pendingGstVideoCodecFrame
- Returns:
- oldest unfinished pending
GstVideoCodecFrame
-
getOutputState
Get the currentGstVideoCodecState
- Returns:
GstVideoCodecState
describing format of video data.
-
isQosEnabled
public boolean isQosEnabled()Checks if this VideoEncoder is currently configured to handle Quality-of-Service events from downstream.- Returns:
true
if the encoder is configured to perform Quality-of-Service.
-
mergeTags
Sets the video encoder tags and how they should be merged with any upstream stream tags. This will override any tags previously-set with gst_video_encoder_merge_tags().Note that this is provided for convenience, and the subclass is not required to use this and can still do tag handling on its own.
MT safe.
- Parameters:
tags
- aGstTagList
to merge, or NULL to unset previously-set tagsmode
- theGstTagMergeMode
to use, usuallyGST_TAG_MERGE_REPLACE
-
negotiate
public boolean negotiate()Negotiate with downstream elements to currently configuredGstVideoCodecState
. Unmark GST_PAD_FLAG_NEED_RECONFIGURE in any case. But mark it again if negotiate fails.- Returns:
true
if the negotiation succeeded, elsefalse
.
-
proxyGetcaps
Returns caps that expresscaps
(or sink template caps ifcaps
== NULL) restricted to resolution/format/... combinations supported by downstream elements (e.g. muxers).- Parameters:
caps
- initial capsfilter
- filter caps- Returns:
- a
GstCaps
owned by caller
-
setHeaders
-
setLatency
Informs baseclass of encoding latency. If the provided values changed from previously provided ones, this will also post a LATENCY message on the bus so the pipeline can reconfigure its global latency.- Parameters:
minLatency
- minimum latencymaxLatency
- maximum latency
-
setMinForceKeyUnitInterval
Sets the minimum interval for requesting keyframes based on force-keyunit events. Setting this to 0 will allow to handle every event, setting this toGST_CLOCK_TIME_NONE
causes force-keyunit events to be ignored.- Parameters:
interval
- minimum interval
-
setMinPts
Request minimal value for PTS passed to handle_frame.For streams with reordered frames this can be used to ensure that there is enough time to accommodate first DTS, which may be less than first PTS
- Parameters:
minPts
- minimal PTS that will be passed to handle_frame
-
setOutputState
Creates a newGstVideoCodecState
with the specified caps as the output state for the encoder. Any previously set output state on this VideoEncoder will be replaced by the newly created one.The specified
caps
should not contain any resolution, pixel-aspect-ratio, framerate, codec-data, .... Those should be specified instead in the returnedGstVideoCodecState
.If the subclass wishes to copy over existing fields (like pixel aspect ratio, or framerate) from an existing
GstVideoCodecState
, it can be provided as areference
.If the subclass wishes to override some fields from the output state (like pixel-aspect-ratio or framerate) it can do so on the returned
GstVideoCodecState
.The new output state will only take effect (set on pads and buffers) starting from the next call to
gst_video_encoder_finish_frame
().- Parameters:
caps
- theGstCaps
to use for the outputreference
- An optional referenceGstVideoCodecState
- Returns:
- the newly configured output state.
-
setQosEnabled
public void setQosEnabled(boolean enabled) Configures this VideoEncoder to handle Quality-of-Service events from downstream.- Parameters:
enabled
- the new qos value.
-
close
protected boolean close()Optional. Called when the element changes to GST_STATE_NULL. Allows closing external resources. -
decideAllocation
Optional. Setup the allocation parameters for allocating output buffers. The passed in query contains the result of the downstream allocation query. Subclasses should chain up to the parent implementation to invoke the default handler. -
finish
Optional. Called to request subclass to dispatch any pending remaining data (e.g. at EOS). -
flush
protected boolean flush()Optional. Flush all remaining data from the encoder without pushing it downstream. Since: 1.2 -
getcaps
-
handleFrame
Provides input frame to subclass. -
open
protected boolean open()Optional. Called when the element changes to GST_STATE_READY. Allows opening external resources. -
prePush
Optional. Allows subclass to push frame downstream in whatever shape or form it deems appropriate. If not provided, provided encoded frame data is simply pushed downstream. -
proposeAllocation
Optional. Propose buffer allocation parameters for upstream elements. Subclasses should chain up to the parent implementation to invoke the default handler. -
reset
protected boolean reset(boolean hard) Optional. Allows subclass (encoder) to perform post-seek semantics reset. Deprecated. -
setFormat
Optional. Notifies subclass of incoming data format. GstVideoCodecState fields have already been set according to provided caps. -
sinkEvent
Optional. Event handler on the sink pad. This function should return TRUE if the event was handled and should be discarded (i.e. not unref'ed). Subclasses should chain up to the parent implementation to invoke the default handler. -
sinkQuery
Optional. Query handler on the sink pad. This function should return TRUE if the query could be performed. Subclasses should chain up to the parent implementation to invoke the default handler. Since: 1.4 -
srcEvent
Optional. Event handler on the source pad. This function should return TRUE if the event was handled and should be discarded (i.e. not unref'ed). Subclasses should chain up to the parent implementation to invoke the default handler. -
srcQuery
Optional. Query handler on the source pad. This function should return TRUE if the query could be performed. Subclasses should chain up to the parent implementation to invoke the default handler. Since: 1.4 -
start
protected boolean start()Optional. Called when the element starts processing. Allows opening external resources. -
stop
protected boolean stop()Optional. Called when the element stops processing. Allows closing external resources. -
transformMeta
Optional. Transform the metadata on the input buffer to the output buffer. By default this method is copies all meta without tags and meta with only the "video" tag. subclasses can implement this method and returntrue
if the metadata is to be copied. Since: 1.6 -
builder
AVideoEncoder.Builder
object constructs aVideoEncoder
with the specified properties. Use the variousset...()
methods to set properties, and finish construction withVideoEncoder.Builder.build()
.
-