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