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