Class VideoEncoder
- Direct Known Subclasses:
VideoEncoder.VideoEncoder$Impl
GstVideoEncoder and subclass should cooperate as follows.
Configuration
- Initially, GstVideoEncoder calls
startwhen the encoder element is activated, which allows subclass to perform any global setup. - GstVideoEncoder calls
setFormatto 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
stopat 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
gstVideoEncoderFinishFrameto have encoded data pushed downstream.
- If implemented, baseclass calls subclass
prePushjust 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
eventcallback has been provided.
Shutdown phase
- GstVideoEncoder class calls
stopto 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
handleFrameand 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
Nested ClassesModifier and TypeClassDescriptionstatic classVideoEncoder.Builder<B extends VideoEncoder.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static classThe VideoEncoder$Impl type represents a native instance of the abstract VideoEncoder class.static classSubclasses can override any of the available virtual methods or not, as needed.Nested classes/interfaces inherited from class org.freedesktop.gstreamer.gst.Element
Element.Element$Impl, Element.ElementClass, Element.NoMorePadsCallback, Element.PadAddedCallback, Element.PadRemovedCallbackNested classes/interfaces inherited from class org.freedesktop.gstreamer.gst.GstObject
GstObject.DeepNotifyCallback, GstObject.Object$Impl, GstObject.ObjectClassNested classes/interfaces inherited from class org.gnome.gobject.InitiallyUnowned
InitiallyUnowned.InitiallyUnownedClassNested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallbackNested classes/interfaces inherited from interface org.freedesktop.gstreamer.gst.Preset
Preset.Preset$Impl, Preset.PresetInterface -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new VideoEncoder.VideoEncoder(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 forencoder'scurrentGstVideoCodecState.allocateOutputFrame(VideoCodecFrame frame, long size) Helper function that allocates a buffer to hold an encoded video frame forencoder'scurrentGstVideoCodecState.protected VideoEncoderasParent()Returns this instance as if it were its parent type.protected booleanclose()Optional.protected booleandecideAllocation(Query query) Optional.voiddropFrame(VideoCodecFrame frame) Removesframefrom the list of pending frames, releases it and posts a QoS message with the frame's details on the bus.protected FlowReturnfinish()Optional.finishFrame(VideoCodecFrame frame) framemust 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 booleanflush()Optional.voidgetAllocator(@Nullable Out<Allocator> allocator, @Nullable AllocationParams params) LetsGstVideoEncodersub-classes to know the memoryallocatorused by the base class and itsparams.protected CapsOptional.@Nullable VideoCodecFramegetFrame(int frameNumber) Get a pending unfinishedGstVideoCodecFrameGet all pending unfinishedGstVideoCodecFramevoidgetLatency(@Nullable ClockTime minLatency, @Nullable ClockTime maxLatency) Query the configured encoding latency.getMaxEncodeTime(VideoCodecFrame frame) Determines maximum possible encoding time forframethat will allow it to encode and arrive in time (as determined by QoS events).static MemoryLayoutThe 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.@Nullable VideoCodecFrameGet the oldest unfinished pendingGstVideoCodecFrame@Nullable VideoCodecStateGet the currentGstVideoCodecStatestatic @Nullable TypegetType()Get the GType of the VideoEncoder classprotected FlowReturnhandleFrame(VideoCodecFrame frame) Provides input frame to subclass.booleanChecks if this VideoEncoder is currently configured to handle Quality-of-Service events from downstream.voidmergeTags(@Nullable TagList tags, TagMergeMode mode) Sets the video encoder tags and how they should be merged with any upstream stream tags.booleanNegotiate with downstream elements to currently configuredGstVideoCodecState.protected booleanopen()Optional.protected FlowReturnprePush(VideoCodecFrame frame) Optional.protected booleanproposeAllocation(Query query) Optional.proxyGetcaps(@Nullable Caps caps, @Nullable Caps filter) Returns caps that expresscaps(or sink template caps ifcaps== NULL) restricted to resolution/format/...voidreleaseFrame(VideoCodecFrame frame) Removesframefrom list of pending frames and releases it, similar to calling gst_video_encoder_finish_frame() without a buffer attached to the frame, but does not post a QoS message or do any additional processing.protected booleanreset(boolean hard) Optional.protected booleansetFormat(VideoCodecState state) Optional.voidsetHeaders(List<Buffer> headers) Set the codec headers to be sent downstream whenever requested.voidsetLatency(ClockTime minLatency, ClockTime maxLatency) Informs baseclass of encoding latency.voidsetMinForceKeyUnitInterval(ClockTime interval) Sets the minimum interval for requesting keyframes based on force-keyunit events.voidRequest minimal value for PTS passed to handle_frame.@Nullable VideoCodecStatesetOutputState(Caps caps, @Nullable VideoCodecState reference) Creates a newGstVideoCodecStatewith the specified caps as the output state for the encoder.voidsetQosEnabled(boolean enabled) Configures this VideoEncoder to handle Quality-of-Service events from downstream.protected booleanOptional.protected booleanOptional.protected booleanOptional.protected booleanOptional.protected booleanstart()Optional.protected booleanstop()Optional.protected booleantransformMeta(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, unlinkPadsMethods 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, unrefMethods inherited from class org.gnome.gobject.InitiallyUnowned
builderMethods 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, 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, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCodeMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods 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
-
VideoEncoder
public VideoEncoder()Creates a new VideoEncoder.
-
-
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 Javasuperkeyword, 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 forencoder'scurrentGstVideoCodecState.- Parameters:
size- size of the buffer- Returns:
- allocated buffer
-
allocateOutputFrame
Helper function that allocates a buffer to hold an encoded video frame forencoder'scurrentGstVideoCodecState. 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- aGstVideoCodecFramesize- size of the buffer- Returns:
FlowReturn.OKif an output buffer could be allocated
-
dropFrame
Removesframefrom the list of pending frames, releases it and posts a QoS message with the frame's details on the bus. Similar to calling gst_video_encoder_finish_frame() without a buffer attached toframe,but this function additionally stores events fromframeas pending, to be pushed out alongside the next frame submitted via gst_video_encoder_finish_frame().- Parameters:
frame- aGstVideoCodecFrame- Since:
- 1.26
-
finishFrame
framemust 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.If
framedoes not have a buffer attached, it will be dropped, and a QoS message will be posted on the bus. Events fromframewill be pushed out immediately.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
GstFlowReturnresulting 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
frameand frame->output_buffer will be pushed downstream.- Parameters:
frame- aGstVideoCodecFramebeing encoded- Returns:
- a
GstFlowReturnresulting from pushing the buffer downstream. - Since:
- 1.18
-
getAllocator
LetsGstVideoEncodersub-classes to know the memoryallocatorused by the base class and itsparams.Unref the
allocatorafter use it.- Parameters:
allocator- theGstAllocatorusedparams- theGstAllocationParamsofallocator
-
getFrame
Get a pending unfinishedGstVideoCodecFrame- Parameters:
frameNumber- system_frame_number of a frame- Returns:
- pending unfinished
GstVideoCodecFrameidentified byframeNumber.
-
getFrames
Get all pending unfinishedGstVideoCodecFrame- Returns:
- pending unfinished
GstVideoCodecFrame.
-
getLatency
Query the configured encoding latency. Results will be returned viaminLatencyandmaxLatency.- Parameters:
minLatency- address of variable in which to store the configured minimum latency, ornullmaxLatency- address of variable in which to store the configured maximum latency, ornull
-
getMaxEncodeTime
Determines maximum possible encoding time forframethat 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.
- Since:
- 1.14
-
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
- Since:
- 1.18
-
getOldestFrame
Get the oldest unfinished pendingGstVideoCodecFrame- Returns:
- oldest unfinished pending
GstVideoCodecFrame
-
getOutputState
Get the currentGstVideoCodecState- Returns:
GstVideoCodecStatedescribing format of video data.
-
isQosEnabled
public boolean isQosEnabled()Checks if this VideoEncoder is currently configured to handle Quality-of-Service events from downstream.- Returns:
trueif the encoder is configured to perform Quality-of-Service.- Since:
- 1.14
-
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- aGstTagListto merge, or NULL to unset previously-set tagsmode- theGstTagMergeModeto 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:
trueif 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
GstCapsowned by caller
-
releaseFrame
Removesframefrom list of pending frames and releases it, similar to calling gst_video_encoder_finish_frame() without a buffer attached to the frame, but does not post a QoS message or do any additional processing. Events fromframeare moved to the pending events list.- Parameters:
frame- aGstVideoCodecFrame- Since:
- 1.26
-
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_NONEcauses force-keyunit events to be ignored.- Parameters:
interval- minimum interval- Since:
- 1.18
-
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- Since:
- 1.6
-
setOutputState
Creates a newGstVideoCodecStatewith 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
capsshould 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- theGstCapsto 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.- Since:
- 1.14
-
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 returntrueif the metadata is to be copied. Since: 1.6
-