videoencoder: Require to chain up to the parent's sink event functions
[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., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, 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  * * Change _set_output_format() to steal the reference of the provided caps
114  * * Calculate actual latency based on input/output timestamp/frame_number
115  *   and if it exceeds the recorded one, save it and emit a GST_MESSAGE_LATENCY
116  */
117
118 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
119  * with newer GLib versions (>= 2.31.0) */
120 #define GLIB_DISABLE_DEPRECATION_WARNINGS
121
122 #include "gstvideoencoder.h"
123 #include "gstvideoutils.h"
124
125 #include <string.h>
126
127 GST_DEBUG_CATEGORY (videoencoder_debug);
128 #define GST_CAT_DEFAULT videoencoder_debug
129
130 #define GST_VIDEO_ENCODER_GET_PRIVATE(obj)  \
131     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_VIDEO_ENCODER, \
132         GstVideoEncoderPrivate))
133
134 struct _GstVideoEncoderPrivate
135 {
136   guint64 presentation_frame_number;
137   int distance_from_sync;
138
139   /* FIXME : (and introduce a context ?) */
140   gboolean drained;
141   gboolean at_eos;
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   guint64 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
164 typedef struct _ForcedKeyUnitEvent ForcedKeyUnitEvent;
165 struct _ForcedKeyUnitEvent
166 {
167   GstClockTime running_time;
168   gboolean pending;             /* TRUE if this was requested already */
169   gboolean all_headers;
170   guint count;
171 };
172
173 static void
174 forced_key_unit_event_free (ForcedKeyUnitEvent * evt)
175 {
176   g_slice_free (ForcedKeyUnitEvent, evt);
177 }
178
179 static ForcedKeyUnitEvent *
180 forced_key_unit_event_new (GstClockTime running_time, gboolean all_headers,
181     guint count)
182 {
183   ForcedKeyUnitEvent *evt = g_slice_new0 (ForcedKeyUnitEvent);
184
185   evt->running_time = running_time;
186   evt->all_headers = all_headers;
187   evt->count = count;
188
189   return evt;
190 }
191
192 static GstElementClass *parent_class = NULL;
193 static void gst_video_encoder_class_init (GstVideoEncoderClass * klass);
194 static void gst_video_encoder_init (GstVideoEncoder * enc,
195     GstVideoEncoderClass * klass);
196
197 static void gst_video_encoder_finalize (GObject * object);
198
199 static gboolean gst_video_encoder_setcaps (GstVideoEncoder * enc,
200     GstCaps * caps);
201 static GstCaps *gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder,
202     GstCaps * filter);
203 static gboolean gst_video_encoder_src_event (GstPad * pad, GstObject * parent,
204     GstEvent * event);
205 static gboolean gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
206     GstEvent * event);
207 static GstFlowReturn gst_video_encoder_chain (GstPad * pad, GstObject * parent,
208     GstBuffer * buf);
209 static GstStateChangeReturn gst_video_encoder_change_state (GstElement *
210     element, GstStateChange transition);
211 static gboolean gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
212     GstQuery * query);
213 static gboolean gst_video_encoder_src_query (GstPad * pad, GstObject * parent,
214     GstQuery * query);
215 static GstVideoCodecFrame *gst_video_encoder_new_frame (GstVideoEncoder *
216     encoder, GstBuffer * buf, GstClockTime timestamp, GstClockTime duration);
217
218 static gboolean gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
219     GstEvent * event);
220 static gboolean gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
221     GstEvent * event);
222
223 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
224  * method to get to the padtemplates */
225 GType
226 gst_video_encoder_get_type (void)
227 {
228   static volatile gsize type = 0;
229
230   if (g_once_init_enter (&type)) {
231     GType _type;
232     static const GTypeInfo info = {
233       sizeof (GstVideoEncoderClass),
234       NULL,
235       NULL,
236       (GClassInitFunc) gst_video_encoder_class_init,
237       NULL,
238       NULL,
239       sizeof (GstVideoEncoder),
240       0,
241       (GInstanceInitFunc) gst_video_encoder_init,
242     };
243     const GInterfaceInfo preset_interface_info = {
244       NULL,                     /* interface_init */
245       NULL,                     /* interface_finalize */
246       NULL                      /* interface_data */
247     };
248
249     _type = g_type_register_static (GST_TYPE_ELEMENT,
250         "GstVideoEncoder", &info, G_TYPE_FLAG_ABSTRACT);
251     g_type_add_interface_static (_type, GST_TYPE_PRESET,
252         &preset_interface_info);
253     g_once_init_leave (&type, _type);
254   }
255   return type;
256 }
257
258 static void
259 gst_video_encoder_class_init (GstVideoEncoderClass * klass)
260 {
261   GObjectClass *gobject_class;
262   GstElementClass *gstelement_class;
263
264   gobject_class = G_OBJECT_CLASS (klass);
265   gstelement_class = GST_ELEMENT_CLASS (klass);
266
267   GST_DEBUG_CATEGORY_INIT (videoencoder_debug, "videoencoder", 0,
268       "Base Video Encoder");
269
270   parent_class = g_type_class_peek_parent (klass);
271
272   g_type_class_add_private (klass, sizeof (GstVideoEncoderPrivate));
273
274   gobject_class->finalize = gst_video_encoder_finalize;
275
276   gstelement_class->change_state =
277       GST_DEBUG_FUNCPTR (gst_video_encoder_change_state);
278
279   klass->sink_event = gst_video_encoder_sink_event_default;
280   klass->src_event = gst_video_encoder_src_event_default;
281 }
282
283 static void
284 gst_video_encoder_reset (GstVideoEncoder * encoder)
285 {
286   GstVideoEncoderPrivate *priv = encoder->priv;
287   GList *g;
288
289   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
290
291   priv->presentation_frame_number = 0;
292   priv->distance_from_sync = 0;
293
294   g_list_foreach (priv->force_key_unit, (GFunc) forced_key_unit_event_free,
295       NULL);
296   g_list_free (priv->force_key_unit);
297   priv->force_key_unit = NULL;
298
299   priv->drained = TRUE;
300   priv->min_latency = 0;
301   priv->max_latency = 0;
302
303   g_list_foreach (priv->headers, (GFunc) gst_event_unref, NULL);
304   g_list_free (priv->headers);
305   priv->headers = NULL;
306   priv->new_headers = FALSE;
307
308   g_list_foreach (priv->current_frame_events, (GFunc) gst_event_unref, NULL);
309   g_list_free (priv->current_frame_events);
310   priv->current_frame_events = NULL;
311
312   for (g = priv->frames; g; g = g->next) {
313     gst_video_codec_frame_unref ((GstVideoCodecFrame *) g->data);
314   }
315   g_list_free (priv->frames);
316   priv->frames = NULL;
317
318   priv->bytes = 0;
319   priv->time = 0;
320
321   if (priv->input_state)
322     gst_video_codec_state_unref (priv->input_state);
323   priv->input_state = NULL;
324   if (priv->output_state)
325     gst_video_codec_state_unref (priv->output_state);
326   priv->output_state = NULL;
327
328   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
329 }
330
331 static void
332 gst_video_encoder_init (GstVideoEncoder * encoder, GstVideoEncoderClass * klass)
333 {
334   GstVideoEncoderPrivate *priv;
335   GstPadTemplate *pad_template;
336   GstPad *pad;
337
338   GST_DEBUG_OBJECT (encoder, "gst_video_encoder_init");
339
340   priv = encoder->priv = GST_VIDEO_ENCODER_GET_PRIVATE (encoder);
341
342   pad_template =
343       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
344   g_return_if_fail (pad_template != NULL);
345
346   encoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
347
348   gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_video_encoder_chain));
349   gst_pad_set_event_function (pad,
350       GST_DEBUG_FUNCPTR (gst_video_encoder_sink_event));
351   gst_pad_set_query_function (pad,
352       GST_DEBUG_FUNCPTR (gst_video_encoder_sink_query));
353   gst_element_add_pad (GST_ELEMENT (encoder), encoder->sinkpad);
354
355   pad_template =
356       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
357   g_return_if_fail (pad_template != NULL);
358
359   encoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
360
361   gst_pad_set_query_function (pad,
362       GST_DEBUG_FUNCPTR (gst_video_encoder_src_query));
363   gst_pad_set_event_function (pad,
364       GST_DEBUG_FUNCPTR (gst_video_encoder_src_event));
365   gst_element_add_pad (GST_ELEMENT (encoder), encoder->srcpad);
366
367   gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
368   gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
369
370   g_rec_mutex_init (&encoder->stream_lock);
371
372   priv->at_eos = FALSE;
373   priv->headers = NULL;
374   priv->new_headers = FALSE;
375
376   gst_video_encoder_reset (encoder);
377 }
378
379 static gboolean
380 gst_video_encoded_video_convert (gint64 bytes, gint64 time,
381     GstFormat src_format, gint64 src_value, GstFormat * dest_format,
382     gint64 * dest_value)
383 {
384   gboolean res = FALSE;
385
386   g_return_val_if_fail (dest_format != NULL, FALSE);
387   g_return_val_if_fail (dest_value != NULL, FALSE);
388
389   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
390           src_value == -1)) {
391     if (dest_value)
392       *dest_value = src_value;
393     return TRUE;
394   }
395
396   if (bytes <= 0 || time <= 0) {
397     GST_DEBUG ("not enough metadata yet to convert");
398     goto exit;
399   }
400
401   switch (src_format) {
402     case GST_FORMAT_BYTES:
403       switch (*dest_format) {
404         case GST_FORMAT_TIME:
405           *dest_value = gst_util_uint64_scale (src_value, time, bytes);
406           res = TRUE;
407           break;
408         default:
409           res = FALSE;
410       }
411       break;
412     case GST_FORMAT_TIME:
413       switch (*dest_format) {
414         case GST_FORMAT_BYTES:
415           *dest_value = gst_util_uint64_scale (src_value, bytes, time);
416           res = TRUE;
417           break;
418         default:
419           res = FALSE;
420       }
421       break;
422     default:
423       GST_DEBUG ("unhandled conversion from %d to %d", src_format,
424           *dest_format);
425       res = FALSE;
426   }
427
428 exit:
429   return res;
430 }
431
432 /**
433  * gst_video_encoder_set_headers:
434  * @encoder: a #GstVideoEncoder
435  * @headers: (transfer full) (element-type GstBuffer): a list of #GstBuffer containing the codec header
436  *
437  * Set the codec headers to be sent downstream whenever requested.
438  *
439  * Since: 0.10.36
440  */
441 void
442 gst_video_encoder_set_headers (GstVideoEncoder * video_encoder, GList * headers)
443 {
444   GST_VIDEO_ENCODER_STREAM_LOCK (video_encoder);
445
446   GST_DEBUG_OBJECT (video_encoder, "new headers %p", headers);
447   if (video_encoder->priv->headers) {
448     g_list_foreach (video_encoder->priv->headers, (GFunc) gst_buffer_unref,
449         NULL);
450     g_list_free (video_encoder->priv->headers);
451   }
452   video_encoder->priv->headers = headers;
453   video_encoder->priv->new_headers = TRUE;
454
455   GST_VIDEO_ENCODER_STREAM_UNLOCK (video_encoder);
456 }
457
458 static gboolean
459 gst_video_encoder_drain (GstVideoEncoder * enc)
460 {
461   GstVideoEncoderPrivate *priv;
462   GstVideoEncoderClass *enc_class;
463   gboolean ret = TRUE;
464
465   enc_class = GST_VIDEO_ENCODER_GET_CLASS (enc);
466   priv = enc->priv;
467
468   GST_DEBUG_OBJECT (enc, "draining");
469
470   if (priv->drained) {
471     GST_DEBUG_OBJECT (enc, "already drained");
472     return TRUE;
473   }
474
475   if (enc_class->reset) {
476     GST_DEBUG_OBJECT (enc, "requesting subclass to finish");
477     ret = enc_class->reset (enc, TRUE);
478   }
479   /* everything should be away now */
480   if (priv->frames) {
481     /* not fatal/impossible though if subclass/enc eats stuff */
482     g_list_foreach (priv->frames, (GFunc) gst_video_codec_frame_unref, NULL);
483     g_list_free (priv->frames);
484     priv->frames = NULL;
485   }
486
487   return ret;
488 }
489
490 static GstVideoCodecState *
491 _new_output_state (GstCaps * caps, GstVideoCodecState * reference)
492 {
493   GstVideoCodecState *state;
494
495   state = g_slice_new0 (GstVideoCodecState);
496   state->ref_count = 1;
497   gst_video_info_init (&state->info);
498   gst_video_info_set_format (&state->info, GST_VIDEO_FORMAT_ENCODED, 0, 0);
499
500   state->caps = caps;
501
502   if (reference) {
503     GstVideoInfo *tgt, *ref;
504
505     tgt = &state->info;
506     ref = &reference->info;
507
508     /* Copy over extra fields from reference state */
509     tgt->interlace_mode = ref->interlace_mode;
510     tgt->flags = ref->flags;
511     tgt->width = ref->width;
512     tgt->height = ref->height;
513     tgt->chroma_site = ref->chroma_site;
514     tgt->colorimetry = ref->colorimetry;
515     tgt->par_n = ref->par_n;
516     tgt->par_d = ref->par_d;
517     tgt->fps_n = ref->fps_n;
518     tgt->fps_d = ref->fps_d;
519   }
520
521   return state;
522 }
523
524 static GstVideoCodecState *
525 _new_input_state (GstCaps * caps)
526 {
527   GstVideoCodecState *state;
528
529   state = g_slice_new0 (GstVideoCodecState);
530   state->ref_count = 1;
531   gst_video_info_init (&state->info);
532   if (G_UNLIKELY (!gst_video_info_from_caps (&state->info, caps)))
533     goto parse_fail;
534   state->caps = gst_caps_ref (caps);
535
536   return state;
537
538 parse_fail:
539   {
540     g_slice_free (GstVideoCodecState, state);
541     return NULL;
542   }
543 }
544
545 static gboolean
546 gst_video_encoder_setcaps (GstVideoEncoder * encoder, GstCaps * caps)
547 {
548   GstVideoEncoderClass *encoder_class;
549   GstVideoCodecState *state;
550   gboolean ret;
551   gboolean samecaps = FALSE;
552
553   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
554
555   /* subclass should do something here ... */
556   g_return_val_if_fail (encoder_class->set_format != NULL, FALSE);
557
558   GST_DEBUG_OBJECT (encoder, "setcaps %" GST_PTR_FORMAT, caps);
559
560   state = _new_input_state (caps);
561   if (G_UNLIKELY (!state))
562     goto parse_fail;
563
564   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
565
566   if (encoder->priv->input_state)
567     samecaps =
568         gst_video_info_is_equal (&state->info,
569         &encoder->priv->input_state->info);
570
571   if (!samecaps) {
572     /* arrange draining pending frames */
573     gst_video_encoder_drain (encoder);
574
575     /* and subclass should be ready to configure format at any time around */
576     ret = encoder_class->set_format (encoder, state);
577     if (ret) {
578       if (encoder->priv->input_state)
579         gst_video_codec_state_unref (encoder->priv->input_state);
580       encoder->priv->input_state = state;
581     } else
582       gst_video_codec_state_unref (state);
583   } else {
584     /* no need to stir things up */
585     GST_DEBUG_OBJECT (encoder,
586         "new video format identical to configured format");
587     gst_video_codec_state_unref (state);
588     ret = TRUE;
589   }
590
591   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
592
593   if (!ret)
594     GST_WARNING_OBJECT (encoder, "rejected caps %" GST_PTR_FORMAT, caps);
595
596   gst_object_unref (encoder);
597
598   return ret;
599
600 parse_fail:
601   {
602     GST_WARNING_OBJECT (encoder, "Failed to parse caps");
603     gst_object_unref (encoder);
604     return FALSE;
605   }
606 }
607
608 /**
609  * gst_video_encoder_proxy_getcaps:
610  * @enc: a #GstVideoEncoder
611  * @caps: initial caps
612  *
613  * Returns caps that express @caps (or sink template caps if @caps == NULL)
614  * restricted to resolution/format/... combinations supported by downstream
615  * elements (e.g. muxers).
616  *
617  * Returns: a #GstCaps owned by caller
618  *
619  * Since: 0.10.36
620  */
621 GstCaps *
622 gst_video_encoder_proxy_getcaps (GstVideoEncoder * encoder, GstCaps * caps,
623     GstCaps * filter)
624 {
625   GstCaps *templ_caps;
626   GstCaps *allowed;
627   GstCaps *fcaps, *filter_caps;
628   gint i, j;
629
630   /* Allow downstream to specify width/height/framerate/PAR constraints
631    * and forward them upstream for video converters to handle
632    */
633   templ_caps = caps ? caps : gst_pad_get_pad_template_caps (encoder->sinkpad);
634   allowed = gst_pad_get_allowed_caps (encoder->srcpad);
635
636   if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
637     fcaps = templ_caps;
638     goto done;
639   }
640
641   GST_LOG_OBJECT (encoder, "template caps %" GST_PTR_FORMAT, templ_caps);
642   GST_LOG_OBJECT (encoder, "allowed caps %" GST_PTR_FORMAT, allowed);
643
644   filter_caps = gst_caps_new_empty ();
645
646   for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
647     GQuark q_name =
648         gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
649
650     for (j = 0; j < gst_caps_get_size (allowed); j++) {
651       const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
652       const GValue *val;
653       GstStructure *s;
654
655       s = gst_structure_new_id_empty (q_name);
656       if ((val = gst_structure_get_value (allowed_s, "width")))
657         gst_structure_set_value (s, "width", val);
658       if ((val = gst_structure_get_value (allowed_s, "height")))
659         gst_structure_set_value (s, "height", val);
660       if ((val = gst_structure_get_value (allowed_s, "framerate")))
661         gst_structure_set_value (s, "framerate", val);
662       if ((val = gst_structure_get_value (allowed_s, "pixel-aspect-ratio")))
663         gst_structure_set_value (s, "pixel-aspect-ratio", val);
664
665       filter_caps = gst_caps_merge_structure (filter_caps, s);
666     }
667   }
668
669   fcaps = gst_caps_intersect (filter_caps, templ_caps);
670   gst_caps_unref (filter_caps);
671   gst_caps_unref (templ_caps);
672
673   if (filter) {
674     GST_LOG_OBJECT (encoder, "intersecting with %" GST_PTR_FORMAT, filter);
675     filter_caps = gst_caps_intersect (fcaps, filter);
676     gst_caps_unref (fcaps);
677     fcaps = filter_caps;
678   }
679
680 done:
681   gst_caps_replace (&allowed, NULL);
682
683   GST_LOG_OBJECT (encoder, "proxy caps %" GST_PTR_FORMAT, fcaps);
684
685   return fcaps;
686 }
687
688 static GstCaps *
689 gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder, GstCaps * filter)
690 {
691   GstVideoEncoderClass *klass;
692   GstCaps *caps;
693
694   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
695
696   if (klass->getcaps)
697     caps = klass->getcaps (encoder, filter);
698   else
699     caps = gst_video_encoder_proxy_getcaps (encoder, NULL, filter);
700
701   GST_LOG_OBJECT (encoder, "Returning caps %" GST_PTR_FORMAT, caps);
702
703   return caps;
704 }
705
706
707 static gboolean
708 gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
709     GstQuery * query)
710 {
711   GstVideoEncoder *encoder;
712   gboolean res = FALSE;
713
714   encoder = GST_VIDEO_ENCODER (parent);
715
716   switch (GST_QUERY_TYPE (query)) {
717     case GST_QUERY_CAPS:
718     {
719       GstCaps *filter, *caps;
720
721       gst_query_parse_caps (query, &filter);
722       caps = gst_video_encoder_sink_getcaps (encoder, filter);
723       gst_query_set_caps_result (query, caps);
724       gst_caps_unref (caps);
725       res = TRUE;
726       break;
727     }
728     default:
729       res = gst_pad_query_default (pad, parent, query);
730       break;
731   }
732   return res;
733 }
734
735 static void
736 gst_video_encoder_finalize (GObject * object)
737 {
738   GstVideoEncoder *encoder;
739
740   GST_DEBUG_OBJECT (object, "finalize");
741
742   encoder = GST_VIDEO_ENCODER (object);
743   if (encoder->priv->headers) {
744     g_list_foreach (encoder->priv->headers, (GFunc) gst_buffer_unref, NULL);
745     g_list_free (encoder->priv->headers);
746   }
747   g_rec_mutex_clear (&encoder->stream_lock);
748
749   G_OBJECT_CLASS (parent_class)->finalize (object);
750 }
751
752 static gboolean
753 gst_video_encoder_push_event (GstVideoEncoder * encoder, GstEvent * event)
754 {
755   switch (GST_EVENT_TYPE (event)) {
756     case GST_EVENT_SEGMENT:
757     {
758       GstSegment segment;
759
760       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
761
762       gst_event_copy_segment (event, &segment);
763
764       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
765
766       if (segment.format != GST_FORMAT_TIME) {
767         GST_DEBUG_OBJECT (encoder, "received non TIME segment");
768         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
769         break;
770       }
771
772       encoder->output_segment = segment;
773       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
774       break;
775     }
776     default:
777       break;
778   }
779
780   return gst_pad_push_event (encoder->srcpad, event);
781 }
782
783 static gboolean
784 gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
785     GstEvent * event)
786 {
787   GstVideoEncoderClass *encoder_class;
788   gboolean ret = FALSE;
789
790   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
791
792   switch (GST_EVENT_TYPE (event)) {
793     case GST_EVENT_CAPS:
794     {
795       GstCaps *caps;
796
797       gst_event_parse_caps (event, &caps);
798       ret = gst_video_encoder_setcaps (encoder, caps);
799       gst_event_unref (event);
800       event = NULL;
801       break;
802     }
803     case GST_EVENT_EOS:
804     {
805       GstFlowReturn flow_ret;
806
807       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
808       encoder->priv->at_eos = TRUE;
809
810       if (encoder_class->finish) {
811         flow_ret = encoder_class->finish (encoder);
812       } else {
813         flow_ret = GST_FLOW_OK;
814       }
815
816       ret = (flow_ret == GST_FLOW_OK);
817       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
818       break;
819     }
820     case GST_EVENT_SEGMENT:
821     {
822       GstSegment segment;
823
824       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
825
826       gst_event_copy_segment (event, &segment);
827
828       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
829
830       if (segment.format != GST_FORMAT_TIME) {
831         GST_DEBUG_OBJECT (encoder, "received non TIME newsegment");
832         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
833         break;
834       }
835
836       encoder->priv->at_eos = FALSE;
837
838       encoder->input_segment = segment;
839       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
840       break;
841     }
842     case GST_EVENT_CUSTOM_DOWNSTREAM:
843     {
844       if (gst_video_event_is_force_key_unit (event)) {
845         GstClockTime running_time;
846         gboolean all_headers;
847         guint count;
848
849         if (gst_video_event_parse_downstream_force_key_unit (event,
850                 NULL, NULL, &running_time, &all_headers, &count)) {
851           ForcedKeyUnitEvent *fevt;
852
853           GST_OBJECT_LOCK (encoder);
854           fevt = forced_key_unit_event_new (running_time, all_headers, count);
855           encoder->priv->force_key_unit =
856               g_list_append (encoder->priv->force_key_unit, fevt);
857           GST_OBJECT_UNLOCK (encoder);
858
859           GST_DEBUG_OBJECT (encoder,
860               "force-key-unit event: running-time %" GST_TIME_FORMAT
861               ", all_headers %d, count %u",
862               GST_TIME_ARGS (running_time), all_headers, count);
863         }
864         gst_event_unref (event);
865         event = NULL;
866         ret = TRUE;
867       }
868       break;
869     }
870     default:
871       break;
872   }
873
874   /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
875    * For EOS this is required because no buffer or serialized event
876    * will come after EOS and nothing could trigger another
877    * _finish_frame() call.   *
878    * If the subclass handles sending of EOS manually it can simply
879    * not chain up to the parent class' event handler
880    *
881    * For FLUSH_STOP this is required because it is expected
882    * to be forwarded immediately and no buffers are queued anyway.
883    */
884   if (event) {
885     if (!GST_EVENT_IS_SERIALIZED (event)
886         || GST_EVENT_TYPE (event) == GST_EVENT_EOS
887         || GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_STOP) {
888       ret = gst_video_encoder_push_event (encoder, event);
889     } else {
890       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
891       encoder->priv->current_frame_events =
892           g_list_prepend (encoder->priv->current_frame_events, event);
893       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
894     }
895   }
896
897   return ret;
898 }
899
900 static gboolean
901 gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
902     GstEvent * event)
903 {
904   GstVideoEncoder *enc;
905   GstVideoEncoderClass *klass;
906   gboolean ret = TRUE;
907
908   enc = GST_VIDEO_ENCODER (parent);
909   klass = GST_VIDEO_ENCODER_GET_CLASS (enc);
910
911   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
912       GST_EVENT_TYPE_NAME (event));
913
914   if (klass->sink_event)
915     ret = klass->sink_event (enc, event);
916
917   return ret;
918 }
919
920 static gboolean
921 gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
922     GstEvent * event)
923 {
924   gboolean ret = FALSE;
925
926   switch (GST_EVENT_TYPE (event)) {
927     case GST_EVENT_CUSTOM_UPSTREAM:
928     {
929       if (gst_video_event_is_force_key_unit (event)) {
930         GstClockTime running_time;
931         gboolean all_headers;
932         guint count;
933
934         if (gst_video_event_parse_upstream_force_key_unit (event,
935                 &running_time, &all_headers, &count)) {
936           ForcedKeyUnitEvent *fevt;
937
938           GST_OBJECT_LOCK (encoder);
939           fevt = forced_key_unit_event_new (running_time, all_headers, count);
940           encoder->priv->force_key_unit =
941               g_list_append (encoder->priv->force_key_unit, fevt);
942           GST_OBJECT_UNLOCK (encoder);
943
944           GST_DEBUG_OBJECT (encoder,
945               "force-key-unit event: running-time %" GST_TIME_FORMAT
946               ", all_headers %d, count %u",
947               GST_TIME_ARGS (running_time), all_headers, count);
948         }
949         gst_event_unref (event);
950         event = NULL;
951         ret = TRUE;
952       }
953       break;
954     }
955     default:
956       break;
957   }
958
959   if (event)
960     ret =
961         gst_pad_event_default (encoder->srcpad, GST_OBJECT_CAST (encoder),
962         event);
963
964   return ret;
965 }
966
967 static gboolean
968 gst_video_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
969 {
970   GstVideoEncoder *encoder;
971   GstVideoEncoderClass *klass;
972   gboolean ret = FALSE;
973
974   encoder = GST_VIDEO_ENCODER (parent);
975   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
976
977   GST_LOG_OBJECT (encoder, "handling event: %" GST_PTR_FORMAT, event);
978
979   if (klass->src_event)
980     ret = klass->src_event (encoder, event);
981
982   return ret;
983 }
984
985 static gboolean
986 gst_video_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
987 {
988   GstVideoEncoderPrivate *priv;
989   GstVideoEncoder *enc;
990   gboolean res;
991
992   enc = GST_VIDEO_ENCODER (parent);
993   priv = enc->priv;
994
995   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
996
997   switch (GST_QUERY_TYPE (query)) {
998     case GST_QUERY_CONVERT:
999     {
1000       GstFormat src_fmt, dest_fmt;
1001       gint64 src_val, dest_val;
1002
1003       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1004       res =
1005           gst_video_encoded_video_convert (priv->bytes, priv->time, src_fmt,
1006           src_val, &dest_fmt, &dest_val);
1007       if (!res)
1008         goto error;
1009       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1010       break;
1011     }
1012     case GST_QUERY_LATENCY:
1013     {
1014       gboolean live;
1015       GstClockTime min_latency, max_latency;
1016
1017       res = gst_pad_peer_query (enc->sinkpad, query);
1018       if (res) {
1019         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1020         GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1021             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1022             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1023
1024         GST_OBJECT_LOCK (enc);
1025         min_latency += priv->min_latency;
1026         if (max_latency != GST_CLOCK_TIME_NONE) {
1027           max_latency += priv->max_latency;
1028         }
1029         GST_OBJECT_UNLOCK (enc);
1030
1031         gst_query_set_latency (query, live, min_latency, max_latency);
1032       }
1033     }
1034       break;
1035     default:
1036       res = gst_pad_query_default (pad, parent, query);
1037   }
1038   return res;
1039
1040 error:
1041   GST_DEBUG_OBJECT (enc, "query failed");
1042   return res;
1043 }
1044
1045 static GstVideoCodecFrame *
1046 gst_video_encoder_new_frame (GstVideoEncoder * encoder, GstBuffer * buf,
1047     GstClockTime timestamp, GstClockTime duration)
1048 {
1049   GstVideoEncoderPrivate *priv = encoder->priv;
1050   GstVideoCodecFrame *frame;
1051
1052   frame = g_slice_new0 (GstVideoCodecFrame);
1053
1054   frame->ref_count = 1;
1055
1056   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1057   frame->system_frame_number = priv->system_frame_number;
1058   priv->system_frame_number++;
1059
1060   frame->presentation_frame_number = priv->presentation_frame_number;
1061   priv->presentation_frame_number++;
1062   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1063
1064   frame->events = priv->current_frame_events;
1065   priv->current_frame_events = NULL;
1066   frame->input_buffer = buf;
1067   frame->pts = timestamp;
1068   frame->duration = duration;
1069
1070   return frame;
1071 }
1072
1073
1074 static GstFlowReturn
1075 gst_video_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1076 {
1077   GstVideoEncoder *encoder;
1078   GstVideoEncoderPrivate *priv;
1079   GstVideoEncoderClass *klass;
1080   GstVideoCodecFrame *frame;
1081   GstFlowReturn ret = GST_FLOW_OK;
1082   guint64 start, stop = GST_CLOCK_TIME_NONE, cstart, cstop;
1083
1084   encoder = GST_VIDEO_ENCODER (parent);
1085   priv = encoder->priv;
1086   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1087
1088   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1089
1090   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1091
1092   start = GST_BUFFER_TIMESTAMP (buf);
1093   if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DURATION (buf)))
1094     stop = start + GST_BUFFER_DURATION (buf);
1095
1096   GST_LOG_OBJECT (encoder,
1097       "received buffer of size %d with ts %" GST_TIME_FORMAT
1098       ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buf),
1099       GST_TIME_ARGS (start), GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1100
1101   if (priv->at_eos) {
1102     ret = GST_FLOW_EOS;
1103     goto done;
1104   }
1105
1106   /* Drop buffers outside of segment */
1107   if (!gst_segment_clip (&encoder->output_segment,
1108           GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
1109     GST_DEBUG_OBJECT (encoder, "clipping to segment dropped frame");
1110     gst_buffer_unref (buf);
1111     goto done;
1112   }
1113
1114   frame = gst_video_encoder_new_frame (encoder, buf, cstart, cstop - cstart);
1115
1116   GST_OBJECT_LOCK (encoder);
1117   if (priv->force_key_unit) {
1118     ForcedKeyUnitEvent *fevt = NULL;
1119     GstClockTime running_time;
1120     GList *l;
1121
1122     running_time =
1123         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1124         GST_BUFFER_TIMESTAMP (buf));
1125
1126     for (l = priv->force_key_unit; l; l = l->next) {
1127       ForcedKeyUnitEvent *tmp = l->data;
1128
1129       /* Skip pending keyunits */
1130       if (tmp->pending)
1131         continue;
1132
1133       /* Simple case, keyunit ASAP */
1134       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1135         fevt = tmp;
1136         break;
1137       }
1138
1139       /* Event for before this frame */
1140       if (tmp->running_time <= running_time) {
1141         fevt = tmp;
1142         break;
1143       }
1144     }
1145
1146     if (fevt) {
1147       GST_DEBUG_OBJECT (encoder,
1148           "Forcing a key unit at running time %" GST_TIME_FORMAT,
1149           GST_TIME_ARGS (running_time));
1150       GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME (frame);
1151       if (fevt->all_headers)
1152         GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME_HEADERS (frame);
1153       fevt->pending = TRUE;
1154     }
1155   }
1156   GST_OBJECT_UNLOCK (encoder);
1157
1158   priv->frames = g_list_append (priv->frames, frame);
1159
1160   /* new data, more finish needed */
1161   priv->drained = FALSE;
1162
1163   GST_LOG_OBJECT (encoder, "passing frame pfn %d to subclass",
1164       frame->presentation_frame_number);
1165
1166   ret = klass->handle_frame (encoder, frame);
1167
1168 done:
1169   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1170
1171   return ret;
1172 }
1173
1174 static GstStateChangeReturn
1175 gst_video_encoder_change_state (GstElement * element, GstStateChange transition)
1176 {
1177   GstVideoEncoder *encoder;
1178   GstVideoEncoderClass *encoder_class;
1179   GstStateChangeReturn ret;
1180
1181   encoder = GST_VIDEO_ENCODER (element);
1182   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (element);
1183
1184   switch (transition) {
1185     case GST_STATE_CHANGE_NULL_TO_READY:
1186       /* open device/library if needed */
1187       if (encoder_class->open && !encoder_class->open (encoder))
1188         goto open_failed;
1189       break;
1190     case GST_STATE_CHANGE_READY_TO_PAUSED:
1191       /* Initialize device/library if needed */
1192       if (encoder_class->start && !encoder_class->start (encoder))
1193         goto start_failed;
1194       break;
1195     default:
1196       break;
1197   }
1198
1199   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1200
1201   switch (transition) {
1202     case GST_STATE_CHANGE_PAUSED_TO_READY:
1203       gst_video_encoder_reset (encoder);
1204       if (encoder_class->stop && !encoder_class->stop (encoder))
1205         goto stop_failed;
1206       break;
1207     case GST_STATE_CHANGE_READY_TO_NULL:
1208       /* close device/library if needed */
1209       if (encoder_class->close && !encoder_class->close (encoder))
1210         goto close_failed;
1211       break;
1212     default:
1213       break;
1214   }
1215
1216   return ret;
1217
1218   /* Errors */
1219
1220 open_failed:
1221   {
1222     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1223         ("Failed to open encoder"));
1224     return GST_STATE_CHANGE_FAILURE;
1225   }
1226
1227 start_failed:
1228   {
1229     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1230         ("Failed to start encoder"));
1231     return GST_STATE_CHANGE_FAILURE;
1232   }
1233
1234 stop_failed:
1235   {
1236     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1237         ("Failed to stop encoder"));
1238     return GST_STATE_CHANGE_FAILURE;
1239   }
1240
1241 close_failed:
1242   {
1243     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1244         ("Failed to close encoder"));
1245     return GST_STATE_CHANGE_FAILURE;
1246   }
1247 }
1248
1249 static gboolean
1250 gst_video_encoder_set_src_caps (GstVideoEncoder * encoder)
1251 {
1252   gboolean ret;
1253   GstVideoCodecState *state = encoder->priv->output_state;
1254   GstVideoInfo *info = &state->info;
1255
1256   g_return_val_if_fail (state->caps != NULL, FALSE);
1257
1258   if (encoder->priv->output_state_changed) {
1259     state->caps = gst_caps_make_writable (state->caps);
1260
1261     /* Fill caps */
1262     gst_caps_set_simple (state->caps, "width", G_TYPE_INT, info->width,
1263         "height", G_TYPE_INT, info->height,
1264         "pixel-aspect-ratio", GST_TYPE_FRACTION,
1265         info->par_n, info->par_d, NULL);
1266     if (info->flags & GST_VIDEO_FLAG_VARIABLE_FPS && info->fps_n != 0) {
1267       /* variable fps with a max-framerate */
1268       gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION, 0, 1,
1269           "max-framerate", GST_TYPE_FRACTION, info->fps_n, info->fps_d, NULL);
1270     } else {
1271       /* no variable fps or no max-framerate */
1272       gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION,
1273           info->fps_n, info->fps_d, NULL);
1274     }
1275     if (state->codec_data)
1276       gst_caps_set_simple (state->caps, "codec_data", GST_TYPE_BUFFER,
1277           state->codec_data, NULL);
1278     encoder->priv->output_state_changed = FALSE;
1279   }
1280
1281   ret = gst_pad_set_caps (encoder->srcpad, state->caps);
1282
1283   return ret;
1284 }
1285
1286 /**
1287  * gst_video_encoder_finish_frame:
1288  * @encoder: a #GstVideoEncoder
1289  * @frame: (transfer full): an encoded #GstVideoCodecFrame 
1290  *
1291  * @frame must have a valid encoded data buffer, whose metadata fields
1292  * are then appropriately set according to frame data or no buffer at
1293  * all if the frame should be dropped.
1294  * It is subsequently pushed downstream or provided to @pre_push.
1295  * In any case, the frame is considered finished and released.
1296  *
1297  * Returns: a #GstFlowReturn resulting from sending data downstream
1298  *
1299  * Since: 0.10.36
1300  */
1301 GstFlowReturn
1302 gst_video_encoder_finish_frame (GstVideoEncoder * encoder,
1303     GstVideoCodecFrame * frame)
1304 {
1305   GstVideoEncoderPrivate *priv = encoder->priv;
1306   GstFlowReturn ret = GST_FLOW_OK;
1307   GstVideoEncoderClass *encoder_class;
1308   GList *l;
1309   gboolean send_headers = FALSE;
1310   gboolean discont = (frame->presentation_frame_number == 0);
1311
1312   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1313
1314   GST_LOG_OBJECT (encoder,
1315       "finish frame fpn %d", frame->presentation_frame_number);
1316
1317   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1318
1319   if (G_UNLIKELY (priv->output_state_changed))
1320     gst_video_encoder_set_src_caps (encoder);
1321
1322   if (G_UNLIKELY (priv->output_state == NULL))
1323     goto no_output_state;
1324
1325   /* Push all pending events that arrived before this frame */
1326   for (l = priv->frames; l; l = l->next) {
1327     GstVideoCodecFrame *tmp = l->data;
1328
1329     if (tmp->events) {
1330       GList *k;
1331
1332       for (k = g_list_last (tmp->events); k; k = k->prev)
1333         gst_video_encoder_push_event (encoder, k->data);
1334       g_list_free (tmp->events);
1335       tmp->events = NULL;
1336     }
1337
1338     if (tmp == frame)
1339       break;
1340   }
1341
1342   /* no buffer data means this frame is skipped/dropped */
1343   if (!frame->output_buffer) {
1344     GST_DEBUG_OBJECT (encoder, "skipping frame %" GST_TIME_FORMAT,
1345         GST_TIME_ARGS (frame->pts));
1346     goto done;
1347   }
1348
1349   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame) && priv->force_key_unit) {
1350     GstClockTime stream_time, running_time;
1351     GstEvent *ev;
1352     ForcedKeyUnitEvent *fevt = NULL;
1353     GList *l;
1354
1355     running_time =
1356         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1357         frame->pts);
1358
1359     GST_OBJECT_LOCK (encoder);
1360     for (l = priv->force_key_unit; l; l = l->next) {
1361       ForcedKeyUnitEvent *tmp = l->data;
1362
1363       /* Skip non-pending keyunits */
1364       if (!tmp->pending)
1365         continue;
1366
1367       /* Simple case, keyunit ASAP */
1368       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1369         fevt = tmp;
1370         break;
1371       }
1372
1373       /* Event for before this frame */
1374       if (tmp->running_time <= running_time) {
1375         fevt = tmp;
1376         break;
1377       }
1378     }
1379
1380     if (fevt) {
1381       priv->force_key_unit = g_list_remove (priv->force_key_unit, fevt);
1382     }
1383     GST_OBJECT_UNLOCK (encoder);
1384
1385     if (fevt) {
1386       stream_time =
1387           gst_segment_to_stream_time (&encoder->output_segment, GST_FORMAT_TIME,
1388           frame->pts);
1389
1390       ev = gst_video_event_new_downstream_force_key_unit
1391           (frame->pts, stream_time, running_time,
1392           fevt->all_headers, fevt->count);
1393
1394       gst_video_encoder_push_event (encoder, ev);
1395
1396       if (fevt->all_headers)
1397         send_headers = TRUE;
1398
1399       GST_DEBUG_OBJECT (encoder,
1400           "Forced key unit: running-time %" GST_TIME_FORMAT
1401           ", all_headers %d, count %u",
1402           GST_TIME_ARGS (running_time), fevt->all_headers, fevt->count);
1403       forced_key_unit_event_free (fevt);
1404     }
1405   }
1406
1407   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
1408     priv->distance_from_sync = 0;
1409     GST_BUFFER_FLAG_UNSET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1410     /* For keyframes, DTS = PTS */
1411     frame->dts = frame->pts;
1412   } else {
1413     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1414   }
1415
1416   frame->distance_from_sync = priv->distance_from_sync;
1417   priv->distance_from_sync++;
1418
1419   GST_BUFFER_TIMESTAMP (frame->output_buffer) = frame->pts;
1420   GST_BUFFER_DURATION (frame->output_buffer) = frame->duration;
1421
1422   /* update rate estimate */
1423   priv->bytes += gst_buffer_get_size (frame->output_buffer);
1424   if (GST_CLOCK_TIME_IS_VALID (frame->duration)) {
1425     priv->time += frame->duration;
1426   } else {
1427     /* better none than nothing valid */
1428     priv->time = GST_CLOCK_TIME_NONE;
1429   }
1430
1431   if (G_UNLIKELY (send_headers || priv->new_headers)) {
1432     GList *tmp, *copy = NULL;
1433
1434     GST_DEBUG_OBJECT (encoder, "Sending headers");
1435
1436     /* First make all buffers metadata-writable */
1437     for (tmp = priv->headers; tmp; tmp = tmp->next) {
1438       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1439
1440       copy = g_list_append (copy, gst_buffer_make_writable (tmpbuf));
1441     }
1442     g_list_free (priv->headers);
1443     priv->headers = copy;
1444
1445     for (tmp = priv->headers; tmp; tmp = tmp->next) {
1446       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1447
1448       gst_buffer_ref (tmpbuf);
1449       priv->bytes += gst_buffer_get_size (tmpbuf);
1450       if (G_UNLIKELY (discont)) {
1451         GST_LOG_OBJECT (encoder, "marking discont");
1452         GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
1453         discont = FALSE;
1454       }
1455
1456       gst_pad_push (encoder->srcpad, tmpbuf);
1457     }
1458     priv->new_headers = FALSE;
1459   }
1460
1461   if (G_UNLIKELY (discont)) {
1462     GST_LOG_OBJECT (encoder, "marking discont");
1463     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DISCONT);
1464   }
1465
1466   if (encoder_class->pre_push)
1467     ret = encoder_class->pre_push (encoder, frame);
1468
1469   if (ret == GST_FLOW_OK)
1470     ret = gst_pad_push (encoder->srcpad, frame->output_buffer);
1471
1472   frame->output_buffer = NULL;
1473
1474 done:
1475   /* handed out */
1476   priv->frames = g_list_remove (priv->frames, frame);
1477
1478   gst_video_codec_frame_unref (frame);
1479
1480   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1481
1482   return ret;
1483
1484   /* ERRORS */
1485 no_output_state:
1486   {
1487     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1488     GST_ERROR_OBJECT (encoder, "Output state was not configured");
1489     return GST_FLOW_ERROR;
1490   }
1491 }
1492
1493 /**
1494  * gst_video_encoder_get_output_state:
1495  * @encoder: a #GstVideoEncoder
1496  *
1497  * Get the current #GstVideoCodecState
1498  *
1499  * Returns: (transfer full): #GstVideoCodecState describing format of video data.
1500  *
1501  * Since: 0.10.36
1502  */
1503 GstVideoCodecState *
1504 gst_video_encoder_get_output_state (GstVideoEncoder * encoder)
1505 {
1506   GstVideoCodecState *state;
1507
1508   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1509   state = gst_video_codec_state_ref (encoder->priv->output_state);
1510   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1511
1512   return state;
1513 }
1514
1515 /**
1516  * gst_video_encoder_set_output_state:
1517  * @encoder: a #GstVideoEncoder
1518  * @caps: (transfer full): the #GstCaps to use for the output
1519  * @reference: (allow-none) (transfer none): An optional reference @GstVideoCodecState
1520  *
1521  * Creates a new #GstVideoCodecState with the specified caps as the output state
1522  * for the encoder.
1523  * Any previously set output state on @decoder will be replaced by the newly
1524  * created one.
1525  *
1526  * The specified @caps should not contain any resolution, pixel-aspect-ratio,
1527  * framerate, codec-data, .... Those should be specified instead in the returned
1528  * #GstVideoCodecState.
1529  *
1530  * If the subclass wishes to copy over existing fields (like pixel aspect ratio,
1531  * or framerate) from an existing #GstVideoCodecState, it can be provided as a
1532  * @reference.
1533  *
1534  * If the subclass wishes to override some fields from the output state (like
1535  * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
1536  *
1537  * The new output state will only take effect (set on pads and buffers) starting
1538  * from the next call to #gst_video_encoder_finish_frame().
1539  *
1540  * Returns: (transfer full): the newly configured output state.
1541  *
1542  * Since: 0.10.36
1543  */
1544 GstVideoCodecState *
1545 gst_video_encoder_set_output_state (GstVideoEncoder * encoder, GstCaps * caps,
1546     GstVideoCodecState * reference)
1547 {
1548   GstVideoEncoderPrivate *priv = encoder->priv;
1549   GstVideoCodecState *state;
1550
1551   g_return_val_if_fail (caps != NULL, NULL);
1552
1553   state = _new_output_state (caps, reference);
1554
1555   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1556   if (priv->output_state)
1557     gst_video_codec_state_unref (priv->output_state);
1558   priv->output_state = gst_video_codec_state_ref (state);
1559
1560   priv->output_state_changed = TRUE;
1561   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1562
1563   return state;
1564 }
1565
1566 /**
1567  * gst_video_encoder_set_latency:
1568  * @encoder: a #GstVideoEncoder
1569  * @min_latency: minimum latency
1570  * @max_latency: maximum latency
1571  *
1572  * Informs baseclass of encoding latency.
1573  *
1574  * Since: 0.10.36
1575  */
1576 void
1577 gst_video_encoder_set_latency (GstVideoEncoder * encoder,
1578     GstClockTime min_latency, GstClockTime max_latency)
1579 {
1580   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
1581   g_return_if_fail (max_latency >= min_latency);
1582
1583   GST_OBJECT_LOCK (encoder);
1584   encoder->priv->min_latency = min_latency;
1585   encoder->priv->max_latency = max_latency;
1586   GST_OBJECT_UNLOCK (encoder);
1587
1588   gst_element_post_message (GST_ELEMENT_CAST (encoder),
1589       gst_message_new_latency (GST_OBJECT_CAST (encoder)));
1590 }
1591
1592 /**
1593  * gst_video_encoder_get_latency:
1594  * @encoder: a #GstVideoEncoder
1595  * @min_latency: (out) (allow-none): the configured minimum latency
1596  * @max_latency: (out) (allow-none): the configured maximum latency
1597  *
1598  * Returns the configured encoding latency.
1599  *
1600  * Since: 0.10.36
1601  */
1602 void
1603 gst_video_encoder_get_latency (GstVideoEncoder * encoder,
1604     GstClockTime * min_latency, GstClockTime * max_latency)
1605 {
1606   GST_OBJECT_LOCK (encoder);
1607   if (min_latency)
1608     *min_latency = encoder->priv->min_latency;
1609   if (max_latency)
1610     *max_latency = encoder->priv->max_latency;
1611   GST_OBJECT_UNLOCK (encoder);
1612 }
1613
1614 /**
1615  * gst_video_encoder_get_oldest_frame:
1616  * @encoder: a #GstVideoEncoder
1617  *
1618  * Get the oldest unfinished pending #GstVideoCodecFrame
1619  *
1620  * Returns: oldest unfinished pending #GstVideoCodecFrame
1621  *
1622  * Since: 0.10.36
1623  */
1624 GstVideoCodecFrame *
1625 gst_video_encoder_get_oldest_frame (GstVideoEncoder * encoder)
1626 {
1627   GList *g;
1628
1629   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1630   g = encoder->priv->frames;
1631   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1632
1633   if (g == NULL)
1634     return NULL;
1635   return (GstVideoCodecFrame *) (g->data);
1636 }
1637
1638 /**
1639  * gst_video_encoder_get_frame:
1640  * @encoder: a #GstVideoEnccoder
1641  * @frame_number: system_frame_number of a frame
1642  *
1643  * Get a pending unfinished #GstVideoCodecFrame
1644  * 
1645  * Returns: (transfer none): pending unfinished #GstVideoCodecFrame identified by @frame_number.
1646  *
1647  * Since: 0.10.36
1648  */
1649 GstVideoCodecFrame *
1650 gst_video_encoder_get_frame (GstVideoEncoder * encoder, int frame_number)
1651 {
1652   GList *g;
1653   GstVideoCodecFrame *frame = NULL;
1654
1655   GST_DEBUG_OBJECT (encoder, "frame_number : %d", frame_number);
1656
1657   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1658   for (g = encoder->priv->frames; g; g = g->next) {
1659     GstVideoCodecFrame *tmp = g->data;
1660
1661     if (tmp->system_frame_number == frame_number) {
1662       frame = tmp;
1663       break;
1664     }
1665   }
1666   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1667
1668   return frame;
1669 }