videoencoder: Add support for subclasses to propose allocation parameters
[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   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE);
715
716   return TRUE;
717 }
718
719 static gboolean
720 gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
721     GstQuery * query)
722 {
723   GstVideoEncoder *encoder;
724   gboolean res = FALSE;
725
726   encoder = GST_VIDEO_ENCODER (parent);
727
728   switch (GST_QUERY_TYPE (query)) {
729     case GST_QUERY_CAPS:
730     {
731       GstCaps *filter, *caps;
732
733       gst_query_parse_caps (query, &filter);
734       caps = gst_video_encoder_sink_getcaps (encoder, filter);
735       gst_query_set_caps_result (query, caps);
736       gst_caps_unref (caps);
737       res = TRUE;
738       break;
739     }
740     case GST_QUERY_ALLOCATION:
741     {
742       GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
743
744       if (klass->propose_allocation)
745         res = klass->propose_allocation (encoder, query);
746       break;
747     }
748     default:
749       res = gst_pad_query_default (pad, parent, query);
750       break;
751   }
752   return res;
753 }
754
755 static void
756 gst_video_encoder_finalize (GObject * object)
757 {
758   GstVideoEncoder *encoder;
759
760   GST_DEBUG_OBJECT (object, "finalize");
761
762   encoder = GST_VIDEO_ENCODER (object);
763   if (encoder->priv->headers) {
764     g_list_foreach (encoder->priv->headers, (GFunc) gst_buffer_unref, NULL);
765     g_list_free (encoder->priv->headers);
766   }
767   g_rec_mutex_clear (&encoder->stream_lock);
768
769   G_OBJECT_CLASS (parent_class)->finalize (object);
770 }
771
772 static gboolean
773 gst_video_encoder_push_event (GstVideoEncoder * encoder, GstEvent * event)
774 {
775   switch (GST_EVENT_TYPE (event)) {
776     case GST_EVENT_SEGMENT:
777     {
778       GstSegment segment;
779
780       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
781
782       gst_event_copy_segment (event, &segment);
783
784       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
785
786       if (segment.format != GST_FORMAT_TIME) {
787         GST_DEBUG_OBJECT (encoder, "received non TIME segment");
788         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
789         break;
790       }
791
792       encoder->output_segment = segment;
793       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
794       break;
795     }
796     default:
797       break;
798   }
799
800   return gst_pad_push_event (encoder->srcpad, event);
801 }
802
803 static gboolean
804 gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
805     GstEvent * event)
806 {
807   GstVideoEncoderClass *encoder_class;
808   gboolean ret = FALSE;
809
810   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
811
812   switch (GST_EVENT_TYPE (event)) {
813     case GST_EVENT_CAPS:
814     {
815       GstCaps *caps;
816
817       gst_event_parse_caps (event, &caps);
818       ret = gst_video_encoder_setcaps (encoder, caps);
819       gst_event_unref (event);
820       event = NULL;
821       break;
822     }
823     case GST_EVENT_EOS:
824     {
825       GstFlowReturn flow_ret;
826
827       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
828       encoder->priv->at_eos = TRUE;
829
830       if (encoder_class->finish) {
831         flow_ret = encoder_class->finish (encoder);
832       } else {
833         flow_ret = GST_FLOW_OK;
834       }
835
836       ret = (flow_ret == GST_FLOW_OK);
837       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
838       break;
839     }
840     case GST_EVENT_SEGMENT:
841     {
842       GstSegment segment;
843
844       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
845
846       gst_event_copy_segment (event, &segment);
847
848       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
849
850       if (segment.format != GST_FORMAT_TIME) {
851         GST_DEBUG_OBJECT (encoder, "received non TIME newsegment");
852         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
853         break;
854       }
855
856       encoder->priv->at_eos = FALSE;
857
858       encoder->input_segment = segment;
859       ret = TRUE;
860       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
861       break;
862     }
863     case GST_EVENT_CUSTOM_DOWNSTREAM:
864     {
865       if (gst_video_event_is_force_key_unit (event)) {
866         GstClockTime running_time;
867         gboolean all_headers;
868         guint count;
869
870         if (gst_video_event_parse_downstream_force_key_unit (event,
871                 NULL, NULL, &running_time, &all_headers, &count)) {
872           ForcedKeyUnitEvent *fevt;
873
874           GST_OBJECT_LOCK (encoder);
875           fevt = forced_key_unit_event_new (running_time, all_headers, count);
876           encoder->priv->force_key_unit =
877               g_list_append (encoder->priv->force_key_unit, fevt);
878           GST_OBJECT_UNLOCK (encoder);
879
880           GST_DEBUG_OBJECT (encoder,
881               "force-key-unit event: running-time %" GST_TIME_FORMAT
882               ", all_headers %d, count %u",
883               GST_TIME_ARGS (running_time), all_headers, count);
884         }
885         gst_event_unref (event);
886         event = NULL;
887         ret = TRUE;
888       }
889       break;
890     }
891     default:
892       break;
893   }
894
895   /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
896    * For EOS this is required because no buffer or serialized event
897    * will come after EOS and nothing could trigger another
898    * _finish_frame() call.   *
899    * If the subclass handles sending of EOS manually it can simply
900    * not chain up to the parent class' event handler
901    *
902    * For FLUSH_STOP this is required because it is expected
903    * to be forwarded immediately and no buffers are queued anyway.
904    */
905   if (event) {
906     if (!GST_EVENT_IS_SERIALIZED (event)
907         || GST_EVENT_TYPE (event) == GST_EVENT_EOS
908         || GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_STOP) {
909       ret = gst_video_encoder_push_event (encoder, event);
910     } else {
911       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
912       encoder->priv->current_frame_events =
913           g_list_prepend (encoder->priv->current_frame_events, event);
914       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
915       ret = TRUE;
916     }
917   }
918
919   return ret;
920 }
921
922 static gboolean
923 gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
924     GstEvent * event)
925 {
926   GstVideoEncoder *enc;
927   GstVideoEncoderClass *klass;
928   gboolean ret = TRUE;
929
930   enc = GST_VIDEO_ENCODER (parent);
931   klass = GST_VIDEO_ENCODER_GET_CLASS (enc);
932
933   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
934       GST_EVENT_TYPE_NAME (event));
935
936   if (klass->sink_event)
937     ret = klass->sink_event (enc, event);
938
939   return ret;
940 }
941
942 static gboolean
943 gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
944     GstEvent * event)
945 {
946   gboolean ret = FALSE;
947
948   switch (GST_EVENT_TYPE (event)) {
949     case GST_EVENT_CUSTOM_UPSTREAM:
950     {
951       if (gst_video_event_is_force_key_unit (event)) {
952         GstClockTime running_time;
953         gboolean all_headers;
954         guint count;
955
956         if (gst_video_event_parse_upstream_force_key_unit (event,
957                 &running_time, &all_headers, &count)) {
958           ForcedKeyUnitEvent *fevt;
959
960           GST_OBJECT_LOCK (encoder);
961           fevt = forced_key_unit_event_new (running_time, all_headers, count);
962           encoder->priv->force_key_unit =
963               g_list_append (encoder->priv->force_key_unit, fevt);
964           GST_OBJECT_UNLOCK (encoder);
965
966           GST_DEBUG_OBJECT (encoder,
967               "force-key-unit event: running-time %" GST_TIME_FORMAT
968               ", all_headers %d, count %u",
969               GST_TIME_ARGS (running_time), all_headers, count);
970         }
971         gst_event_unref (event);
972         event = NULL;
973         ret = TRUE;
974       }
975       break;
976     }
977     default:
978       break;
979   }
980
981   if (event)
982     ret =
983         gst_pad_event_default (encoder->srcpad, GST_OBJECT_CAST (encoder),
984         event);
985
986   return ret;
987 }
988
989 static gboolean
990 gst_video_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
991 {
992   GstVideoEncoder *encoder;
993   GstVideoEncoderClass *klass;
994   gboolean ret = FALSE;
995
996   encoder = GST_VIDEO_ENCODER (parent);
997   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
998
999   GST_LOG_OBJECT (encoder, "handling event: %" GST_PTR_FORMAT, event);
1000
1001   if (klass->src_event)
1002     ret = klass->src_event (encoder, event);
1003
1004   return ret;
1005 }
1006
1007 static gboolean
1008 gst_video_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1009 {
1010   GstVideoEncoderPrivate *priv;
1011   GstVideoEncoder *enc;
1012   gboolean res;
1013
1014   enc = GST_VIDEO_ENCODER (parent);
1015   priv = enc->priv;
1016
1017   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1018
1019   switch (GST_QUERY_TYPE (query)) {
1020     case GST_QUERY_CONVERT:
1021     {
1022       GstFormat src_fmt, dest_fmt;
1023       gint64 src_val, dest_val;
1024
1025       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1026       res =
1027           gst_video_encoded_video_convert (priv->bytes, priv->time, src_fmt,
1028           src_val, &dest_fmt, &dest_val);
1029       if (!res)
1030         goto error;
1031       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1032       break;
1033     }
1034     case GST_QUERY_LATENCY:
1035     {
1036       gboolean live;
1037       GstClockTime min_latency, max_latency;
1038
1039       res = gst_pad_peer_query (enc->sinkpad, query);
1040       if (res) {
1041         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1042         GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1043             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1044             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1045
1046         GST_OBJECT_LOCK (enc);
1047         min_latency += priv->min_latency;
1048         if (max_latency != GST_CLOCK_TIME_NONE) {
1049           max_latency += 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   return frame;
1093 }
1094
1095
1096 static GstFlowReturn
1097 gst_video_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1098 {
1099   GstVideoEncoder *encoder;
1100   GstVideoEncoderPrivate *priv;
1101   GstVideoEncoderClass *klass;
1102   GstVideoCodecFrame *frame;
1103   GstFlowReturn ret = GST_FLOW_OK;
1104   guint64 start, stop = GST_CLOCK_TIME_NONE, cstart, cstop;
1105
1106   encoder = GST_VIDEO_ENCODER (parent);
1107   priv = encoder->priv;
1108   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1109
1110   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1111
1112   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1113
1114   start = GST_BUFFER_TIMESTAMP (buf);
1115   if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DURATION (buf)))
1116     stop = start + GST_BUFFER_DURATION (buf);
1117
1118   GST_LOG_OBJECT (encoder,
1119       "received buffer of size %d with ts %" GST_TIME_FORMAT
1120       ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buf),
1121       GST_TIME_ARGS (start), GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1122
1123   if (priv->at_eos) {
1124     ret = GST_FLOW_EOS;
1125     goto done;
1126   }
1127
1128   /* Drop buffers outside of segment */
1129   if (!gst_segment_clip (&encoder->output_segment,
1130           GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
1131     GST_DEBUG_OBJECT (encoder, "clipping to segment dropped frame");
1132     gst_buffer_unref (buf);
1133     goto done;
1134   }
1135
1136   frame = gst_video_encoder_new_frame (encoder, buf, cstart, cstop - cstart);
1137
1138   GST_OBJECT_LOCK (encoder);
1139   if (priv->force_key_unit) {
1140     ForcedKeyUnitEvent *fevt = NULL;
1141     GstClockTime running_time;
1142     GList *l;
1143
1144     running_time =
1145         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1146         GST_BUFFER_TIMESTAMP (buf));
1147
1148     for (l = priv->force_key_unit; l; l = l->next) {
1149       ForcedKeyUnitEvent *tmp = l->data;
1150
1151       /* Skip pending keyunits */
1152       if (tmp->pending)
1153         continue;
1154
1155       /* Simple case, keyunit ASAP */
1156       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1157         fevt = tmp;
1158         break;
1159       }
1160
1161       /* Event for before this frame */
1162       if (tmp->running_time <= running_time) {
1163         fevt = tmp;
1164         break;
1165       }
1166     }
1167
1168     if (fevt) {
1169       GST_DEBUG_OBJECT (encoder,
1170           "Forcing a key unit at running time %" GST_TIME_FORMAT,
1171           GST_TIME_ARGS (running_time));
1172       GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME (frame);
1173       if (fevt->all_headers)
1174         GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME_HEADERS (frame);
1175       fevt->pending = TRUE;
1176     }
1177   }
1178   GST_OBJECT_UNLOCK (encoder);
1179
1180   priv->frames = g_list_append (priv->frames, frame);
1181
1182   /* new data, more finish needed */
1183   priv->drained = FALSE;
1184
1185   GST_LOG_OBJECT (encoder, "passing frame pfn %d to subclass",
1186       frame->presentation_frame_number);
1187
1188   ret = klass->handle_frame (encoder, frame);
1189
1190 done:
1191   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1192
1193   return ret;
1194 }
1195
1196 static GstStateChangeReturn
1197 gst_video_encoder_change_state (GstElement * element, GstStateChange transition)
1198 {
1199   GstVideoEncoder *encoder;
1200   GstVideoEncoderClass *encoder_class;
1201   GstStateChangeReturn ret;
1202
1203   encoder = GST_VIDEO_ENCODER (element);
1204   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (element);
1205
1206   switch (transition) {
1207     case GST_STATE_CHANGE_NULL_TO_READY:
1208       /* open device/library if needed */
1209       if (encoder_class->open && !encoder_class->open (encoder))
1210         goto open_failed;
1211       break;
1212     case GST_STATE_CHANGE_READY_TO_PAUSED:
1213       /* Initialize device/library if needed */
1214       if (encoder_class->start && !encoder_class->start (encoder))
1215         goto start_failed;
1216       break;
1217     default:
1218       break;
1219   }
1220
1221   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1222
1223   switch (transition) {
1224     case GST_STATE_CHANGE_PAUSED_TO_READY:
1225       gst_video_encoder_reset (encoder);
1226       if (encoder_class->stop && !encoder_class->stop (encoder))
1227         goto stop_failed;
1228       break;
1229     case GST_STATE_CHANGE_READY_TO_NULL:
1230       /* close device/library if needed */
1231       if (encoder_class->close && !encoder_class->close (encoder))
1232         goto close_failed;
1233       break;
1234     default:
1235       break;
1236   }
1237
1238   return ret;
1239
1240   /* Errors */
1241
1242 open_failed:
1243   {
1244     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1245         ("Failed to open encoder"));
1246     return GST_STATE_CHANGE_FAILURE;
1247   }
1248
1249 start_failed:
1250   {
1251     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1252         ("Failed to start encoder"));
1253     return GST_STATE_CHANGE_FAILURE;
1254   }
1255
1256 stop_failed:
1257   {
1258     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1259         ("Failed to stop encoder"));
1260     return GST_STATE_CHANGE_FAILURE;
1261   }
1262
1263 close_failed:
1264   {
1265     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1266         ("Failed to close encoder"));
1267     return GST_STATE_CHANGE_FAILURE;
1268   }
1269 }
1270
1271 static gboolean
1272 gst_video_encoder_set_src_caps (GstVideoEncoder * encoder)
1273 {
1274   gboolean ret;
1275   GstVideoCodecState *state = encoder->priv->output_state;
1276   GstVideoInfo *info = &state->info;
1277
1278   g_return_val_if_fail (state->caps != NULL, FALSE);
1279
1280   if (encoder->priv->output_state_changed) {
1281     state->caps = gst_caps_make_writable (state->caps);
1282
1283     /* Fill caps */
1284     gst_caps_set_simple (state->caps, "width", G_TYPE_INT, info->width,
1285         "height", G_TYPE_INT, info->height,
1286         "pixel-aspect-ratio", GST_TYPE_FRACTION,
1287         info->par_n, info->par_d, NULL);
1288     if (info->flags & GST_VIDEO_FLAG_VARIABLE_FPS && info->fps_n != 0) {
1289       /* variable fps with a max-framerate */
1290       gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION, 0, 1,
1291           "max-framerate", GST_TYPE_FRACTION, info->fps_n, info->fps_d, NULL);
1292     } else {
1293       /* no variable fps or no max-framerate */
1294       gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION,
1295           info->fps_n, info->fps_d, NULL);
1296     }
1297     if (state->codec_data)
1298       gst_caps_set_simple (state->caps, "codec_data", GST_TYPE_BUFFER,
1299           state->codec_data, NULL);
1300     encoder->priv->output_state_changed = FALSE;
1301   }
1302
1303   ret = gst_pad_set_caps (encoder->srcpad, state->caps);
1304
1305   return ret;
1306 }
1307
1308 /**
1309  * gst_video_encoder_finish_frame:
1310  * @encoder: a #GstVideoEncoder
1311  * @frame: (transfer full): an encoded #GstVideoCodecFrame 
1312  *
1313  * @frame must have a valid encoded data buffer, whose metadata fields
1314  * are then appropriately set according to frame data or no buffer at
1315  * all if the frame should be dropped.
1316  * It is subsequently pushed downstream or provided to @pre_push.
1317  * In any case, the frame is considered finished and released.
1318  *
1319  * Returns: a #GstFlowReturn resulting from sending data downstream
1320  *
1321  * Since: 0.10.36
1322  */
1323 GstFlowReturn
1324 gst_video_encoder_finish_frame (GstVideoEncoder * encoder,
1325     GstVideoCodecFrame * frame)
1326 {
1327   GstVideoEncoderPrivate *priv = encoder->priv;
1328   GstFlowReturn ret = GST_FLOW_OK;
1329   GstVideoEncoderClass *encoder_class;
1330   GList *l;
1331   gboolean send_headers = FALSE;
1332   gboolean discont = (frame->presentation_frame_number == 0);
1333
1334   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1335
1336   GST_LOG_OBJECT (encoder,
1337       "finish frame fpn %d", frame->presentation_frame_number);
1338
1339   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1340
1341   if (G_UNLIKELY (priv->output_state_changed))
1342     gst_video_encoder_set_src_caps (encoder);
1343
1344   if (G_UNLIKELY (priv->output_state == NULL))
1345     goto no_output_state;
1346
1347   /* Push all pending events that arrived before this frame */
1348   for (l = priv->frames; l; l = l->next) {
1349     GstVideoCodecFrame *tmp = l->data;
1350
1351     if (tmp->events) {
1352       GList *k;
1353
1354       for (k = g_list_last (tmp->events); k; k = k->prev)
1355         gst_video_encoder_push_event (encoder, k->data);
1356       g_list_free (tmp->events);
1357       tmp->events = NULL;
1358     }
1359
1360     if (tmp == frame)
1361       break;
1362   }
1363
1364   /* no buffer data means this frame is skipped/dropped */
1365   if (!frame->output_buffer) {
1366     GST_DEBUG_OBJECT (encoder, "skipping frame %" GST_TIME_FORMAT,
1367         GST_TIME_ARGS (frame->pts));
1368     goto done;
1369   }
1370
1371   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame) && priv->force_key_unit) {
1372     GstClockTime stream_time, running_time;
1373     GstEvent *ev;
1374     ForcedKeyUnitEvent *fevt = NULL;
1375     GList *l;
1376
1377     running_time =
1378         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1379         frame->pts);
1380
1381     GST_OBJECT_LOCK (encoder);
1382     for (l = priv->force_key_unit; l; l = l->next) {
1383       ForcedKeyUnitEvent *tmp = l->data;
1384
1385       /* Skip non-pending keyunits */
1386       if (!tmp->pending)
1387         continue;
1388
1389       /* Simple case, keyunit ASAP */
1390       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1391         fevt = tmp;
1392         break;
1393       }
1394
1395       /* Event for before this frame */
1396       if (tmp->running_time <= running_time) {
1397         fevt = tmp;
1398         break;
1399       }
1400     }
1401
1402     if (fevt) {
1403       priv->force_key_unit = g_list_remove (priv->force_key_unit, fevt);
1404     }
1405     GST_OBJECT_UNLOCK (encoder);
1406
1407     if (fevt) {
1408       stream_time =
1409           gst_segment_to_stream_time (&encoder->output_segment, GST_FORMAT_TIME,
1410           frame->pts);
1411
1412       ev = gst_video_event_new_downstream_force_key_unit
1413           (frame->pts, stream_time, running_time,
1414           fevt->all_headers, fevt->count);
1415
1416       gst_video_encoder_push_event (encoder, ev);
1417
1418       if (fevt->all_headers)
1419         send_headers = TRUE;
1420
1421       GST_DEBUG_OBJECT (encoder,
1422           "Forced key unit: running-time %" GST_TIME_FORMAT
1423           ", all_headers %d, count %u",
1424           GST_TIME_ARGS (running_time), fevt->all_headers, fevt->count);
1425       forced_key_unit_event_free (fevt);
1426     }
1427   }
1428
1429   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
1430     priv->distance_from_sync = 0;
1431     GST_BUFFER_FLAG_UNSET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1432     /* For keyframes, DTS = PTS */
1433     frame->dts = frame->pts;
1434   } else {
1435     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1436   }
1437
1438   frame->distance_from_sync = priv->distance_from_sync;
1439   priv->distance_from_sync++;
1440
1441   GST_BUFFER_TIMESTAMP (frame->output_buffer) = frame->pts;
1442   GST_BUFFER_DURATION (frame->output_buffer) = frame->duration;
1443
1444   /* update rate estimate */
1445   priv->bytes += gst_buffer_get_size (frame->output_buffer);
1446   if (GST_CLOCK_TIME_IS_VALID (frame->duration)) {
1447     priv->time += frame->duration;
1448   } else {
1449     /* better none than nothing valid */
1450     priv->time = GST_CLOCK_TIME_NONE;
1451   }
1452
1453   if (G_UNLIKELY (send_headers || priv->new_headers)) {
1454     GList *tmp, *copy = NULL;
1455
1456     GST_DEBUG_OBJECT (encoder, "Sending headers");
1457
1458     /* First make all buffers metadata-writable */
1459     for (tmp = priv->headers; tmp; tmp = tmp->next) {
1460       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1461
1462       copy = g_list_append (copy, gst_buffer_make_writable (tmpbuf));
1463     }
1464     g_list_free (priv->headers);
1465     priv->headers = copy;
1466
1467     for (tmp = priv->headers; tmp; tmp = tmp->next) {
1468       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1469
1470       gst_buffer_ref (tmpbuf);
1471       priv->bytes += gst_buffer_get_size (tmpbuf);
1472       if (G_UNLIKELY (discont)) {
1473         GST_LOG_OBJECT (encoder, "marking discont");
1474         GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
1475         discont = FALSE;
1476       }
1477
1478       gst_pad_push (encoder->srcpad, tmpbuf);
1479     }
1480     priv->new_headers = FALSE;
1481   }
1482
1483   if (G_UNLIKELY (discont)) {
1484     GST_LOG_OBJECT (encoder, "marking discont");
1485     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DISCONT);
1486   }
1487
1488   if (encoder_class->pre_push)
1489     ret = encoder_class->pre_push (encoder, frame);
1490
1491   if (ret == GST_FLOW_OK)
1492     ret = gst_pad_push (encoder->srcpad, frame->output_buffer);
1493
1494   frame->output_buffer = NULL;
1495
1496 done:
1497   /* handed out */
1498   priv->frames = g_list_remove (priv->frames, frame);
1499
1500   gst_video_codec_frame_unref (frame);
1501
1502   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1503
1504   return ret;
1505
1506   /* ERRORS */
1507 no_output_state:
1508   {
1509     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1510     GST_ERROR_OBJECT (encoder, "Output state was not configured");
1511     return GST_FLOW_ERROR;
1512   }
1513 }
1514
1515 /**
1516  * gst_video_encoder_get_output_state:
1517  * @encoder: a #GstVideoEncoder
1518  *
1519  * Get the current #GstVideoCodecState
1520  *
1521  * Returns: (transfer full): #GstVideoCodecState describing format of video data.
1522  *
1523  * Since: 0.10.36
1524  */
1525 GstVideoCodecState *
1526 gst_video_encoder_get_output_state (GstVideoEncoder * encoder)
1527 {
1528   GstVideoCodecState *state;
1529
1530   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1531   state = gst_video_codec_state_ref (encoder->priv->output_state);
1532   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1533
1534   return state;
1535 }
1536
1537 /**
1538  * gst_video_encoder_set_output_state:
1539  * @encoder: a #GstVideoEncoder
1540  * @caps: (transfer full): the #GstCaps to use for the output
1541  * @reference: (allow-none) (transfer none): An optional reference @GstVideoCodecState
1542  *
1543  * Creates a new #GstVideoCodecState with the specified caps as the output state
1544  * for the encoder.
1545  * Any previously set output state on @decoder will be replaced by the newly
1546  * created one.
1547  *
1548  * The specified @caps should not contain any resolution, pixel-aspect-ratio,
1549  * framerate, codec-data, .... Those should be specified instead in the returned
1550  * #GstVideoCodecState.
1551  *
1552  * If the subclass wishes to copy over existing fields (like pixel aspect ratio,
1553  * or framerate) from an existing #GstVideoCodecState, it can be provided as a
1554  * @reference.
1555  *
1556  * If the subclass wishes to override some fields from the output state (like
1557  * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
1558  *
1559  * The new output state will only take effect (set on pads and buffers) starting
1560  * from the next call to #gst_video_encoder_finish_frame().
1561  *
1562  * Returns: (transfer full): the newly configured output state.
1563  *
1564  * Since: 0.10.36
1565  */
1566 GstVideoCodecState *
1567 gst_video_encoder_set_output_state (GstVideoEncoder * encoder, GstCaps * caps,
1568     GstVideoCodecState * reference)
1569 {
1570   GstVideoEncoderPrivate *priv = encoder->priv;
1571   GstVideoCodecState *state;
1572
1573   g_return_val_if_fail (caps != NULL, NULL);
1574
1575   state = _new_output_state (caps, reference);
1576
1577   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1578   if (priv->output_state)
1579     gst_video_codec_state_unref (priv->output_state);
1580   priv->output_state = gst_video_codec_state_ref (state);
1581
1582   priv->output_state_changed = TRUE;
1583   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1584
1585   return state;
1586 }
1587
1588 /**
1589  * gst_video_encoder_set_latency:
1590  * @encoder: a #GstVideoEncoder
1591  * @min_latency: minimum latency
1592  * @max_latency: maximum latency
1593  *
1594  * Informs baseclass of encoding latency.
1595  *
1596  * Since: 0.10.36
1597  */
1598 void
1599 gst_video_encoder_set_latency (GstVideoEncoder * encoder,
1600     GstClockTime min_latency, GstClockTime max_latency)
1601 {
1602   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
1603   g_return_if_fail (max_latency >= min_latency);
1604
1605   GST_OBJECT_LOCK (encoder);
1606   encoder->priv->min_latency = min_latency;
1607   encoder->priv->max_latency = max_latency;
1608   GST_OBJECT_UNLOCK (encoder);
1609
1610   gst_element_post_message (GST_ELEMENT_CAST (encoder),
1611       gst_message_new_latency (GST_OBJECT_CAST (encoder)));
1612 }
1613
1614 /**
1615  * gst_video_encoder_get_latency:
1616  * @encoder: a #GstVideoEncoder
1617  * @min_latency: (out) (allow-none): the configured minimum latency
1618  * @max_latency: (out) (allow-none): the configured maximum latency
1619  *
1620  * Returns the configured encoding latency.
1621  *
1622  * Since: 0.10.36
1623  */
1624 void
1625 gst_video_encoder_get_latency (GstVideoEncoder * encoder,
1626     GstClockTime * min_latency, GstClockTime * max_latency)
1627 {
1628   GST_OBJECT_LOCK (encoder);
1629   if (min_latency)
1630     *min_latency = encoder->priv->min_latency;
1631   if (max_latency)
1632     *max_latency = encoder->priv->max_latency;
1633   GST_OBJECT_UNLOCK (encoder);
1634 }
1635
1636 /**
1637  * gst_video_encoder_get_oldest_frame:
1638  * @encoder: a #GstVideoEncoder
1639  *
1640  * Get the oldest unfinished pending #GstVideoCodecFrame
1641  *
1642  * Returns: oldest unfinished pending #GstVideoCodecFrame
1643  *
1644  * Since: 0.10.36
1645  */
1646 GstVideoCodecFrame *
1647 gst_video_encoder_get_oldest_frame (GstVideoEncoder * encoder)
1648 {
1649   GList *g;
1650
1651   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1652   g = encoder->priv->frames;
1653   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1654
1655   if (g == NULL)
1656     return NULL;
1657   return (GstVideoCodecFrame *) (g->data);
1658 }
1659
1660 /**
1661  * gst_video_encoder_get_frame:
1662  * @encoder: a #GstVideoEnccoder
1663  * @frame_number: system_frame_number of a frame
1664  *
1665  * Get a pending unfinished #GstVideoCodecFrame
1666  * 
1667  * Returns: (transfer none): pending unfinished #GstVideoCodecFrame identified by @frame_number.
1668  *
1669  * Since: 0.10.36
1670  */
1671 GstVideoCodecFrame *
1672 gst_video_encoder_get_frame (GstVideoEncoder * encoder, int frame_number)
1673 {
1674   GList *g;
1675   GstVideoCodecFrame *frame = NULL;
1676
1677   GST_DEBUG_OBJECT (encoder, "frame_number : %d", frame_number);
1678
1679   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1680   for (g = encoder->priv->frames; g; g = g->next) {
1681     GstVideoCodecFrame *tmp = g->data;
1682
1683     if (tmp->system_frame_number == frame_number) {
1684       frame = tmp;
1685       break;
1686     }
1687   }
1688   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1689
1690   return frame;
1691 }