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