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