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