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