2 * Copyright (C) 2008 David Schleef <ds@schleef.org>
3 * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>.
4 * Copyright (C) 2011 Nokia Corporation. All rights reserved.
5 * Contact: Stefan Kost <stefan.kost@nokia.com>
6 * Copyright (C) 2012 Collabora Ltd.
7 * Author : Edward Hervey <edward@collabora.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public
20 * License along with this library; if not, write to the
21 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
26 * SECTION:gstvideoencoder
27 * @short_description: Base class for video encoders
30 * This base class is for video encoders turning raw video into
33 * GstVideoEncoder and subclass should cooperate as follows.
36 * <itemizedlist><title>Configuration</title>
38 * Initially, GstVideoEncoder calls @start when the encoder element
39 * is activated, which allows subclass to perform any global setup.
42 * GstVideoEncoder calls @set_format to inform subclass of the format
43 * of input video data that it is about to receive. Subclass should
44 * setup for encoding and configure base class as appropriate
45 * (e.g. latency). While unlikely, it might be called more than once,
46 * if changing input parameters require reconfiguration. Baseclass
47 * will ensure that processing of current configuration is finished.
50 * GstVideoEncoder calls @stop at end of all processing.
56 * <title>Data processing</title>
58 * Base class collects input data and metadata into a frame and hands
59 * this to subclass' @handle_frame.
62 * If codec processing results in encoded data, subclass should call
63 * @gst_video_encoder_finish_frame to have encoded data pushed
67 * If implemented, baseclass calls subclass @pre_push just prior to
68 * pushing to allow subclasses to modify some metadata on the buffer.
69 * If it returns GST_FLOW_OK, the buffer is pushed downstream.
72 * GstVideoEncoderClass will handle both srcpad and sinkpad events.
73 * Sink events will be passed to subclass if @event callback has been
79 * <itemizedlist><title>Shutdown phase</title>
81 * GstVideoEncoder class calls @stop to inform the subclass that data
82 * parsing will be stopped.
88 * Subclass is responsible for providing pad template caps for
89 * source and sink pads. The pads need to be named "sink" and "src". It should
90 * also be able to provide fixed src pad caps in @getcaps by the time it calls
91 * @gst_video_encoder_finish_frame.
93 * Things that subclass need to take care of:
95 * <listitem><para>Provide pad templates</para></listitem>
97 * Provide source pad caps before pushing the first buffer
100 * Accept data in @handle_frame and provide encoded results to
101 * @gst_video_encoder_finish_frame.
113 * * Calculate actual latency based on input/output timestamp/frame_number
114 * and if it exceeds the recorded one, save it and emit a GST_MESSAGE_LATENCY
117 #include <gst/video/video.h>
118 #include "gstvideoencoder.h"
119 #include "gstvideoutils.h"
121 #include <gst/video/gstvideometa.h>
122 #include <gst/video/gstvideopool.h>
126 GST_DEBUG_CATEGORY (videoencoder_debug);
127 #define GST_CAT_DEFAULT videoencoder_debug
129 #define GST_VIDEO_ENCODER_GET_PRIVATE(obj) \
130 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_VIDEO_ENCODER, \
131 GstVideoEncoderPrivate))
133 struct _GstVideoEncoderPrivate
135 guint64 presentation_frame_number;
136 int distance_from_sync;
138 /* FIXME : (and introduce a context ?) */
146 GList *current_frame_events;
149 gboolean new_headers; /* Whether new headers were just set */
151 GList *force_key_unit; /* List of pending forced keyunits */
153 guint32 system_frame_number;
155 GList *frames; /* Protected with OBJECT_LOCK */
156 GstVideoCodecState *input_state;
157 GstVideoCodecState *output_state;
158 gboolean output_state_changed;
163 GstAllocator *allocator;
164 GstAllocationParams params;
167 gboolean tags_changed;
170 typedef struct _ForcedKeyUnitEvent ForcedKeyUnitEvent;
171 struct _ForcedKeyUnitEvent
173 GstClockTime running_time;
174 gboolean pending; /* TRUE if this was requested already */
175 gboolean all_headers;
180 forced_key_unit_event_free (ForcedKeyUnitEvent * evt)
182 g_slice_free (ForcedKeyUnitEvent, evt);
185 static ForcedKeyUnitEvent *
186 forced_key_unit_event_new (GstClockTime running_time, gboolean all_headers,
189 ForcedKeyUnitEvent *evt = g_slice_new0 (ForcedKeyUnitEvent);
191 evt->running_time = running_time;
192 evt->all_headers = all_headers;
198 static GstElementClass *parent_class = NULL;
199 static void gst_video_encoder_class_init (GstVideoEncoderClass * klass);
200 static void gst_video_encoder_init (GstVideoEncoder * enc,
201 GstVideoEncoderClass * klass);
203 static void gst_video_encoder_finalize (GObject * object);
205 static gboolean gst_video_encoder_setcaps (GstVideoEncoder * enc,
207 static GstCaps *gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder,
209 static gboolean gst_video_encoder_src_event (GstPad * pad, GstObject * parent,
211 static gboolean gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
213 static GstFlowReturn gst_video_encoder_chain (GstPad * pad, GstObject * parent,
215 static GstStateChangeReturn gst_video_encoder_change_state (GstElement *
216 element, GstStateChange transition);
217 static gboolean gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
219 static gboolean gst_video_encoder_src_query (GstPad * pad, GstObject * parent,
221 static GstVideoCodecFrame *gst_video_encoder_new_frame (GstVideoEncoder *
222 encoder, GstBuffer * buf, GstClockTime pts, GstClockTime dts,
223 GstClockTime duration);
225 static gboolean gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
227 static gboolean gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
229 static gboolean gst_video_encoder_decide_allocation_default (GstVideoEncoder *
230 encoder, GstQuery * query);
231 static gboolean gst_video_encoder_propose_allocation_default (GstVideoEncoder *
232 encoder, GstQuery * query);
233 static gboolean gst_video_encoder_negotiate_default (GstVideoEncoder * encoder);
235 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
236 * method to get to the padtemplates */
238 gst_video_encoder_get_type (void)
240 static volatile gsize type = 0;
242 if (g_once_init_enter (&type)) {
244 static const GTypeInfo info = {
245 sizeof (GstVideoEncoderClass),
248 (GClassInitFunc) gst_video_encoder_class_init,
251 sizeof (GstVideoEncoder),
253 (GInstanceInitFunc) gst_video_encoder_init,
255 const GInterfaceInfo preset_interface_info = {
256 NULL, /* interface_init */
257 NULL, /* interface_finalize */
258 NULL /* interface_data */
261 _type = g_type_register_static (GST_TYPE_ELEMENT,
262 "GstVideoEncoder", &info, G_TYPE_FLAG_ABSTRACT);
263 g_type_add_interface_static (_type, GST_TYPE_PRESET,
264 &preset_interface_info);
265 g_once_init_leave (&type, _type);
271 gst_video_encoder_class_init (GstVideoEncoderClass * klass)
273 GObjectClass *gobject_class;
274 GstElementClass *gstelement_class;
276 gobject_class = G_OBJECT_CLASS (klass);
277 gstelement_class = GST_ELEMENT_CLASS (klass);
279 GST_DEBUG_CATEGORY_INIT (videoencoder_debug, "videoencoder", 0,
280 "Base Video Encoder");
282 parent_class = g_type_class_peek_parent (klass);
284 g_type_class_add_private (klass, sizeof (GstVideoEncoderPrivate));
286 gobject_class->finalize = gst_video_encoder_finalize;
288 gstelement_class->change_state =
289 GST_DEBUG_FUNCPTR (gst_video_encoder_change_state);
291 klass->sink_event = gst_video_encoder_sink_event_default;
292 klass->src_event = gst_video_encoder_src_event_default;
293 klass->propose_allocation = gst_video_encoder_propose_allocation_default;
294 klass->decide_allocation = gst_video_encoder_decide_allocation_default;
295 klass->negotiate = gst_video_encoder_negotiate_default;
299 gst_video_encoder_reset (GstVideoEncoder * encoder, gboolean hard)
301 GstVideoEncoderPrivate *priv = encoder->priv;
304 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
306 priv->presentation_frame_number = 0;
307 priv->distance_from_sync = 0;
309 g_list_foreach (priv->force_key_unit, (GFunc) forced_key_unit_event_free,
311 g_list_free (priv->force_key_unit);
312 priv->force_key_unit = NULL;
314 priv->drained = TRUE;
316 g_list_foreach (priv->current_frame_events, (GFunc) gst_event_unref, NULL);
317 g_list_free (priv->current_frame_events);
318 priv->current_frame_events = NULL;
320 g_list_foreach (priv->frames, (GFunc) gst_video_codec_frame_unref, NULL);
321 g_list_free (priv->frames);
328 gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
329 gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
331 if (priv->input_state)
332 gst_video_codec_state_unref (priv->input_state);
333 priv->input_state = NULL;
334 if (priv->output_state)
335 gst_video_codec_state_unref (priv->output_state);
336 priv->output_state = NULL;
339 gst_tag_list_unref (priv->tags);
341 priv->tags_changed = FALSE;
343 priv->min_latency = 0;
344 priv->max_latency = 0;
346 g_list_foreach (priv->headers, (GFunc) gst_event_unref, NULL);
347 g_list_free (priv->headers);
348 priv->headers = NULL;
349 priv->new_headers = FALSE;
352 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
357 /* Always call reset() in one way or another after this */
359 gst_video_encoder_flush (GstVideoEncoder * encoder)
361 GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
364 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
366 ret = klass->flush (encoder);
368 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
373 gst_video_encoder_init (GstVideoEncoder * encoder, GstVideoEncoderClass * klass)
375 GstVideoEncoderPrivate *priv;
376 GstPadTemplate *pad_template;
379 GST_DEBUG_OBJECT (encoder, "gst_video_encoder_init");
381 priv = encoder->priv = GST_VIDEO_ENCODER_GET_PRIVATE (encoder);
384 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
385 g_return_if_fail (pad_template != NULL);
387 encoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
389 gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_video_encoder_chain));
390 gst_pad_set_event_function (pad,
391 GST_DEBUG_FUNCPTR (gst_video_encoder_sink_event));
392 gst_pad_set_query_function (pad,
393 GST_DEBUG_FUNCPTR (gst_video_encoder_sink_query));
394 gst_element_add_pad (GST_ELEMENT (encoder), encoder->sinkpad);
397 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
398 g_return_if_fail (pad_template != NULL);
400 encoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
402 gst_pad_set_query_function (pad,
403 GST_DEBUG_FUNCPTR (gst_video_encoder_src_query));
404 gst_pad_set_event_function (pad,
405 GST_DEBUG_FUNCPTR (gst_video_encoder_src_event));
406 gst_element_add_pad (GST_ELEMENT (encoder), encoder->srcpad);
408 gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
409 gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
411 g_rec_mutex_init (&encoder->stream_lock);
413 priv->at_eos = FALSE;
414 priv->headers = NULL;
415 priv->new_headers = FALSE;
417 gst_video_encoder_reset (encoder, TRUE);
421 gst_video_encoded_video_convert (gint64 bytes, gint64 time,
422 GstFormat src_format, gint64 src_value, GstFormat * dest_format,
425 gboolean res = FALSE;
427 g_return_val_if_fail (dest_format != NULL, FALSE);
428 g_return_val_if_fail (dest_value != NULL, FALSE);
430 if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
433 *dest_value = src_value;
437 if (bytes <= 0 || time <= 0) {
438 GST_DEBUG ("not enough metadata yet to convert");
442 switch (src_format) {
443 case GST_FORMAT_BYTES:
444 switch (*dest_format) {
445 case GST_FORMAT_TIME:
446 *dest_value = gst_util_uint64_scale (src_value, time, bytes);
453 case GST_FORMAT_TIME:
454 switch (*dest_format) {
455 case GST_FORMAT_BYTES:
456 *dest_value = gst_util_uint64_scale (src_value, bytes, time);
464 GST_DEBUG ("unhandled conversion from %d to %d", src_format,
474 * gst_video_encoder_set_headers:
475 * @encoder: a #GstVideoEncoder
476 * @headers: (transfer full) (element-type GstBuffer): a list of #GstBuffer containing the codec header
478 * Set the codec headers to be sent downstream whenever requested.
481 gst_video_encoder_set_headers (GstVideoEncoder * video_encoder, GList * headers)
483 GST_VIDEO_ENCODER_STREAM_LOCK (video_encoder);
485 GST_DEBUG_OBJECT (video_encoder, "new headers %p", headers);
486 if (video_encoder->priv->headers) {
487 g_list_foreach (video_encoder->priv->headers, (GFunc) gst_buffer_unref,
489 g_list_free (video_encoder->priv->headers);
491 video_encoder->priv->headers = headers;
492 video_encoder->priv->new_headers = TRUE;
494 GST_VIDEO_ENCODER_STREAM_UNLOCK (video_encoder);
497 static GstVideoCodecState *
498 _new_output_state (GstCaps * caps, GstVideoCodecState * reference)
500 GstVideoCodecState *state;
502 state = g_slice_new0 (GstVideoCodecState);
503 state->ref_count = 1;
504 gst_video_info_init (&state->info);
505 gst_video_info_set_format (&state->info, GST_VIDEO_FORMAT_ENCODED, 0, 0);
510 GstVideoInfo *tgt, *ref;
513 ref = &reference->info;
515 /* Copy over extra fields from reference state */
516 tgt->interlace_mode = ref->interlace_mode;
517 tgt->flags = ref->flags;
518 tgt->width = ref->width;
519 tgt->height = ref->height;
520 tgt->chroma_site = ref->chroma_site;
521 tgt->colorimetry = ref->colorimetry;
522 tgt->par_n = ref->par_n;
523 tgt->par_d = ref->par_d;
524 tgt->fps_n = ref->fps_n;
525 tgt->fps_d = ref->fps_d;
531 static GstVideoCodecState *
532 _new_input_state (GstCaps * caps)
534 GstVideoCodecState *state;
536 state = g_slice_new0 (GstVideoCodecState);
537 state->ref_count = 1;
538 gst_video_info_init (&state->info);
539 if (G_UNLIKELY (!gst_video_info_from_caps (&state->info, caps)))
541 state->caps = gst_caps_ref (caps);
547 g_slice_free (GstVideoCodecState, state);
553 gst_video_encoder_setcaps (GstVideoEncoder * encoder, GstCaps * caps)
555 GstVideoEncoderClass *encoder_class;
556 GstVideoCodecState *state;
559 encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
561 /* subclass should do something here ... */
562 g_return_val_if_fail (encoder_class->set_format != NULL, FALSE);
564 GST_DEBUG_OBJECT (encoder, "setcaps %" GST_PTR_FORMAT, caps);
566 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
568 if (encoder->priv->input_state) {
569 GST_DEBUG_OBJECT (encoder,
570 "Checking if caps changed old %" GST_PTR_FORMAT " new %" GST_PTR_FORMAT,
571 encoder->priv->input_state->caps, caps);
572 if (gst_caps_is_equal (encoder->priv->input_state->caps, caps))
573 goto caps_not_changed;
576 state = _new_input_state (caps);
577 if (G_UNLIKELY (!state))
580 if (encoder->priv->input_state
581 && gst_video_info_is_equal (&state->info,
582 &encoder->priv->input_state->info)) {
583 gst_video_codec_state_unref (state);
584 goto caps_not_changed;
587 if (encoder_class->reset) {
588 GST_FIXME_OBJECT (encoder, "GstVideoEncoder::reset() is deprecated");
589 ret = encoder_class->reset (encoder, TRUE);
592 /* and subclass should be ready to configure format at any time around */
593 ret = encoder_class->set_format (encoder, state);
595 if (encoder->priv->input_state)
596 gst_video_codec_state_unref (encoder->priv->input_state);
597 encoder->priv->input_state = state;
599 gst_video_codec_state_unref (state);
602 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
605 GST_WARNING_OBJECT (encoder, "rejected caps %" GST_PTR_FORMAT, caps);
611 GST_DEBUG_OBJECT (encoder, "Caps did not change - ignore");
612 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
619 GST_WARNING_OBJECT (encoder, "Failed to parse caps");
620 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
626 * gst_video_encoder_proxy_getcaps:
627 * @enc: a #GstVideoEncoder
628 * @caps: initial caps
629 * @filter: filter caps
631 * Returns caps that express @caps (or sink template caps if @caps == NULL)
632 * restricted to resolution/format/... combinations supported by downstream
633 * elements (e.g. muxers).
635 * Returns: a #GstCaps owned by caller
638 gst_video_encoder_proxy_getcaps (GstVideoEncoder * encoder, GstCaps * caps,
643 GstCaps *fcaps, *filter_caps;
646 /* Allow downstream to specify width/height/framerate/PAR constraints
647 * and forward them upstream for video converters to handle
650 caps ? gst_caps_ref (caps) :
651 gst_pad_get_pad_template_caps (encoder->sinkpad);
652 allowed = gst_pad_get_allowed_caps (encoder->srcpad);
654 if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
659 GST_LOG_OBJECT (encoder, "template caps %" GST_PTR_FORMAT, templ_caps);
660 GST_LOG_OBJECT (encoder, "allowed caps %" GST_PTR_FORMAT, allowed);
662 filter_caps = gst_caps_new_empty ();
664 for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
666 gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
668 for (j = 0; j < gst_caps_get_size (allowed); j++) {
669 const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
673 s = gst_structure_new_id_empty (q_name);
674 if ((val = gst_structure_get_value (allowed_s, "width")))
675 gst_structure_set_value (s, "width", val);
676 if ((val = gst_structure_get_value (allowed_s, "height")))
677 gst_structure_set_value (s, "height", val);
678 if ((val = gst_structure_get_value (allowed_s, "framerate")))
679 gst_structure_set_value (s, "framerate", val);
680 if ((val = gst_structure_get_value (allowed_s, "pixel-aspect-ratio")))
681 gst_structure_set_value (s, "pixel-aspect-ratio", val);
683 filter_caps = gst_caps_merge_structure (filter_caps, s);
687 fcaps = gst_caps_intersect (filter_caps, templ_caps);
688 gst_caps_unref (filter_caps);
689 gst_caps_unref (templ_caps);
692 GST_LOG_OBJECT (encoder, "intersecting with %" GST_PTR_FORMAT, filter);
693 filter_caps = gst_caps_intersect (fcaps, filter);
694 gst_caps_unref (fcaps);
699 gst_caps_replace (&allowed, NULL);
701 GST_LOG_OBJECT (encoder, "proxy caps %" GST_PTR_FORMAT, fcaps);
707 gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder, GstCaps * filter)
709 GstVideoEncoderClass *klass;
712 klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
715 caps = klass->getcaps (encoder, filter);
717 caps = gst_video_encoder_proxy_getcaps (encoder, NULL, filter);
719 GST_LOG_OBJECT (encoder, "Returning caps %" GST_PTR_FORMAT, caps);
725 gst_video_encoder_decide_allocation_default (GstVideoEncoder * encoder,
728 GstAllocator *allocator = NULL;
729 GstAllocationParams params;
730 gboolean update_allocator;
732 /* we got configuration from our peer or the decide_allocation method,
734 if (gst_query_get_n_allocation_params (query) > 0) {
735 /* try the allocator */
736 gst_query_parse_nth_allocation_param (query, 0, &allocator, ¶ms);
737 update_allocator = TRUE;
740 gst_allocation_params_init (¶ms);
741 update_allocator = FALSE;
744 if (update_allocator)
745 gst_query_set_nth_allocation_param (query, 0, allocator, ¶ms);
747 gst_query_add_allocation_param (query, allocator, ¶ms);
749 gst_object_unref (allocator);
755 gst_video_encoder_propose_allocation_default (GstVideoEncoder * encoder,
763 gst_query_parse_allocation (query, &caps, NULL);
768 if (!gst_video_info_from_caps (&info, caps))
771 size = GST_VIDEO_INFO_SIZE (&info);
773 if (gst_query_get_n_allocation_pools (query) == 0) {
774 GstStructure *structure;
775 GstAllocator *allocator = NULL;
776 GstAllocationParams params = { 0, 15, 0, 0 };
778 if (gst_query_get_n_allocation_params (query) > 0)
779 gst_query_parse_nth_allocation_param (query, 0, &allocator, ¶ms);
781 gst_query_add_allocation_param (query, allocator, ¶ms);
783 pool = gst_video_buffer_pool_new ();
785 structure = gst_buffer_pool_get_config (pool);
786 gst_buffer_pool_config_set_params (structure, caps, size, 0, 0);
787 gst_buffer_pool_config_set_allocator (structure, allocator, ¶ms);
790 gst_object_unref (allocator);
792 if (!gst_buffer_pool_set_config (pool, structure))
795 gst_query_add_allocation_pool (query, pool, size, 0, 0);
796 gst_object_unref (pool);
797 gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
805 GST_ERROR_OBJECT (encoder, "failed to set config");
806 gst_object_unref (pool);
812 gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
815 GstVideoEncoder *encoder;
816 gboolean res = FALSE;
818 encoder = GST_VIDEO_ENCODER (parent);
820 switch (GST_QUERY_TYPE (query)) {
823 GstCaps *filter, *caps;
825 gst_query_parse_caps (query, &filter);
826 caps = gst_video_encoder_sink_getcaps (encoder, filter);
827 gst_query_set_caps_result (query, caps);
828 gst_caps_unref (caps);
832 case GST_QUERY_ALLOCATION:
834 GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
836 if (klass->propose_allocation)
837 res = klass->propose_allocation (encoder, query);
841 res = gst_pad_query_default (pad, parent, query);
848 gst_video_encoder_finalize (GObject * object)
850 GstVideoEncoder *encoder;
852 GST_DEBUG_OBJECT (object, "finalize");
854 encoder = GST_VIDEO_ENCODER (object);
855 g_rec_mutex_clear (&encoder->stream_lock);
857 if (encoder->priv->allocator) {
858 gst_object_unref (encoder->priv->allocator);
859 encoder->priv->allocator = NULL;
862 G_OBJECT_CLASS (parent_class)->finalize (object);
866 gst_video_encoder_push_event (GstVideoEncoder * encoder, GstEvent * event)
868 switch (GST_EVENT_TYPE (event)) {
869 case GST_EVENT_SEGMENT:
873 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
875 gst_event_copy_segment (event, &segment);
877 GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
879 if (segment.format != GST_FORMAT_TIME) {
880 GST_DEBUG_OBJECT (encoder, "received non TIME segment");
881 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
885 encoder->output_segment = segment;
886 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
893 return gst_pad_push_event (encoder->srcpad, event);
897 gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
900 GstVideoEncoderClass *encoder_class;
901 gboolean ret = FALSE;
903 encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
905 switch (GST_EVENT_TYPE (event)) {
910 gst_event_parse_caps (event, &caps);
912 encoder->priv->do_caps = TRUE;
913 gst_event_unref (event);
919 GstFlowReturn flow_ret;
921 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
922 encoder->priv->at_eos = TRUE;
924 if (encoder_class->finish) {
925 flow_ret = encoder_class->finish (encoder);
927 flow_ret = GST_FLOW_OK;
930 ret = (flow_ret == GST_FLOW_OK);
931 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
934 case GST_EVENT_SEGMENT:
938 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
940 gst_event_copy_segment (event, &segment);
942 GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
944 if (segment.format != GST_FORMAT_TIME) {
945 GST_DEBUG_OBJECT (encoder, "received non TIME newsegment");
946 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
950 encoder->priv->at_eos = FALSE;
952 encoder->input_segment = segment;
954 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
957 case GST_EVENT_CUSTOM_DOWNSTREAM:
959 if (gst_video_event_is_force_key_unit (event)) {
960 GstClockTime running_time;
961 gboolean all_headers;
964 if (gst_video_event_parse_downstream_force_key_unit (event,
965 NULL, NULL, &running_time, &all_headers, &count)) {
966 ForcedKeyUnitEvent *fevt;
968 GST_OBJECT_LOCK (encoder);
969 fevt = forced_key_unit_event_new (running_time, all_headers, count);
970 encoder->priv->force_key_unit =
971 g_list_append (encoder->priv->force_key_unit, fevt);
972 GST_OBJECT_UNLOCK (encoder);
974 GST_DEBUG_OBJECT (encoder,
975 "force-key-unit event: running-time %" GST_TIME_FORMAT
976 ", all_headers %d, count %u",
977 GST_TIME_ARGS (running_time), all_headers, count);
979 gst_event_unref (event);
989 gst_event_parse_tag (event, &tags);
991 if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
992 tags = gst_tag_list_copy (tags);
994 /* FIXME: make generic based on GST_TAG_FLAG_ENCODED */
995 gst_tag_list_remove_tag (tags, GST_TAG_CODEC);
996 gst_tag_list_remove_tag (tags, GST_TAG_AUDIO_CODEC);
997 gst_tag_list_remove_tag (tags, GST_TAG_VIDEO_CODEC);
998 gst_tag_list_remove_tag (tags, GST_TAG_SUBTITLE_CODEC);
999 gst_tag_list_remove_tag (tags, GST_TAG_CONTAINER_FORMAT);
1000 gst_tag_list_remove_tag (tags, GST_TAG_BITRATE);
1001 gst_tag_list_remove_tag (tags, GST_TAG_NOMINAL_BITRATE);
1002 gst_tag_list_remove_tag (tags, GST_TAG_MAXIMUM_BITRATE);
1003 gst_tag_list_remove_tag (tags, GST_TAG_MINIMUM_BITRATE);
1004 gst_tag_list_remove_tag (tags, GST_TAG_ENCODER);
1005 gst_tag_list_remove_tag (tags, GST_TAG_ENCODER_VERSION);
1007 gst_video_encoder_merge_tags (encoder, tags, GST_TAG_MERGE_REPLACE);
1008 gst_tag_list_unref (tags);
1009 gst_event_unref (event);
1015 case GST_EVENT_FLUSH_STOP:{
1016 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1017 gst_video_encoder_flush (encoder);
1018 gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
1019 gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
1020 gst_video_encoder_reset (encoder, FALSE);
1021 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1028 /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
1029 * For EOS this is required because no buffer or serialized event
1030 * will come after EOS and nothing could trigger another
1031 * _finish_frame() call. *
1032 * If the subclass handles sending of EOS manually it can simply
1033 * not chain up to the parent class' event handler
1035 * For FLUSH_STOP this is required because it is expected
1036 * to be forwarded immediately and no buffers are queued anyway.
1039 if (!GST_EVENT_IS_SERIALIZED (event)
1040 || GST_EVENT_TYPE (event) == GST_EVENT_EOS
1041 || GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_STOP) {
1042 ret = gst_video_encoder_push_event (encoder, event);
1044 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1045 encoder->priv->current_frame_events =
1046 g_list_prepend (encoder->priv->current_frame_events, event);
1047 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1056 gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
1059 GstVideoEncoder *enc;
1060 GstVideoEncoderClass *klass;
1061 gboolean ret = TRUE;
1063 enc = GST_VIDEO_ENCODER (parent);
1064 klass = GST_VIDEO_ENCODER_GET_CLASS (enc);
1066 GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1067 GST_EVENT_TYPE_NAME (event));
1069 if (klass->sink_event)
1070 ret = klass->sink_event (enc, event);
1076 gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
1079 gboolean ret = FALSE;
1081 switch (GST_EVENT_TYPE (event)) {
1082 case GST_EVENT_CUSTOM_UPSTREAM:
1084 if (gst_video_event_is_force_key_unit (event)) {
1085 GstClockTime running_time;
1086 gboolean all_headers;
1089 if (gst_video_event_parse_upstream_force_key_unit (event,
1090 &running_time, &all_headers, &count)) {
1091 ForcedKeyUnitEvent *fevt;
1093 GST_OBJECT_LOCK (encoder);
1094 fevt = forced_key_unit_event_new (running_time, all_headers, count);
1095 encoder->priv->force_key_unit =
1096 g_list_append (encoder->priv->force_key_unit, fevt);
1097 GST_OBJECT_UNLOCK (encoder);
1099 GST_DEBUG_OBJECT (encoder,
1100 "force-key-unit event: running-time %" GST_TIME_FORMAT
1101 ", all_headers %d, count %u",
1102 GST_TIME_ARGS (running_time), all_headers, count);
1104 gst_event_unref (event);
1116 gst_pad_event_default (encoder->srcpad, GST_OBJECT_CAST (encoder),
1123 gst_video_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1125 GstVideoEncoder *encoder;
1126 GstVideoEncoderClass *klass;
1127 gboolean ret = FALSE;
1129 encoder = GST_VIDEO_ENCODER (parent);
1130 klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1132 GST_LOG_OBJECT (encoder, "handling event: %" GST_PTR_FORMAT, event);
1134 if (klass->src_event)
1135 ret = klass->src_event (encoder, event);
1141 gst_video_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1143 GstVideoEncoderPrivate *priv;
1144 GstVideoEncoder *enc;
1147 enc = GST_VIDEO_ENCODER (parent);
1150 GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1152 switch (GST_QUERY_TYPE (query)) {
1153 case GST_QUERY_CONVERT:
1155 GstFormat src_fmt, dest_fmt;
1156 gint64 src_val, dest_val;
1158 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1160 gst_video_encoded_video_convert (priv->bytes, priv->time, src_fmt,
1161 src_val, &dest_fmt, &dest_val);
1164 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1167 case GST_QUERY_LATENCY:
1170 GstClockTime min_latency, max_latency;
1172 res = gst_pad_peer_query (enc->sinkpad, query);
1174 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1175 GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1176 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1177 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1179 GST_OBJECT_LOCK (enc);
1180 min_latency += priv->min_latency;
1181 if (enc->priv->max_latency == GST_CLOCK_TIME_NONE) {
1182 max_latency = GST_CLOCK_TIME_NONE;
1183 } else if (max_latency != GST_CLOCK_TIME_NONE) {
1184 max_latency += enc->priv->max_latency;
1186 GST_OBJECT_UNLOCK (enc);
1188 gst_query_set_latency (query, live, min_latency, max_latency);
1193 res = gst_pad_query_default (pad, parent, query);
1198 GST_DEBUG_OBJECT (enc, "query failed");
1202 static GstVideoCodecFrame *
1203 gst_video_encoder_new_frame (GstVideoEncoder * encoder, GstBuffer * buf,
1204 GstClockTime pts, GstClockTime dts, GstClockTime duration)
1206 GstVideoEncoderPrivate *priv = encoder->priv;
1207 GstVideoCodecFrame *frame;
1209 frame = g_slice_new0 (GstVideoCodecFrame);
1211 frame->ref_count = 1;
1213 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1214 frame->system_frame_number = priv->system_frame_number;
1215 priv->system_frame_number++;
1217 frame->presentation_frame_number = priv->presentation_frame_number;
1218 priv->presentation_frame_number++;
1219 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1221 frame->events = priv->current_frame_events;
1222 priv->current_frame_events = NULL;
1223 frame->input_buffer = buf;
1226 frame->duration = duration;
1227 frame->abidata.ABI.ts = pts;
1233 static GstFlowReturn
1234 gst_video_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1236 GstVideoEncoder *encoder;
1237 GstVideoEncoderPrivate *priv;
1238 GstVideoEncoderClass *klass;
1239 GstVideoCodecFrame *frame;
1240 GstClockTime pts, duration;
1241 GstFlowReturn ret = GST_FLOW_OK;
1242 guint64 start, stop, cstart, cstop;
1244 encoder = GST_VIDEO_ENCODER (parent);
1245 priv = encoder->priv;
1246 klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1248 g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1250 if (G_UNLIKELY (encoder->priv->do_caps)) {
1251 GstCaps *caps = gst_pad_get_current_caps (encoder->sinkpad);
1253 goto not_negotiated;
1254 if (!gst_video_encoder_setcaps (encoder, caps)) {
1255 gst_caps_unref (caps);
1256 goto not_negotiated;
1258 gst_caps_unref (caps);
1259 encoder->priv->do_caps = FALSE;
1262 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1264 pts = GST_BUFFER_PTS (buf);
1265 duration = GST_BUFFER_DURATION (buf);
1267 GST_LOG_OBJECT (encoder,
1268 "received buffer of size %" G_GSIZE_FORMAT " with PTS %" GST_TIME_FORMAT
1269 ", DTS %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1270 gst_buffer_get_size (buf), GST_TIME_ARGS (pts),
1271 GST_TIME_ARGS (GST_BUFFER_DTS (buf)), GST_TIME_ARGS (duration));
1279 if (GST_CLOCK_TIME_IS_VALID (duration))
1280 stop = start + duration;
1282 stop = GST_CLOCK_TIME_NONE;
1284 /* Drop buffers outside of segment */
1285 if (!gst_segment_clip (&encoder->input_segment,
1286 GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
1287 GST_DEBUG_OBJECT (encoder, "clipping to segment dropped frame");
1288 gst_buffer_unref (buf);
1292 /* incoming DTS is not really relevant and does not make sense anyway,
1293 * so pass along _NONE and maybe come up with something better later on */
1294 frame = gst_video_encoder_new_frame (encoder, buf, cstart,
1295 GST_CLOCK_TIME_NONE, cstop - cstart);
1297 GST_OBJECT_LOCK (encoder);
1298 if (priv->force_key_unit) {
1299 ForcedKeyUnitEvent *fevt = NULL;
1300 GstClockTime running_time;
1304 gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1307 for (l = priv->force_key_unit; l; l = l->next) {
1308 ForcedKeyUnitEvent *tmp = l->data;
1310 /* Skip pending keyunits */
1314 /* Simple case, keyunit ASAP */
1315 if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1320 /* Event for before this frame */
1321 if (tmp->running_time <= running_time) {
1328 GST_DEBUG_OBJECT (encoder,
1329 "Forcing a key unit at running time %" GST_TIME_FORMAT,
1330 GST_TIME_ARGS (running_time));
1331 GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME (frame);
1332 if (fevt->all_headers)
1333 GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME_HEADERS (frame);
1334 fevt->pending = TRUE;
1337 GST_OBJECT_UNLOCK (encoder);
1339 gst_video_codec_frame_ref (frame);
1340 priv->frames = g_list_append (priv->frames, frame);
1342 /* new data, more finish needed */
1343 priv->drained = FALSE;
1345 GST_LOG_OBJECT (encoder, "passing frame pfn %d to subclass",
1346 frame->presentation_frame_number);
1348 ret = klass->handle_frame (encoder, frame);
1351 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1358 GST_ELEMENT_ERROR (encoder, CORE, NEGOTIATION, (NULL),
1359 ("encoder not initialized"));
1360 gst_buffer_unref (buf);
1361 return GST_FLOW_NOT_NEGOTIATED;
1365 static GstStateChangeReturn
1366 gst_video_encoder_change_state (GstElement * element, GstStateChange transition)
1368 GstVideoEncoder *encoder;
1369 GstVideoEncoderClass *encoder_class;
1370 GstStateChangeReturn ret;
1372 encoder = GST_VIDEO_ENCODER (element);
1373 encoder_class = GST_VIDEO_ENCODER_GET_CLASS (element);
1375 switch (transition) {
1376 case GST_STATE_CHANGE_NULL_TO_READY:
1377 /* open device/library if needed */
1378 if (encoder_class->open && !encoder_class->open (encoder))
1381 case GST_STATE_CHANGE_READY_TO_PAUSED:
1382 /* Initialize device/library if needed */
1383 if (encoder_class->start && !encoder_class->start (encoder))
1385 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1386 gst_video_encoder_reset (encoder, TRUE);
1387 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1393 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1395 switch (transition) {
1396 case GST_STATE_CHANGE_PAUSED_TO_READY:
1397 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1398 gst_video_encoder_reset (encoder, TRUE);
1399 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1400 if (encoder_class->stop && !encoder_class->stop (encoder))
1403 case GST_STATE_CHANGE_READY_TO_NULL:
1404 /* close device/library if needed */
1405 if (encoder_class->close && !encoder_class->close (encoder))
1418 GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1419 ("Failed to open encoder"));
1420 return GST_STATE_CHANGE_FAILURE;
1425 GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1426 ("Failed to start encoder"));
1427 return GST_STATE_CHANGE_FAILURE;
1432 GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1433 ("Failed to stop encoder"));
1434 return GST_STATE_CHANGE_FAILURE;
1439 GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1440 ("Failed to close encoder"));
1441 return GST_STATE_CHANGE_FAILURE;
1446 gst_video_encoder_negotiate_default (GstVideoEncoder * encoder)
1448 GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1449 GstAllocator *allocator;
1450 GstAllocationParams params;
1451 gboolean ret = TRUE;
1452 GstVideoCodecState *state = encoder->priv->output_state;
1453 GstVideoInfo *info = &state->info;
1454 GstQuery *query = NULL;
1455 GstVideoCodecFrame *frame;
1458 g_return_val_if_fail (state->caps != NULL, FALSE);
1460 if (encoder->priv->output_state_changed) {
1461 state->caps = gst_caps_make_writable (state->caps);
1464 gst_caps_set_simple (state->caps, "width", G_TYPE_INT, info->width,
1465 "height", G_TYPE_INT, info->height,
1466 "pixel-aspect-ratio", GST_TYPE_FRACTION,
1467 info->par_n, info->par_d, NULL);
1468 if (info->flags & GST_VIDEO_FLAG_VARIABLE_FPS && info->fps_n != 0) {
1469 /* variable fps with a max-framerate */
1470 gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION, 0, 1,
1471 "max-framerate", GST_TYPE_FRACTION, info->fps_n, info->fps_d, NULL);
1473 /* no variable fps or no max-framerate */
1474 gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION,
1475 info->fps_n, info->fps_d, NULL);
1477 if (state->codec_data)
1478 gst_caps_set_simple (state->caps, "codec_data", GST_TYPE_BUFFER,
1479 state->codec_data, NULL);
1480 encoder->priv->output_state_changed = FALSE;
1483 /* Push all pending pre-caps events of the oldest frame before
1485 frame = encoder->priv->frames ? encoder->priv->frames->data : NULL;
1486 if (frame || encoder->priv->current_frame_events) {
1490 events = &frame->events;
1492 events = &encoder->priv->current_frame_events;
1495 for (l = g_list_last (*events); l;) {
1496 GstEvent *event = GST_EVENT (l->data);
1499 if (GST_EVENT_TYPE (event) < GST_EVENT_CAPS) {
1500 gst_video_encoder_push_event (encoder, event);
1503 *events = g_list_delete_link (*events, tmp);
1510 prevcaps = gst_pad_get_current_caps (encoder->srcpad);
1511 if (!prevcaps || !gst_caps_is_equal (prevcaps, state->caps))
1512 ret = gst_pad_set_caps (encoder->srcpad, state->caps);
1516 gst_caps_unref (prevcaps);
1521 query = gst_query_new_allocation (state->caps, TRUE);
1522 if (!gst_pad_peer_query (encoder->srcpad, query)) {
1523 GST_DEBUG_OBJECT (encoder, "didn't get downstream ALLOCATION hints");
1526 g_assert (klass->decide_allocation != NULL);
1527 ret = klass->decide_allocation (encoder, query);
1529 GST_DEBUG_OBJECT (encoder, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, ret,
1533 goto no_decide_allocation;
1535 /* we got configuration from our peer or the decide_allocation method,
1537 if (gst_query_get_n_allocation_params (query) > 0) {
1538 gst_query_parse_nth_allocation_param (query, 0, &allocator, ¶ms);
1541 gst_allocation_params_init (¶ms);
1544 if (encoder->priv->allocator)
1545 gst_object_unref (encoder->priv->allocator);
1546 encoder->priv->allocator = allocator;
1547 encoder->priv->params = params;
1551 gst_query_unref (query);
1556 no_decide_allocation:
1558 GST_WARNING_OBJECT (encoder, "Subclass failed to decide allocation");
1564 * gst_video_encoder_negotiate:
1565 * @encoder: a #GstVideoEncoder
1567 * Negotiate with downstream elements to currently configured #GstVideoCodecState.
1569 * Returns: #TRUE if the negotiation succeeded, else #FALSE.
1572 gst_video_encoder_negotiate (GstVideoEncoder * encoder)
1574 GstVideoEncoderClass *klass;
1575 gboolean ret = TRUE;
1577 g_return_val_if_fail (GST_IS_VIDEO_ENCODER (encoder), FALSE);
1578 g_return_val_if_fail (encoder->priv->output_state, FALSE);
1580 klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1582 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1583 if (klass->negotiate)
1584 ret = klass->negotiate (encoder);
1585 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1591 * gst_video_encoder_allocate_output_buffer:
1592 * @encoder: a #GstVideoEncoder
1593 * @size: size of the buffer
1595 * Helper function that allocates a buffer to hold an encoded video frame
1596 * for @encoder's current #GstVideoCodecState.
1598 * Returns: (transfer full): allocated buffer
1601 gst_video_encoder_allocate_output_buffer (GstVideoEncoder * encoder, gsize size)
1605 g_return_val_if_fail (size > 0, NULL);
1607 GST_DEBUG ("alloc src buffer");
1609 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1610 if (G_UNLIKELY (encoder->priv->output_state_changed
1611 || (encoder->priv->output_state
1612 && gst_pad_check_reconfigure (encoder->srcpad)))) {
1613 if (!gst_video_encoder_negotiate (encoder)) {
1614 GST_DEBUG_OBJECT (encoder, "Failed to negotiate, fallback allocation");
1620 gst_buffer_new_allocate (encoder->priv->allocator, size,
1621 &encoder->priv->params);
1623 GST_INFO_OBJECT (encoder, "couldn't allocate output buffer");
1627 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1632 buffer = gst_buffer_new_allocate (NULL, size, NULL);
1634 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1640 * gst_video_encoder_allocate_output_frame:
1641 * @encoder: a #GstVideoEncoder
1642 * @frame: a #GstVideoCodecFrame
1643 * @size: size of the buffer
1645 * Helper function that allocates a buffer to hold an encoded video frame for @encoder's
1646 * current #GstVideoCodecState. Subclass should already have configured video
1647 * state and set src pad caps.
1649 * The buffer allocated here is owned by the frame and you should only
1650 * keep references to the frame, not the buffer.
1652 * Returns: %GST_FLOW_OK if an output buffer could be allocated
1655 gst_video_encoder_allocate_output_frame (GstVideoEncoder *
1656 encoder, GstVideoCodecFrame * frame, gsize size)
1658 g_return_val_if_fail (frame->output_buffer == NULL, GST_FLOW_ERROR);
1660 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1661 if (G_UNLIKELY (encoder->priv->output_state_changed
1662 || (encoder->priv->output_state
1663 && gst_pad_check_reconfigure (encoder->srcpad))))
1664 gst_video_encoder_negotiate (encoder);
1666 GST_LOG_OBJECT (encoder, "alloc buffer size %" G_GSIZE_FORMAT, size);
1668 frame->output_buffer =
1669 gst_buffer_new_allocate (encoder->priv->allocator, size,
1670 &encoder->priv->params);
1672 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1674 return frame->output_buffer ? GST_FLOW_OK : GST_FLOW_ERROR;
1678 gst_video_encoder_release_frame (GstVideoEncoder * enc,
1679 GstVideoCodecFrame * frame)
1683 /* unref once from the list */
1684 link = g_list_find (enc->priv->frames, frame);
1686 gst_video_codec_frame_unref (frame);
1687 enc->priv->frames = g_list_delete_link (enc->priv->frames, link);
1689 /* unref because this function takes ownership */
1690 gst_video_codec_frame_unref (frame);
1694 * gst_video_encoder_finish_frame:
1695 * @encoder: a #GstVideoEncoder
1696 * @frame: (transfer full): an encoded #GstVideoCodecFrame
1698 * @frame must have a valid encoded data buffer, whose metadata fields
1699 * are then appropriately set according to frame data or no buffer at
1700 * all if the frame should be dropped.
1701 * It is subsequently pushed downstream or provided to @pre_push.
1702 * In any case, the frame is considered finished and released.
1704 * After calling this function the output buffer of the frame is to be
1705 * considered read-only. This function will also change the metadata
1708 * Returns: a #GstFlowReturn resulting from sending data downstream
1711 gst_video_encoder_finish_frame (GstVideoEncoder * encoder,
1712 GstVideoCodecFrame * frame)
1714 GstVideoEncoderPrivate *priv = encoder->priv;
1715 GstFlowReturn ret = GST_FLOW_OK;
1716 GstVideoEncoderClass *encoder_class;
1718 gboolean send_headers = FALSE;
1719 gboolean discont = (frame->presentation_frame_number == 0);
1722 encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1724 GST_LOG_OBJECT (encoder,
1725 "finish frame fpn %d", frame->presentation_frame_number);
1727 GST_LOG_OBJECT (encoder, "frame PTS %" GST_TIME_FORMAT
1728 ", DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (frame->pts),
1729 GST_TIME_ARGS (frame->dts));
1731 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1733 if (G_UNLIKELY (priv->output_state_changed || (priv->output_state
1734 && gst_pad_check_reconfigure (encoder->srcpad)))) {
1735 if (!gst_video_encoder_negotiate (encoder)) {
1736 if (GST_PAD_IS_FLUSHING (encoder->srcpad))
1737 ret = GST_FLOW_FLUSHING;
1739 ret = GST_FLOW_NOT_NEGOTIATED;
1744 if (G_UNLIKELY (priv->output_state == NULL))
1745 goto no_output_state;
1747 /* Push all pending events that arrived before this frame */
1748 for (l = priv->frames; l; l = l->next) {
1749 GstVideoCodecFrame *tmp = l->data;
1754 for (k = g_list_last (tmp->events); k; k = k->prev)
1755 gst_video_encoder_push_event (encoder, k->data);
1756 g_list_free (tmp->events);
1764 if (priv->tags && priv->tags_changed) {
1765 gst_video_encoder_push_event (encoder,
1766 gst_event_new_tag (gst_tag_list_ref (priv->tags)));
1767 priv->tags_changed = FALSE;
1770 /* no buffer data means this frame is skipped/dropped */
1771 if (!frame->output_buffer) {
1772 GST_DEBUG_OBJECT (encoder, "skipping frame %" GST_TIME_FORMAT,
1773 GST_TIME_ARGS (frame->pts));
1777 if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame) && priv->force_key_unit) {
1778 GstClockTime stream_time, running_time;
1780 ForcedKeyUnitEvent *fevt = NULL;
1784 gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1787 GST_OBJECT_LOCK (encoder);
1788 for (l = priv->force_key_unit; l; l = l->next) {
1789 ForcedKeyUnitEvent *tmp = l->data;
1791 /* Skip non-pending keyunits */
1795 /* Simple case, keyunit ASAP */
1796 if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1801 /* Event for before this frame */
1802 if (tmp->running_time <= running_time) {
1809 priv->force_key_unit = g_list_remove (priv->force_key_unit, fevt);
1811 GST_OBJECT_UNLOCK (encoder);
1815 gst_segment_to_stream_time (&encoder->output_segment, GST_FORMAT_TIME,
1818 ev = gst_video_event_new_downstream_force_key_unit
1819 (frame->pts, stream_time, running_time,
1820 fevt->all_headers, fevt->count);
1822 gst_video_encoder_push_event (encoder, ev);
1824 if (fevt->all_headers)
1825 send_headers = TRUE;
1827 GST_DEBUG_OBJECT (encoder,
1828 "Forced key unit: running-time %" GST_TIME_FORMAT
1829 ", all_headers %d, count %u",
1830 GST_TIME_ARGS (running_time), fevt->all_headers, fevt->count);
1831 forced_key_unit_event_free (fevt);
1835 if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
1836 priv->distance_from_sync = 0;
1837 GST_BUFFER_FLAG_UNSET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1838 /* For keyframes, DTS = PTS */
1839 if (!GST_CLOCK_TIME_IS_VALID (frame->dts)) {
1840 frame->dts = frame->pts;
1841 } else if (GST_CLOCK_TIME_IS_VALID (frame->pts) && frame->pts != frame->dts) {
1842 GST_WARNING_OBJECT (encoder, "keyframe PTS != DTS");
1845 GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1848 /* DTS is expected monotone ascending,
1849 * so a good guess is the lowest unsent PTS (all being OK) */
1851 GstClockTime min_ts = GST_CLOCK_TIME_NONE;
1852 GstVideoCodecFrame *oframe = NULL;
1853 gboolean seen_none = FALSE;
1855 /* some maintenance regardless */
1856 for (l = priv->frames; l; l = l->next) {
1857 GstVideoCodecFrame *tmp = l->data;
1859 if (!GST_CLOCK_TIME_IS_VALID (tmp->abidata.ABI.ts)) {
1864 if (!GST_CLOCK_TIME_IS_VALID (min_ts) || tmp->abidata.ABI.ts < min_ts) {
1865 min_ts = tmp->abidata.ABI.ts;
1869 /* save a ts if needed */
1870 if (oframe && oframe != frame) {
1871 oframe->abidata.ABI.ts = frame->abidata.ABI.ts;
1874 /* and set if needed */
1875 if (!GST_CLOCK_TIME_IS_VALID (frame->dts) && !seen_none) {
1876 frame->dts = min_ts;
1877 GST_DEBUG_OBJECT (encoder,
1878 "no valid DTS, using oldest PTS %" GST_TIME_FORMAT,
1879 GST_TIME_ARGS (frame->pts));
1883 frame->distance_from_sync = priv->distance_from_sync;
1884 priv->distance_from_sync++;
1886 GST_BUFFER_PTS (frame->output_buffer) = frame->pts;
1887 GST_BUFFER_DTS (frame->output_buffer) = frame->dts;
1888 GST_BUFFER_DURATION (frame->output_buffer) = frame->duration;
1890 /* update rate estimate */
1891 priv->bytes += gst_buffer_get_size (frame->output_buffer);
1892 if (GST_CLOCK_TIME_IS_VALID (frame->duration)) {
1893 priv->time += frame->duration;
1895 /* better none than nothing valid */
1896 priv->time = GST_CLOCK_TIME_NONE;
1899 if (G_UNLIKELY (send_headers || priv->new_headers)) {
1900 GList *tmp, *copy = NULL;
1902 GST_DEBUG_OBJECT (encoder, "Sending headers");
1904 /* First make all buffers metadata-writable */
1905 for (tmp = priv->headers; tmp; tmp = tmp->next) {
1906 GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1908 copy = g_list_append (copy, gst_buffer_make_writable (tmpbuf));
1910 g_list_free (priv->headers);
1911 priv->headers = copy;
1913 for (tmp = priv->headers; tmp; tmp = tmp->next) {
1914 GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1916 priv->bytes += gst_buffer_get_size (tmpbuf);
1917 if (G_UNLIKELY (discont)) {
1918 GST_LOG_OBJECT (encoder, "marking discont");
1919 GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
1923 gst_pad_push (encoder->srcpad, gst_buffer_ref (tmpbuf));
1925 priv->new_headers = FALSE;
1928 if (G_UNLIKELY (discont)) {
1929 GST_LOG_OBJECT (encoder, "marking discont");
1930 GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DISCONT);
1933 if (encoder_class->pre_push)
1934 ret = encoder_class->pre_push (encoder, frame);
1936 /* Get an additional ref to the buffer, which is going to be pushed
1937 * downstream, the original ref is owned by the frame */
1938 buffer = gst_buffer_ref (frame->output_buffer);
1940 /* Release frame so the buffer is writable when we push it downstream
1941 * if possible, i.e. if the subclass does not hold additional references
1944 gst_video_encoder_release_frame (encoder, frame);
1947 if (ret == GST_FLOW_OK)
1948 ret = gst_pad_push (encoder->srcpad, buffer);
1953 gst_video_encoder_release_frame (encoder, frame);
1955 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1962 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1963 GST_ERROR_OBJECT (encoder, "Output state was not configured");
1964 return GST_FLOW_ERROR;
1969 * gst_video_encoder_get_output_state:
1970 * @encoder: a #GstVideoEncoder
1972 * Get the current #GstVideoCodecState
1974 * Returns: (transfer full): #GstVideoCodecState describing format of video data.
1976 GstVideoCodecState *
1977 gst_video_encoder_get_output_state (GstVideoEncoder * encoder)
1979 GstVideoCodecState *state;
1981 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1982 state = gst_video_codec_state_ref (encoder->priv->output_state);
1983 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1989 * gst_video_encoder_set_output_state:
1990 * @encoder: a #GstVideoEncoder
1991 * @caps: (transfer full): the #GstCaps to use for the output
1992 * @reference: (allow-none) (transfer none): An optional reference @GstVideoCodecState
1994 * Creates a new #GstVideoCodecState with the specified caps as the output state
1996 * Any previously set output state on @encoder will be replaced by the newly
1999 * The specified @caps should not contain any resolution, pixel-aspect-ratio,
2000 * framerate, codec-data, .... Those should be specified instead in the returned
2001 * #GstVideoCodecState.
2003 * If the subclass wishes to copy over existing fields (like pixel aspect ratio,
2004 * or framerate) from an existing #GstVideoCodecState, it can be provided as a
2007 * If the subclass wishes to override some fields from the output state (like
2008 * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
2010 * The new output state will only take effect (set on pads and buffers) starting
2011 * from the next call to #gst_video_encoder_finish_frame().
2013 * Returns: (transfer full): the newly configured output state.
2015 GstVideoCodecState *
2016 gst_video_encoder_set_output_state (GstVideoEncoder * encoder, GstCaps * caps,
2017 GstVideoCodecState * reference)
2019 GstVideoEncoderPrivate *priv = encoder->priv;
2020 GstVideoCodecState *state;
2022 g_return_val_if_fail (caps != NULL, NULL);
2024 state = _new_output_state (caps, reference);
2026 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2027 if (priv->output_state)
2028 gst_video_codec_state_unref (priv->output_state);
2029 priv->output_state = gst_video_codec_state_ref (state);
2031 priv->output_state_changed = TRUE;
2032 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2038 * gst_video_encoder_set_latency:
2039 * @encoder: a #GstVideoEncoder
2040 * @min_latency: minimum latency
2041 * @max_latency: maximum latency
2043 * Informs baseclass of encoding latency.
2046 gst_video_encoder_set_latency (GstVideoEncoder * encoder,
2047 GstClockTime min_latency, GstClockTime max_latency)
2049 g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
2050 g_return_if_fail (max_latency >= min_latency);
2052 GST_OBJECT_LOCK (encoder);
2053 encoder->priv->min_latency = min_latency;
2054 encoder->priv->max_latency = max_latency;
2055 GST_OBJECT_UNLOCK (encoder);
2057 gst_element_post_message (GST_ELEMENT_CAST (encoder),
2058 gst_message_new_latency (GST_OBJECT_CAST (encoder)));
2062 * gst_video_encoder_get_latency:
2063 * @encoder: a #GstVideoEncoder
2064 * @min_latency: (out) (allow-none): address of variable in which to store the
2065 * configured minimum latency, or %NULL
2066 * @max_latency: (out) (allow-none): address of variable in which to store the
2067 * configured maximum latency, or %NULL
2069 * Query the configured encoding latency. Results will be returned via
2070 * @min_latency and @max_latency.
2073 gst_video_encoder_get_latency (GstVideoEncoder * encoder,
2074 GstClockTime * min_latency, GstClockTime * max_latency)
2076 GST_OBJECT_LOCK (encoder);
2078 *min_latency = encoder->priv->min_latency;
2080 *max_latency = encoder->priv->max_latency;
2081 GST_OBJECT_UNLOCK (encoder);
2085 * gst_video_encoder_get_oldest_frame:
2086 * @encoder: a #GstVideoEncoder
2088 * Get the oldest unfinished pending #GstVideoCodecFrame
2090 * Returns: (transfer full): oldest unfinished pending #GstVideoCodecFrame
2092 GstVideoCodecFrame *
2093 gst_video_encoder_get_oldest_frame (GstVideoEncoder * encoder)
2095 GstVideoCodecFrame *frame = NULL;
2097 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2098 if (encoder->priv->frames)
2099 frame = gst_video_codec_frame_ref (encoder->priv->frames->data);
2100 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2102 return (GstVideoCodecFrame *) frame;
2106 * gst_video_encoder_get_frame:
2107 * @encoder: a #GstVideoEnccoder
2108 * @frame_number: system_frame_number of a frame
2110 * Get a pending unfinished #GstVideoCodecFrame
2112 * Returns: (transfer full): pending unfinished #GstVideoCodecFrame identified by @frame_number.
2114 GstVideoCodecFrame *
2115 gst_video_encoder_get_frame (GstVideoEncoder * encoder, int frame_number)
2118 GstVideoCodecFrame *frame = NULL;
2120 GST_DEBUG_OBJECT (encoder, "frame_number : %d", frame_number);
2122 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2123 for (g = encoder->priv->frames; g; g = g->next) {
2124 GstVideoCodecFrame *tmp = g->data;
2126 if (tmp->system_frame_number == frame_number) {
2127 frame = gst_video_codec_frame_ref (tmp);
2131 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2137 * gst_video_encoder_get_frames:
2138 * @encoder: a #GstVideoEncoder
2140 * Get all pending unfinished #GstVideoCodecFrame
2142 * Returns: (transfer full) (element-type GstVideoCodecFrame): pending unfinished #GstVideoCodecFrame.
2145 gst_video_encoder_get_frames (GstVideoEncoder * encoder)
2149 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2150 frames = g_list_copy (encoder->priv->frames);
2151 g_list_foreach (frames, (GFunc) gst_video_codec_frame_ref, NULL);
2152 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2158 * gst_video_encoder_merge_tags:
2159 * @encoder: a #GstVideoEncoder
2160 * @tags: a #GstTagList to merge
2161 * @mode: the #GstTagMergeMode to use
2163 * Adds tags to so-called pending tags, which will be processed
2164 * before pushing out data downstream.
2166 * Note that this is provided for convenience, and the subclass is
2167 * not required to use this and can still do tag handling on its own.
2172 gst_video_encoder_merge_tags (GstVideoEncoder * encoder,
2173 const GstTagList * tags, GstTagMergeMode mode)
2177 g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
2178 g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
2180 GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2182 GST_DEBUG_OBJECT (encoder, "merging tags %" GST_PTR_FORMAT, tags);
2183 otags = encoder->priv->tags;
2184 encoder->priv->tags = gst_tag_list_merge (encoder->priv->tags, tags, mode);
2186 gst_tag_list_unref (otags);
2187 encoder->priv->tags_changed = TRUE;
2188 GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2192 * gst_video_encoder_get_allocator:
2193 * @encoder: a #GstVideoEncoder
2194 * @allocator: (out) (allow-none) (transfer full): the #GstAllocator
2196 * @params: (out) (allow-none) (transfer full): the
2197 * #GstAllocatorParams of @allocator
2199 * Lets #GstVideoEncoder sub-classes to know the memory @allocator
2200 * used by the base class and its @params.
2202 * Unref the @allocator after use it.
2205 gst_video_encoder_get_allocator (GstVideoEncoder * encoder,
2206 GstAllocator ** allocator, GstAllocationParams * params)
2208 g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
2211 *allocator = encoder->priv->allocator ?
2212 gst_object_ref (encoder->priv->allocator) : NULL;
2215 *params = encoder->priv->params;