videoencoder: Make sure to return TRUE if the same caps are set again
[platform/upstream/gstreamer.git] / gst-libs / gst / video / gstvideoencoder.c
1 /* GStreamer
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>
8  *
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.
13  *
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.
18  *
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.
23  */
24
25 /**
26  * SECTION:gstvideoencoder
27  * @short_description: Base class for video encoders
28  * @see_also:
29  *
30  * This base class is for video encoders turning raw video into
31  * encoded video data.
32  *
33  * GstVideoEncoder and subclass should cooperate as follows.
34  * <orderedlist>
35  * <listitem>
36  *   <itemizedlist><title>Configuration</title>
37  *   <listitem><para>
38  *     Initially, GstVideoEncoder calls @start when the encoder element
39  *     is activated, which allows subclass to perform any global setup.
40  *   </para></listitem>
41  *   <listitem><para>
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.
48  *   </para></listitem>
49  *   <listitem><para>
50  *     GstVideoEncoder calls @stop at end of all processing.
51  *   </para></listitem>
52  *   </itemizedlist>
53  * </listitem>
54  * <listitem>
55  *   <itemizedlist>
56  *   <title>Data processing</title>
57  *     <listitem><para>
58  *       Base class collects input data and metadata into a frame and hands
59  *       this to subclass' @handle_frame.
60  *     </para></listitem>
61  *     <listitem><para>
62  *       If codec processing results in encoded data, subclass should call
63  *       @gst_video_encoder_finish_frame to have encoded data pushed
64  *       downstream.
65  *     </para></listitem>
66  *     <listitem><para>
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.
70  *     </para></listitem>
71  *     <listitem><para>
72  *       GstVideoEncoderClass will handle both srcpad and sinkpad events.
73  *       Sink events will be passed to subclass if @event callback has been
74  *       provided.
75  *     </para></listitem>
76  *   </itemizedlist>
77  * </listitem>
78  * <listitem>
79  *   <itemizedlist><title>Shutdown phase</title>
80  *   <listitem><para>
81  *     GstVideoEncoder class calls @stop to inform the subclass that data
82  *     parsing will be stopped.
83  *   </para></listitem>
84  *   </itemizedlist>
85  * </listitem>
86  * </orderedlist>
87  *
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.
92  *
93  * Things that subclass need to take care of:
94  * <itemizedlist>
95  *   <listitem><para>Provide pad templates</para></listitem>
96  *   <listitem><para>
97  *      Provide source pad caps before pushing the first buffer
98  *   </para></listitem>
99  *   <listitem><para>
100  *      Accept data in @handle_frame and provide encoded results to
101  *      @gst_video_encoder_finish_frame.
102  *   </para></listitem>
103  * </itemizedlist>
104  *
105  */
106
107 #ifdef HAVE_CONFIG_H
108 #include "config.h"
109 #endif
110
111 /* TODO
112  *
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
115  */
116
117 #include <gst/video/video.h>
118 #include "gstvideoencoder.h"
119 #include "gstvideoutils.h"
120
121 #include <gst/video/gstvideometa.h>
122 #include <gst/video/gstvideopool.h>
123
124 #include <string.h>
125
126 GST_DEBUG_CATEGORY (videoencoder_debug);
127 #define GST_CAT_DEFAULT videoencoder_debug
128
129 #define GST_VIDEO_ENCODER_GET_PRIVATE(obj)  \
130     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_VIDEO_ENCODER, \
131         GstVideoEncoderPrivate))
132
133 struct _GstVideoEncoderPrivate
134 {
135   guint64 presentation_frame_number;
136   int distance_from_sync;
137
138   /* FIXME : (and introduce a context ?) */
139   gboolean drained;
140   gboolean at_eos;
141   gboolean do_caps;
142
143   gint64 min_latency;
144   gint64 max_latency;
145
146   GList *current_frame_events;
147
148   GList *headers;
149   gboolean new_headers;         /* Whether new headers were just set */
150
151   GList *force_key_unit;        /* List of pending forced keyunits */
152
153   guint32 system_frame_number;
154
155   GList *frames;                /* Protected with OBJECT_LOCK */
156   GstVideoCodecState *input_state;
157   GstVideoCodecState *output_state;
158   gboolean output_state_changed;
159
160   gint64 bytes;
161   gint64 time;
162
163   GstAllocator *allocator;
164   GstAllocationParams params;
165
166   GstTagList *tags;
167   gboolean tags_changed;
168 };
169
170 typedef struct _ForcedKeyUnitEvent ForcedKeyUnitEvent;
171 struct _ForcedKeyUnitEvent
172 {
173   GstClockTime running_time;
174   gboolean pending;             /* TRUE if this was requested already */
175   gboolean all_headers;
176   guint count;
177 };
178
179 static void
180 forced_key_unit_event_free (ForcedKeyUnitEvent * evt)
181 {
182   g_slice_free (ForcedKeyUnitEvent, evt);
183 }
184
185 static ForcedKeyUnitEvent *
186 forced_key_unit_event_new (GstClockTime running_time, gboolean all_headers,
187     guint count)
188 {
189   ForcedKeyUnitEvent *evt = g_slice_new0 (ForcedKeyUnitEvent);
190
191   evt->running_time = running_time;
192   evt->all_headers = all_headers;
193   evt->count = count;
194
195   return evt;
196 }
197
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);
202
203 static void gst_video_encoder_finalize (GObject * object);
204
205 static gboolean gst_video_encoder_setcaps (GstVideoEncoder * enc,
206     GstCaps * caps);
207 static GstCaps *gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder,
208     GstCaps * filter);
209 static gboolean gst_video_encoder_src_event (GstPad * pad, GstObject * parent,
210     GstEvent * event);
211 static gboolean gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
212     GstEvent * event);
213 static GstFlowReturn gst_video_encoder_chain (GstPad * pad, GstObject * parent,
214     GstBuffer * buf);
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,
218     GstQuery * query);
219 static gboolean gst_video_encoder_src_query (GstPad * pad, GstObject * parent,
220     GstQuery * query);
221 static GstVideoCodecFrame *gst_video_encoder_new_frame (GstVideoEncoder *
222     encoder, GstBuffer * buf, GstClockTime pts, GstClockTime dts,
223     GstClockTime duration);
224
225 static gboolean gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
226     GstEvent * event);
227 static gboolean gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
228     GstEvent * event);
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);
234
235 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
236  * method to get to the padtemplates */
237 GType
238 gst_video_encoder_get_type (void)
239 {
240   static volatile gsize type = 0;
241
242   if (g_once_init_enter (&type)) {
243     GType _type;
244     static const GTypeInfo info = {
245       sizeof (GstVideoEncoderClass),
246       NULL,
247       NULL,
248       (GClassInitFunc) gst_video_encoder_class_init,
249       NULL,
250       NULL,
251       sizeof (GstVideoEncoder),
252       0,
253       (GInstanceInitFunc) gst_video_encoder_init,
254     };
255     const GInterfaceInfo preset_interface_info = {
256       NULL,                     /* interface_init */
257       NULL,                     /* interface_finalize */
258       NULL                      /* interface_data */
259     };
260
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);
266   }
267   return type;
268 }
269
270 static void
271 gst_video_encoder_class_init (GstVideoEncoderClass * klass)
272 {
273   GObjectClass *gobject_class;
274   GstElementClass *gstelement_class;
275
276   gobject_class = G_OBJECT_CLASS (klass);
277   gstelement_class = GST_ELEMENT_CLASS (klass);
278
279   GST_DEBUG_CATEGORY_INIT (videoencoder_debug, "videoencoder", 0,
280       "Base Video Encoder");
281
282   parent_class = g_type_class_peek_parent (klass);
283
284   g_type_class_add_private (klass, sizeof (GstVideoEncoderPrivate));
285
286   gobject_class->finalize = gst_video_encoder_finalize;
287
288   gstelement_class->change_state =
289       GST_DEBUG_FUNCPTR (gst_video_encoder_change_state);
290
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;
296 }
297
298 static gboolean
299 gst_video_encoder_reset (GstVideoEncoder * encoder, gboolean hard)
300 {
301   GstVideoEncoderPrivate *priv = encoder->priv;
302   gboolean ret = TRUE;
303
304   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
305
306   priv->presentation_frame_number = 0;
307   priv->distance_from_sync = 0;
308
309   g_list_foreach (priv->force_key_unit, (GFunc) forced_key_unit_event_free,
310       NULL);
311   g_list_free (priv->force_key_unit);
312   priv->force_key_unit = NULL;
313
314   priv->drained = TRUE;
315
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;
319
320   g_list_foreach (priv->frames, (GFunc) gst_video_codec_frame_unref, NULL);
321   g_list_free (priv->frames);
322   priv->frames = NULL;
323
324   priv->bytes = 0;
325   priv->time = 0;
326
327   if (hard) {
328     gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
329     gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
330
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;
337
338     if (priv->tags)
339       gst_tag_list_unref (priv->tags);
340     priv->tags = NULL;
341     priv->tags_changed = FALSE;
342
343     priv->min_latency = 0;
344     priv->max_latency = 0;
345
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;
350   }
351
352   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
353
354   return ret;
355 }
356
357 /* Always call reset() in one way or another after this */
358 static gboolean
359 gst_video_encoder_flush (GstVideoEncoder * encoder)
360 {
361   GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
362   gboolean ret = TRUE;
363
364   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
365   if (klass->flush)
366     ret = klass->flush (encoder);
367
368   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
369   return ret;
370 }
371
372 static void
373 gst_video_encoder_init (GstVideoEncoder * encoder, GstVideoEncoderClass * klass)
374 {
375   GstVideoEncoderPrivate *priv;
376   GstPadTemplate *pad_template;
377   GstPad *pad;
378
379   GST_DEBUG_OBJECT (encoder, "gst_video_encoder_init");
380
381   priv = encoder->priv = GST_VIDEO_ENCODER_GET_PRIVATE (encoder);
382
383   pad_template =
384       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
385   g_return_if_fail (pad_template != NULL);
386
387   encoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
388
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);
395
396   pad_template =
397       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
398   g_return_if_fail (pad_template != NULL);
399
400   encoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
401
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);
407
408   gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
409   gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
410
411   g_rec_mutex_init (&encoder->stream_lock);
412
413   priv->at_eos = FALSE;
414   priv->headers = NULL;
415   priv->new_headers = FALSE;
416
417   gst_video_encoder_reset (encoder, TRUE);
418 }
419
420 static gboolean
421 gst_video_encoded_video_convert (gint64 bytes, gint64 time,
422     GstFormat src_format, gint64 src_value, GstFormat * dest_format,
423     gint64 * dest_value)
424 {
425   gboolean res = FALSE;
426
427   g_return_val_if_fail (dest_format != NULL, FALSE);
428   g_return_val_if_fail (dest_value != NULL, FALSE);
429
430   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
431           src_value == -1)) {
432     if (dest_value)
433       *dest_value = src_value;
434     return TRUE;
435   }
436
437   if (bytes <= 0 || time <= 0) {
438     GST_DEBUG ("not enough metadata yet to convert");
439     goto exit;
440   }
441
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);
447           res = TRUE;
448           break;
449         default:
450           res = FALSE;
451       }
452       break;
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);
457           res = TRUE;
458           break;
459         default:
460           res = FALSE;
461       }
462       break;
463     default:
464       GST_DEBUG ("unhandled conversion from %d to %d", src_format,
465           *dest_format);
466       res = FALSE;
467   }
468
469 exit:
470   return res;
471 }
472
473 /**
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
477  *
478  * Set the codec headers to be sent downstream whenever requested.
479  */
480 void
481 gst_video_encoder_set_headers (GstVideoEncoder * video_encoder, GList * headers)
482 {
483   GST_VIDEO_ENCODER_STREAM_LOCK (video_encoder);
484
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,
488         NULL);
489     g_list_free (video_encoder->priv->headers);
490   }
491   video_encoder->priv->headers = headers;
492   video_encoder->priv->new_headers = TRUE;
493
494   GST_VIDEO_ENCODER_STREAM_UNLOCK (video_encoder);
495 }
496
497 static GstVideoCodecState *
498 _new_output_state (GstCaps * caps, GstVideoCodecState * reference)
499 {
500   GstVideoCodecState *state;
501
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);
506
507   state->caps = caps;
508
509   if (reference) {
510     GstVideoInfo *tgt, *ref;
511
512     tgt = &state->info;
513     ref = &reference->info;
514
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;
526   }
527
528   return state;
529 }
530
531 static GstVideoCodecState *
532 _new_input_state (GstCaps * caps)
533 {
534   GstVideoCodecState *state;
535
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)))
540     goto parse_fail;
541   state->caps = gst_caps_ref (caps);
542
543   return state;
544
545 parse_fail:
546   {
547     g_slice_free (GstVideoCodecState, state);
548     return NULL;
549   }
550 }
551
552 static gboolean
553 gst_video_encoder_setcaps (GstVideoEncoder * encoder, GstCaps * caps)
554 {
555   GstVideoEncoderClass *encoder_class;
556   GstVideoCodecState *state;
557   gboolean ret;
558
559   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
560
561   /* subclass should do something here ... */
562   g_return_val_if_fail (encoder_class->set_format != NULL, FALSE);
563
564   GST_DEBUG_OBJECT (encoder, "setcaps %" GST_PTR_FORMAT, caps);
565
566   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
567
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;
574   }
575
576   state = _new_input_state (caps);
577   if (G_UNLIKELY (!state))
578     goto parse_fail;
579
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;
585   }
586
587   if (encoder_class->reset) {
588     GST_FIXME_OBJECT (encoder, "GstVideoEncoder::reset() is deprecated");
589     ret = encoder_class->reset (encoder, TRUE);
590   }
591
592   /* and subclass should be ready to configure format at any time around */
593   ret = encoder_class->set_format (encoder, state);
594   if (ret) {
595     if (encoder->priv->input_state)
596       gst_video_codec_state_unref (encoder->priv->input_state);
597     encoder->priv->input_state = state;
598   } else {
599     gst_video_codec_state_unref (state);
600   }
601
602   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
603
604   if (!ret)
605     GST_WARNING_OBJECT (encoder, "rejected caps %" GST_PTR_FORMAT, caps);
606
607   return ret;
608
609 caps_not_changed:
610   {
611     GST_DEBUG_OBJECT (encoder, "Caps did not change - ignore");
612     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
613     return TRUE;
614   }
615
616   /* ERRORS */
617 parse_fail:
618   {
619     GST_WARNING_OBJECT (encoder, "Failed to parse caps");
620     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
621     return FALSE;
622   }
623 }
624
625 /**
626  * gst_video_encoder_proxy_getcaps:
627  * @enc: a #GstVideoEncoder
628  * @caps: initial caps
629  * @filter: filter caps
630  *
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).
634  *
635  * Returns: a #GstCaps owned by caller
636  */
637 GstCaps *
638 gst_video_encoder_proxy_getcaps (GstVideoEncoder * encoder, GstCaps * caps,
639     GstCaps * filter)
640 {
641   GstCaps *templ_caps;
642   GstCaps *allowed;
643   GstCaps *fcaps, *filter_caps;
644   gint i, j;
645
646   /* Allow downstream to specify width/height/framerate/PAR constraints
647    * and forward them upstream for video converters to handle
648    */
649   templ_caps =
650       caps ? gst_caps_ref (caps) :
651       gst_pad_get_pad_template_caps (encoder->sinkpad);
652   allowed = gst_pad_get_allowed_caps (encoder->srcpad);
653
654   if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
655     fcaps = templ_caps;
656     goto done;
657   }
658
659   GST_LOG_OBJECT (encoder, "template caps %" GST_PTR_FORMAT, templ_caps);
660   GST_LOG_OBJECT (encoder, "allowed caps %" GST_PTR_FORMAT, allowed);
661
662   filter_caps = gst_caps_new_empty ();
663
664   for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
665     GQuark q_name =
666         gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
667
668     for (j = 0; j < gst_caps_get_size (allowed); j++) {
669       const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
670       const GValue *val;
671       GstStructure *s;
672
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);
682
683       filter_caps = gst_caps_merge_structure (filter_caps, s);
684     }
685   }
686
687   fcaps = gst_caps_intersect (filter_caps, templ_caps);
688   gst_caps_unref (filter_caps);
689   gst_caps_unref (templ_caps);
690
691   if (filter) {
692     GST_LOG_OBJECT (encoder, "intersecting with %" GST_PTR_FORMAT, filter);
693     filter_caps = gst_caps_intersect (fcaps, filter);
694     gst_caps_unref (fcaps);
695     fcaps = filter_caps;
696   }
697
698 done:
699   gst_caps_replace (&allowed, NULL);
700
701   GST_LOG_OBJECT (encoder, "proxy caps %" GST_PTR_FORMAT, fcaps);
702
703   return fcaps;
704 }
705
706 static GstCaps *
707 gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder, GstCaps * filter)
708 {
709   GstVideoEncoderClass *klass;
710   GstCaps *caps;
711
712   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
713
714   if (klass->getcaps)
715     caps = klass->getcaps (encoder, filter);
716   else
717     caps = gst_video_encoder_proxy_getcaps (encoder, NULL, filter);
718
719   GST_LOG_OBJECT (encoder, "Returning caps %" GST_PTR_FORMAT, caps);
720
721   return caps;
722 }
723
724 static gboolean
725 gst_video_encoder_decide_allocation_default (GstVideoEncoder * encoder,
726     GstQuery * query)
727 {
728   GstAllocator *allocator = NULL;
729   GstAllocationParams params;
730   gboolean update_allocator;
731
732   /* we got configuration from our peer or the decide_allocation method,
733    * parse them */
734   if (gst_query_get_n_allocation_params (query) > 0) {
735     /* try the allocator */
736     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
737     update_allocator = TRUE;
738   } else {
739     allocator = NULL;
740     gst_allocation_params_init (&params);
741     update_allocator = FALSE;
742   }
743
744   if (update_allocator)
745     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
746   else
747     gst_query_add_allocation_param (query, allocator, &params);
748   if (allocator)
749     gst_object_unref (allocator);
750
751   return TRUE;
752 }
753
754 static gboolean
755 gst_video_encoder_propose_allocation_default (GstVideoEncoder * encoder,
756     GstQuery * query)
757 {
758   GstCaps *caps;
759   GstVideoInfo info;
760   GstBufferPool *pool;
761   guint size;
762
763   gst_query_parse_allocation (query, &caps, NULL);
764
765   if (caps == NULL)
766     return FALSE;
767
768   if (!gst_video_info_from_caps (&info, caps))
769     return FALSE;
770
771   size = GST_VIDEO_INFO_SIZE (&info);
772
773   if (gst_query_get_n_allocation_pools (query) == 0) {
774     GstStructure *structure;
775     GstAllocator *allocator = NULL;
776     GstAllocationParams params = { 0, 15, 0, 0 };
777
778     if (gst_query_get_n_allocation_params (query) > 0)
779       gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
780     else
781       gst_query_add_allocation_param (query, allocator, &params);
782
783     pool = gst_video_buffer_pool_new ();
784
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, &params);
788
789     if (allocator)
790       gst_object_unref (allocator);
791
792     if (!gst_buffer_pool_set_config (pool, structure))
793       goto config_failed;
794
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);
798   }
799
800   return TRUE;
801
802   /* ERRORS */
803 config_failed:
804   {
805     GST_ERROR_OBJECT (encoder, "failed to set config");
806     gst_object_unref (pool);
807     return FALSE;
808   }
809 }
810
811 static gboolean
812 gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
813     GstQuery * query)
814 {
815   GstVideoEncoder *encoder;
816   gboolean res = FALSE;
817
818   encoder = GST_VIDEO_ENCODER (parent);
819
820   switch (GST_QUERY_TYPE (query)) {
821     case GST_QUERY_CAPS:
822     {
823       GstCaps *filter, *caps;
824
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);
829       res = TRUE;
830       break;
831     }
832     case GST_QUERY_ALLOCATION:
833     {
834       GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
835
836       if (klass->propose_allocation)
837         res = klass->propose_allocation (encoder, query);
838       break;
839     }
840     default:
841       res = gst_pad_query_default (pad, parent, query);
842       break;
843   }
844   return res;
845 }
846
847 static void
848 gst_video_encoder_finalize (GObject * object)
849 {
850   GstVideoEncoder *encoder;
851
852   GST_DEBUG_OBJECT (object, "finalize");
853
854   encoder = GST_VIDEO_ENCODER (object);
855   g_rec_mutex_clear (&encoder->stream_lock);
856
857   if (encoder->priv->allocator) {
858     gst_object_unref (encoder->priv->allocator);
859     encoder->priv->allocator = NULL;
860   }
861
862   G_OBJECT_CLASS (parent_class)->finalize (object);
863 }
864
865 static gboolean
866 gst_video_encoder_push_event (GstVideoEncoder * encoder, GstEvent * event)
867 {
868   switch (GST_EVENT_TYPE (event)) {
869     case GST_EVENT_SEGMENT:
870     {
871       GstSegment segment;
872
873       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
874
875       gst_event_copy_segment (event, &segment);
876
877       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
878
879       if (segment.format != GST_FORMAT_TIME) {
880         GST_DEBUG_OBJECT (encoder, "received non TIME segment");
881         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
882         break;
883       }
884
885       encoder->output_segment = segment;
886       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
887       break;
888     }
889     default:
890       break;
891   }
892
893   return gst_pad_push_event (encoder->srcpad, event);
894 }
895
896 static gboolean
897 gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
898     GstEvent * event)
899 {
900   GstVideoEncoderClass *encoder_class;
901   gboolean ret = FALSE;
902
903   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
904
905   switch (GST_EVENT_TYPE (event)) {
906     case GST_EVENT_CAPS:
907     {
908       GstCaps *caps;
909
910       gst_event_parse_caps (event, &caps);
911       ret = TRUE;
912       encoder->priv->do_caps = TRUE;
913       gst_event_unref (event);
914       event = NULL;
915       break;
916     }
917     case GST_EVENT_EOS:
918     {
919       GstFlowReturn flow_ret;
920
921       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
922       encoder->priv->at_eos = TRUE;
923
924       if (encoder_class->finish) {
925         flow_ret = encoder_class->finish (encoder);
926       } else {
927         flow_ret = GST_FLOW_OK;
928       }
929
930       ret = (flow_ret == GST_FLOW_OK);
931       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
932       break;
933     }
934     case GST_EVENT_SEGMENT:
935     {
936       GstSegment segment;
937
938       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
939
940       gst_event_copy_segment (event, &segment);
941
942       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
943
944       if (segment.format != GST_FORMAT_TIME) {
945         GST_DEBUG_OBJECT (encoder, "received non TIME newsegment");
946         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
947         break;
948       }
949
950       encoder->priv->at_eos = FALSE;
951
952       encoder->input_segment = segment;
953       ret = TRUE;
954       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
955       break;
956     }
957     case GST_EVENT_CUSTOM_DOWNSTREAM:
958     {
959       if (gst_video_event_is_force_key_unit (event)) {
960         GstClockTime running_time;
961         gboolean all_headers;
962         guint count;
963
964         if (gst_video_event_parse_downstream_force_key_unit (event,
965                 NULL, NULL, &running_time, &all_headers, &count)) {
966           ForcedKeyUnitEvent *fevt;
967
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);
973
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);
978         }
979         gst_event_unref (event);
980         event = NULL;
981         ret = TRUE;
982       }
983       break;
984     }
985     case GST_EVENT_TAG:
986     {
987       GstTagList *tags;
988
989       gst_event_parse_tag (event, &tags);
990
991       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
992         tags = gst_tag_list_copy (tags);
993
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);
1006
1007         gst_video_encoder_merge_tags (encoder, tags, GST_TAG_MERGE_REPLACE);
1008         gst_tag_list_unref (tags);
1009         gst_event_unref (event);
1010         event = NULL;
1011         ret = TRUE;
1012       }
1013       break;
1014     }
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);
1022       break;
1023     }
1024     default:
1025       break;
1026   }
1027
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
1034    *
1035    * For FLUSH_STOP this is required because it is expected
1036    * to be forwarded immediately and no buffers are queued anyway.
1037    */
1038   if (event) {
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);
1043     } else {
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);
1048       ret = TRUE;
1049     }
1050   }
1051
1052   return ret;
1053 }
1054
1055 static gboolean
1056 gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
1057     GstEvent * event)
1058 {
1059   GstVideoEncoder *enc;
1060   GstVideoEncoderClass *klass;
1061   gboolean ret = TRUE;
1062
1063   enc = GST_VIDEO_ENCODER (parent);
1064   klass = GST_VIDEO_ENCODER_GET_CLASS (enc);
1065
1066   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1067       GST_EVENT_TYPE_NAME (event));
1068
1069   if (klass->sink_event)
1070     ret = klass->sink_event (enc, event);
1071
1072   return ret;
1073 }
1074
1075 static gboolean
1076 gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
1077     GstEvent * event)
1078 {
1079   gboolean ret = FALSE;
1080
1081   switch (GST_EVENT_TYPE (event)) {
1082     case GST_EVENT_CUSTOM_UPSTREAM:
1083     {
1084       if (gst_video_event_is_force_key_unit (event)) {
1085         GstClockTime running_time;
1086         gboolean all_headers;
1087         guint count;
1088
1089         if (gst_video_event_parse_upstream_force_key_unit (event,
1090                 &running_time, &all_headers, &count)) {
1091           ForcedKeyUnitEvent *fevt;
1092
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);
1098
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);
1103         }
1104         gst_event_unref (event);
1105         event = NULL;
1106         ret = TRUE;
1107       }
1108       break;
1109     }
1110     default:
1111       break;
1112   }
1113
1114   if (event)
1115     ret =
1116         gst_pad_event_default (encoder->srcpad, GST_OBJECT_CAST (encoder),
1117         event);
1118
1119   return ret;
1120 }
1121
1122 static gboolean
1123 gst_video_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1124 {
1125   GstVideoEncoder *encoder;
1126   GstVideoEncoderClass *klass;
1127   gboolean ret = FALSE;
1128
1129   encoder = GST_VIDEO_ENCODER (parent);
1130   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1131
1132   GST_LOG_OBJECT (encoder, "handling event: %" GST_PTR_FORMAT, event);
1133
1134   if (klass->src_event)
1135     ret = klass->src_event (encoder, event);
1136
1137   return ret;
1138 }
1139
1140 static gboolean
1141 gst_video_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1142 {
1143   GstVideoEncoderPrivate *priv;
1144   GstVideoEncoder *enc;
1145   gboolean res;
1146
1147   enc = GST_VIDEO_ENCODER (parent);
1148   priv = enc->priv;
1149
1150   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1151
1152   switch (GST_QUERY_TYPE (query)) {
1153     case GST_QUERY_CONVERT:
1154     {
1155       GstFormat src_fmt, dest_fmt;
1156       gint64 src_val, dest_val;
1157
1158       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1159       res =
1160           gst_video_encoded_video_convert (priv->bytes, priv->time, src_fmt,
1161           src_val, &dest_fmt, &dest_val);
1162       if (!res)
1163         goto error;
1164       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1165       break;
1166     }
1167     case GST_QUERY_LATENCY:
1168     {
1169       gboolean live;
1170       GstClockTime min_latency, max_latency;
1171
1172       res = gst_pad_peer_query (enc->sinkpad, query);
1173       if (res) {
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));
1178
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;
1185         }
1186         GST_OBJECT_UNLOCK (enc);
1187
1188         gst_query_set_latency (query, live, min_latency, max_latency);
1189       }
1190     }
1191       break;
1192     default:
1193       res = gst_pad_query_default (pad, parent, query);
1194   }
1195   return res;
1196
1197 error:
1198   GST_DEBUG_OBJECT (enc, "query failed");
1199   return res;
1200 }
1201
1202 static GstVideoCodecFrame *
1203 gst_video_encoder_new_frame (GstVideoEncoder * encoder, GstBuffer * buf,
1204     GstClockTime pts, GstClockTime dts, GstClockTime duration)
1205 {
1206   GstVideoEncoderPrivate *priv = encoder->priv;
1207   GstVideoCodecFrame *frame;
1208
1209   frame = g_slice_new0 (GstVideoCodecFrame);
1210
1211   frame->ref_count = 1;
1212
1213   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1214   frame->system_frame_number = priv->system_frame_number;
1215   priv->system_frame_number++;
1216
1217   frame->presentation_frame_number = priv->presentation_frame_number;
1218   priv->presentation_frame_number++;
1219   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1220
1221   frame->events = priv->current_frame_events;
1222   priv->current_frame_events = NULL;
1223   frame->input_buffer = buf;
1224   frame->pts = pts;
1225   frame->dts = dts;
1226   frame->duration = duration;
1227   frame->abidata.ABI.ts = pts;
1228
1229   return frame;
1230 }
1231
1232
1233 static GstFlowReturn
1234 gst_video_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1235 {
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;
1243
1244   encoder = GST_VIDEO_ENCODER (parent);
1245   priv = encoder->priv;
1246   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1247
1248   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1249
1250   if (G_UNLIKELY (encoder->priv->do_caps)) {
1251     GstCaps *caps = gst_pad_get_current_caps (encoder->sinkpad);
1252     if (!caps)
1253       goto not_negotiated;
1254     if (!gst_video_encoder_setcaps (encoder, caps)) {
1255       gst_caps_unref (caps);
1256       goto not_negotiated;
1257     }
1258     gst_caps_unref (caps);
1259     encoder->priv->do_caps = FALSE;
1260   }
1261
1262   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1263
1264   pts = GST_BUFFER_PTS (buf);
1265   duration = GST_BUFFER_DURATION (buf);
1266
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));
1272
1273   if (priv->at_eos) {
1274     ret = GST_FLOW_EOS;
1275     goto done;
1276   }
1277
1278   start = pts;
1279   if (GST_CLOCK_TIME_IS_VALID (duration))
1280     stop = start + duration;
1281   else
1282     stop = GST_CLOCK_TIME_NONE;
1283
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);
1289     goto done;
1290   }
1291
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);
1296
1297   GST_OBJECT_LOCK (encoder);
1298   if (priv->force_key_unit) {
1299     ForcedKeyUnitEvent *fevt = NULL;
1300     GstClockTime running_time;
1301     GList *l;
1302
1303     running_time =
1304         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1305         cstart);
1306
1307     for (l = priv->force_key_unit; l; l = l->next) {
1308       ForcedKeyUnitEvent *tmp = l->data;
1309
1310       /* Skip pending keyunits */
1311       if (tmp->pending)
1312         continue;
1313
1314       /* Simple case, keyunit ASAP */
1315       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1316         fevt = tmp;
1317         break;
1318       }
1319
1320       /* Event for before this frame */
1321       if (tmp->running_time <= running_time) {
1322         fevt = tmp;
1323         break;
1324       }
1325     }
1326
1327     if (fevt) {
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;
1335     }
1336   }
1337   GST_OBJECT_UNLOCK (encoder);
1338
1339   gst_video_codec_frame_ref (frame);
1340   priv->frames = g_list_append (priv->frames, frame);
1341
1342   /* new data, more finish needed */
1343   priv->drained = FALSE;
1344
1345   GST_LOG_OBJECT (encoder, "passing frame pfn %d to subclass",
1346       frame->presentation_frame_number);
1347
1348   ret = klass->handle_frame (encoder, frame);
1349
1350 done:
1351   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1352
1353   return ret;
1354
1355   /* ERRORS */
1356 not_negotiated:
1357   {
1358     GST_ELEMENT_ERROR (encoder, CORE, NEGOTIATION, (NULL),
1359         ("encoder not initialized"));
1360     gst_buffer_unref (buf);
1361     return GST_FLOW_NOT_NEGOTIATED;
1362   }
1363 }
1364
1365 static GstStateChangeReturn
1366 gst_video_encoder_change_state (GstElement * element, GstStateChange transition)
1367 {
1368   GstVideoEncoder *encoder;
1369   GstVideoEncoderClass *encoder_class;
1370   GstStateChangeReturn ret;
1371
1372   encoder = GST_VIDEO_ENCODER (element);
1373   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (element);
1374
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))
1379         goto open_failed;
1380       break;
1381     case GST_STATE_CHANGE_READY_TO_PAUSED:
1382       /* Initialize device/library if needed */
1383       if (encoder_class->start && !encoder_class->start (encoder))
1384         goto start_failed;
1385       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1386       gst_video_encoder_reset (encoder, TRUE);
1387       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1388       break;
1389     default:
1390       break;
1391   }
1392
1393   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1394
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))
1401         goto stop_failed;
1402       break;
1403     case GST_STATE_CHANGE_READY_TO_NULL:
1404       /* close device/library if needed */
1405       if (encoder_class->close && !encoder_class->close (encoder))
1406         goto close_failed;
1407       break;
1408     default:
1409       break;
1410   }
1411
1412   return ret;
1413
1414   /* Errors */
1415
1416 open_failed:
1417   {
1418     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1419         ("Failed to open encoder"));
1420     return GST_STATE_CHANGE_FAILURE;
1421   }
1422
1423 start_failed:
1424   {
1425     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1426         ("Failed to start encoder"));
1427     return GST_STATE_CHANGE_FAILURE;
1428   }
1429
1430 stop_failed:
1431   {
1432     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1433         ("Failed to stop encoder"));
1434     return GST_STATE_CHANGE_FAILURE;
1435   }
1436
1437 close_failed:
1438   {
1439     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1440         ("Failed to close encoder"));
1441     return GST_STATE_CHANGE_FAILURE;
1442   }
1443 }
1444
1445 static gboolean
1446 gst_video_encoder_negotiate_default (GstVideoEncoder * encoder)
1447 {
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;
1456   GstCaps *prevcaps;
1457
1458   g_return_val_if_fail (state->caps != NULL, FALSE);
1459
1460   if (encoder->priv->output_state_changed) {
1461     state->caps = gst_caps_make_writable (state->caps);
1462
1463     /* Fill 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);
1472     } else {
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);
1476     }
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;
1481   }
1482
1483   /* Push all pending pre-caps events of the oldest frame before
1484    * setting caps */
1485   frame = encoder->priv->frames ? encoder->priv->frames->data : NULL;
1486   if (frame || encoder->priv->current_frame_events) {
1487     GList **events, *l;
1488
1489     if (frame) {
1490       events = &frame->events;
1491     } else {
1492       events = &encoder->priv->current_frame_events;
1493     }
1494
1495     for (l = g_list_last (*events); l;) {
1496       GstEvent *event = GST_EVENT (l->data);
1497       GList *tmp;
1498
1499       if (GST_EVENT_TYPE (event) < GST_EVENT_CAPS) {
1500         gst_video_encoder_push_event (encoder, event);
1501         tmp = l;
1502         l = l->prev;
1503         *events = g_list_delete_link (*events, tmp);
1504       } else {
1505         l = l->prev;
1506       }
1507     }
1508   }
1509
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);
1513   else
1514     ret = TRUE;
1515   if (prevcaps)
1516     gst_caps_unref (prevcaps);
1517
1518   if (!ret)
1519     goto done;
1520
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");
1524   }
1525
1526   g_assert (klass->decide_allocation != NULL);
1527   ret = klass->decide_allocation (encoder, query);
1528
1529   GST_DEBUG_OBJECT (encoder, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, ret,
1530       query);
1531
1532   if (!ret)
1533     goto no_decide_allocation;
1534
1535   /* we got configuration from our peer or the decide_allocation method,
1536    * parse them */
1537   if (gst_query_get_n_allocation_params (query) > 0) {
1538     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
1539   } else {
1540     allocator = NULL;
1541     gst_allocation_params_init (&params);
1542   }
1543
1544   if (encoder->priv->allocator)
1545     gst_object_unref (encoder->priv->allocator);
1546   encoder->priv->allocator = allocator;
1547   encoder->priv->params = params;
1548
1549 done:
1550   if (query)
1551     gst_query_unref (query);
1552
1553   return ret;
1554
1555   /* Errors */
1556 no_decide_allocation:
1557   {
1558     GST_WARNING_OBJECT (encoder, "Subclass failed to decide allocation");
1559     goto done;
1560   }
1561 }
1562
1563 /**
1564  * gst_video_encoder_negotiate:
1565  * @encoder: a #GstVideoEncoder
1566  *
1567  * Negotiate with downstream elements to currently configured #GstVideoCodecState.
1568  *
1569  * Returns: #TRUE if the negotiation succeeded, else #FALSE.
1570  */
1571 gboolean
1572 gst_video_encoder_negotiate (GstVideoEncoder * encoder)
1573 {
1574   GstVideoEncoderClass *klass;
1575   gboolean ret = TRUE;
1576
1577   g_return_val_if_fail (GST_IS_VIDEO_ENCODER (encoder), FALSE);
1578   g_return_val_if_fail (encoder->priv->output_state, FALSE);
1579
1580   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1581
1582   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1583   if (klass->negotiate)
1584     ret = klass->negotiate (encoder);
1585   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1586
1587   return ret;
1588 }
1589
1590 /**
1591  * gst_video_encoder_allocate_output_buffer:
1592  * @encoder: a #GstVideoEncoder
1593  * @size: size of the buffer
1594  *
1595  * Helper function that allocates a buffer to hold an encoded video frame
1596  * for @encoder's current #GstVideoCodecState.
1597  *
1598  * Returns: (transfer full): allocated buffer
1599  */
1600 GstBuffer *
1601 gst_video_encoder_allocate_output_buffer (GstVideoEncoder * encoder, gsize size)
1602 {
1603   GstBuffer *buffer;
1604
1605   g_return_val_if_fail (size > 0, NULL);
1606
1607   GST_DEBUG ("alloc src buffer");
1608
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");
1615       goto fallback;
1616     }
1617   }
1618
1619   buffer =
1620       gst_buffer_new_allocate (encoder->priv->allocator, size,
1621       &encoder->priv->params);
1622   if (!buffer) {
1623     GST_INFO_OBJECT (encoder, "couldn't allocate output buffer");
1624     goto fallback;
1625   }
1626
1627   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1628
1629   return buffer;
1630
1631 fallback:
1632   buffer = gst_buffer_new_allocate (NULL, size, NULL);
1633
1634   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1635
1636   return buffer;
1637 }
1638
1639 /**
1640  * gst_video_encoder_allocate_output_frame:
1641  * @encoder: a #GstVideoEncoder
1642  * @frame: a #GstVideoCodecFrame
1643  * @size: size of the buffer
1644  *
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.
1648  *
1649  * The buffer allocated here is owned by the frame and you should only
1650  * keep references to the frame, not the buffer.
1651  *
1652  * Returns: %GST_FLOW_OK if an output buffer could be allocated
1653  */
1654 GstFlowReturn
1655 gst_video_encoder_allocate_output_frame (GstVideoEncoder *
1656     encoder, GstVideoCodecFrame * frame, gsize size)
1657 {
1658   g_return_val_if_fail (frame->output_buffer == NULL, GST_FLOW_ERROR);
1659
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);
1665
1666   GST_LOG_OBJECT (encoder, "alloc buffer size %" G_GSIZE_FORMAT, size);
1667
1668   frame->output_buffer =
1669       gst_buffer_new_allocate (encoder->priv->allocator, size,
1670       &encoder->priv->params);
1671
1672   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1673
1674   return frame->output_buffer ? GST_FLOW_OK : GST_FLOW_ERROR;
1675 }
1676
1677 static void
1678 gst_video_encoder_release_frame (GstVideoEncoder * enc,
1679     GstVideoCodecFrame * frame)
1680 {
1681   GList *link;
1682
1683   /* unref once from the list */
1684   link = g_list_find (enc->priv->frames, frame);
1685   if (link) {
1686     gst_video_codec_frame_unref (frame);
1687     enc->priv->frames = g_list_delete_link (enc->priv->frames, link);
1688   }
1689   /* unref because this function takes ownership */
1690   gst_video_codec_frame_unref (frame);
1691 }
1692
1693 /**
1694  * gst_video_encoder_finish_frame:
1695  * @encoder: a #GstVideoEncoder
1696  * @frame: (transfer full): an encoded #GstVideoCodecFrame 
1697  *
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.
1703  *
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
1706  * of the buffer.
1707  *
1708  * Returns: a #GstFlowReturn resulting from sending data downstream
1709  */
1710 GstFlowReturn
1711 gst_video_encoder_finish_frame (GstVideoEncoder * encoder,
1712     GstVideoCodecFrame * frame)
1713 {
1714   GstVideoEncoderPrivate *priv = encoder->priv;
1715   GstFlowReturn ret = GST_FLOW_OK;
1716   GstVideoEncoderClass *encoder_class;
1717   GList *l;
1718   gboolean send_headers = FALSE;
1719   gboolean discont = (frame->presentation_frame_number == 0);
1720   GstBuffer *buffer;
1721
1722   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1723
1724   GST_LOG_OBJECT (encoder,
1725       "finish frame fpn %d", frame->presentation_frame_number);
1726
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));
1730
1731   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1732
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;
1738       else
1739         ret = GST_FLOW_NOT_NEGOTIATED;
1740       goto done;
1741     }
1742   }
1743
1744   if (G_UNLIKELY (priv->output_state == NULL))
1745     goto no_output_state;
1746
1747   /* Push all pending events that arrived before this frame */
1748   for (l = priv->frames; l; l = l->next) {
1749     GstVideoCodecFrame *tmp = l->data;
1750
1751     if (tmp->events) {
1752       GList *k;
1753
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);
1757       tmp->events = NULL;
1758     }
1759
1760     if (tmp == frame)
1761       break;
1762   }
1763
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;
1768   }
1769
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));
1774     goto done;
1775   }
1776
1777   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame) && priv->force_key_unit) {
1778     GstClockTime stream_time, running_time;
1779     GstEvent *ev;
1780     ForcedKeyUnitEvent *fevt = NULL;
1781     GList *l;
1782
1783     running_time =
1784         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1785         frame->pts);
1786
1787     GST_OBJECT_LOCK (encoder);
1788     for (l = priv->force_key_unit; l; l = l->next) {
1789       ForcedKeyUnitEvent *tmp = l->data;
1790
1791       /* Skip non-pending keyunits */
1792       if (!tmp->pending)
1793         continue;
1794
1795       /* Simple case, keyunit ASAP */
1796       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1797         fevt = tmp;
1798         break;
1799       }
1800
1801       /* Event for before this frame */
1802       if (tmp->running_time <= running_time) {
1803         fevt = tmp;
1804         break;
1805       }
1806     }
1807
1808     if (fevt) {
1809       priv->force_key_unit = g_list_remove (priv->force_key_unit, fevt);
1810     }
1811     GST_OBJECT_UNLOCK (encoder);
1812
1813     if (fevt) {
1814       stream_time =
1815           gst_segment_to_stream_time (&encoder->output_segment, GST_FORMAT_TIME,
1816           frame->pts);
1817
1818       ev = gst_video_event_new_downstream_force_key_unit
1819           (frame->pts, stream_time, running_time,
1820           fevt->all_headers, fevt->count);
1821
1822       gst_video_encoder_push_event (encoder, ev);
1823
1824       if (fevt->all_headers)
1825         send_headers = TRUE;
1826
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);
1832     }
1833   }
1834
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");
1843     }
1844   } else {
1845     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1846   }
1847
1848   /* DTS is expected monotone ascending,
1849    * so a good guess is the lowest unsent PTS (all being OK) */
1850   {
1851     GstClockTime min_ts = GST_CLOCK_TIME_NONE;
1852     GstVideoCodecFrame *oframe = NULL;
1853     gboolean seen_none = FALSE;
1854
1855     /* some maintenance regardless */
1856     for (l = priv->frames; l; l = l->next) {
1857       GstVideoCodecFrame *tmp = l->data;
1858
1859       if (!GST_CLOCK_TIME_IS_VALID (tmp->abidata.ABI.ts)) {
1860         seen_none = TRUE;
1861         continue;
1862       }
1863
1864       if (!GST_CLOCK_TIME_IS_VALID (min_ts) || tmp->abidata.ABI.ts < min_ts) {
1865         min_ts = tmp->abidata.ABI.ts;
1866         oframe = tmp;
1867       }
1868     }
1869     /* save a ts if needed */
1870     if (oframe && oframe != frame) {
1871       oframe->abidata.ABI.ts = frame->abidata.ABI.ts;
1872     }
1873
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));
1880     }
1881   }
1882
1883   frame->distance_from_sync = priv->distance_from_sync;
1884   priv->distance_from_sync++;
1885
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;
1889
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;
1894   } else {
1895     /* better none than nothing valid */
1896     priv->time = GST_CLOCK_TIME_NONE;
1897   }
1898
1899   if (G_UNLIKELY (send_headers || priv->new_headers)) {
1900     GList *tmp, *copy = NULL;
1901
1902     GST_DEBUG_OBJECT (encoder, "Sending headers");
1903
1904     /* First make all buffers metadata-writable */
1905     for (tmp = priv->headers; tmp; tmp = tmp->next) {
1906       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1907
1908       copy = g_list_append (copy, gst_buffer_make_writable (tmpbuf));
1909     }
1910     g_list_free (priv->headers);
1911     priv->headers = copy;
1912
1913     for (tmp = priv->headers; tmp; tmp = tmp->next) {
1914       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1915
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);
1920         discont = FALSE;
1921       }
1922
1923       gst_pad_push (encoder->srcpad, gst_buffer_ref (tmpbuf));
1924     }
1925     priv->new_headers = FALSE;
1926   }
1927
1928   if (G_UNLIKELY (discont)) {
1929     GST_LOG_OBJECT (encoder, "marking discont");
1930     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DISCONT);
1931   }
1932
1933   if (encoder_class->pre_push)
1934     ret = encoder_class->pre_push (encoder, frame);
1935
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);
1939
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
1942    * to the frame
1943    */
1944   gst_video_encoder_release_frame (encoder, frame);
1945   frame = NULL;
1946
1947   if (ret == GST_FLOW_OK)
1948     ret = gst_pad_push (encoder->srcpad, buffer);
1949
1950 done:
1951   /* handed out */
1952   if (frame)
1953     gst_video_encoder_release_frame (encoder, frame);
1954
1955   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1956
1957   return ret;
1958
1959   /* ERRORS */
1960 no_output_state:
1961   {
1962     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1963     GST_ERROR_OBJECT (encoder, "Output state was not configured");
1964     return GST_FLOW_ERROR;
1965   }
1966 }
1967
1968 /**
1969  * gst_video_encoder_get_output_state:
1970  * @encoder: a #GstVideoEncoder
1971  *
1972  * Get the current #GstVideoCodecState
1973  *
1974  * Returns: (transfer full): #GstVideoCodecState describing format of video data.
1975  */
1976 GstVideoCodecState *
1977 gst_video_encoder_get_output_state (GstVideoEncoder * encoder)
1978 {
1979   GstVideoCodecState *state;
1980
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);
1984
1985   return state;
1986 }
1987
1988 /**
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
1993  *
1994  * Creates a new #GstVideoCodecState with the specified caps as the output state
1995  * for the encoder.
1996  * Any previously set output state on @encoder will be replaced by the newly
1997  * created one.
1998  *
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.
2002  *
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
2005  * @reference.
2006  *
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.
2009  *
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().
2012  *
2013  * Returns: (transfer full): the newly configured output state.
2014  */
2015 GstVideoCodecState *
2016 gst_video_encoder_set_output_state (GstVideoEncoder * encoder, GstCaps * caps,
2017     GstVideoCodecState * reference)
2018 {
2019   GstVideoEncoderPrivate *priv = encoder->priv;
2020   GstVideoCodecState *state;
2021
2022   g_return_val_if_fail (caps != NULL, NULL);
2023
2024   state = _new_output_state (caps, reference);
2025
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);
2030
2031   priv->output_state_changed = TRUE;
2032   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2033
2034   return state;
2035 }
2036
2037 /**
2038  * gst_video_encoder_set_latency:
2039  * @encoder: a #GstVideoEncoder
2040  * @min_latency: minimum latency
2041  * @max_latency: maximum latency
2042  *
2043  * Informs baseclass of encoding latency.
2044  */
2045 void
2046 gst_video_encoder_set_latency (GstVideoEncoder * encoder,
2047     GstClockTime min_latency, GstClockTime max_latency)
2048 {
2049   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
2050   g_return_if_fail (max_latency >= min_latency);
2051
2052   GST_OBJECT_LOCK (encoder);
2053   encoder->priv->min_latency = min_latency;
2054   encoder->priv->max_latency = max_latency;
2055   GST_OBJECT_UNLOCK (encoder);
2056
2057   gst_element_post_message (GST_ELEMENT_CAST (encoder),
2058       gst_message_new_latency (GST_OBJECT_CAST (encoder)));
2059 }
2060
2061 /**
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
2068  *
2069  * Query the configured encoding latency. Results will be returned via
2070  * @min_latency and @max_latency.
2071  */
2072 void
2073 gst_video_encoder_get_latency (GstVideoEncoder * encoder,
2074     GstClockTime * min_latency, GstClockTime * max_latency)
2075 {
2076   GST_OBJECT_LOCK (encoder);
2077   if (min_latency)
2078     *min_latency = encoder->priv->min_latency;
2079   if (max_latency)
2080     *max_latency = encoder->priv->max_latency;
2081   GST_OBJECT_UNLOCK (encoder);
2082 }
2083
2084 /**
2085  * gst_video_encoder_get_oldest_frame:
2086  * @encoder: a #GstVideoEncoder
2087  *
2088  * Get the oldest unfinished pending #GstVideoCodecFrame
2089  *
2090  * Returns: (transfer full): oldest unfinished pending #GstVideoCodecFrame
2091  */
2092 GstVideoCodecFrame *
2093 gst_video_encoder_get_oldest_frame (GstVideoEncoder * encoder)
2094 {
2095   GstVideoCodecFrame *frame = NULL;
2096
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);
2101
2102   return (GstVideoCodecFrame *) frame;
2103 }
2104
2105 /**
2106  * gst_video_encoder_get_frame:
2107  * @encoder: a #GstVideoEnccoder
2108  * @frame_number: system_frame_number of a frame
2109  *
2110  * Get a pending unfinished #GstVideoCodecFrame
2111  * 
2112  * Returns: (transfer full): pending unfinished #GstVideoCodecFrame identified by @frame_number.
2113  */
2114 GstVideoCodecFrame *
2115 gst_video_encoder_get_frame (GstVideoEncoder * encoder, int frame_number)
2116 {
2117   GList *g;
2118   GstVideoCodecFrame *frame = NULL;
2119
2120   GST_DEBUG_OBJECT (encoder, "frame_number : %d", frame_number);
2121
2122   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2123   for (g = encoder->priv->frames; g; g = g->next) {
2124     GstVideoCodecFrame *tmp = g->data;
2125
2126     if (tmp->system_frame_number == frame_number) {
2127       frame = gst_video_codec_frame_ref (tmp);
2128       break;
2129     }
2130   }
2131   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2132
2133   return frame;
2134 }
2135
2136 /**
2137  * gst_video_encoder_get_frames:
2138  * @encoder: a #GstVideoEncoder
2139  *
2140  * Get all pending unfinished #GstVideoCodecFrame
2141  * 
2142  * Returns: (transfer full) (element-type GstVideoCodecFrame): pending unfinished #GstVideoCodecFrame.
2143  */
2144 GList *
2145 gst_video_encoder_get_frames (GstVideoEncoder * encoder)
2146 {
2147   GList *frames;
2148
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);
2153
2154   return frames;
2155 }
2156
2157 /**
2158  * gst_video_encoder_merge_tags:
2159  * @encoder: a #GstVideoEncoder
2160  * @tags: a #GstTagList to merge
2161  * @mode: the #GstTagMergeMode to use
2162  *
2163  * Adds tags to so-called pending tags, which will be processed
2164  * before pushing out data downstream.
2165  *
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.
2168  *
2169  * MT safe.
2170  */
2171 void
2172 gst_video_encoder_merge_tags (GstVideoEncoder * encoder,
2173     const GstTagList * tags, GstTagMergeMode mode)
2174 {
2175   GstTagList *otags;
2176
2177   g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
2178   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
2179
2180   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2181   if (tags)
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);
2185   if (otags)
2186     gst_tag_list_unref (otags);
2187   encoder->priv->tags_changed = TRUE;
2188   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2189 }
2190
2191 /**
2192  * gst_video_encoder_get_allocator:
2193  * @encoder: a #GstVideoEncoder
2194  * @allocator: (out) (allow-none) (transfer full): the #GstAllocator
2195  * used
2196  * @params: (out) (allow-none) (transfer full): the
2197  * #GstAllocatorParams of @allocator
2198  *
2199  * Lets #GstVideoEncoder sub-classes to know the memory @allocator
2200  * used by the base class and its @params.
2201  *
2202  * Unref the @allocator after use it.
2203  */
2204 void
2205 gst_video_encoder_get_allocator (GstVideoEncoder * encoder,
2206     GstAllocator ** allocator, GstAllocationParams * params)
2207 {
2208   g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
2209
2210   if (allocator)
2211     *allocator = encoder->priv->allocator ?
2212         gst_object_ref (encoder->priv->allocator) : NULL;
2213
2214   if (params)
2215     *params = encoder->priv->params;
2216 }