video: Document buffer ownership of the GstVideoCodecFrame more explicit
[platform/upstream/gstreamer.git] / gst-libs / gst / video / gstvideoencoder.c
1 /* GStreamer
2  * Copyright (C) 2008 David Schleef <ds@schleef.org>
3  * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>.
4  * Copyright (C) 2011 Nokia Corporation. All rights reserved.
5  *   Contact: Stefan Kost <stefan.kost@nokia.com>
6  * Copyright (C) 2012 Collabora Ltd.
7  *      Author : Edward Hervey <edward@collabora.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 /**
26  * SECTION:gstvideoencoder
27  * @short_description: Base class for video encoders
28  * @see_also:
29  *
30  * This base class is for video encoders turning raw video into
31  * encoded video data.
32  *
33  * GstVideoEncoder and subclass should cooperate as follows.
34  * <orderedlist>
35  * <listitem>
36  *   <itemizedlist><title>Configuration</title>
37  *   <listitem><para>
38  *     Initially, GstVideoEncoder calls @start when the encoder element
39  *     is activated, which allows subclass to perform any global setup.
40  *   </para></listitem>
41  *   <listitem><para>
42  *     GstVideoEncoder calls @set_format to inform subclass of the format
43  *     of input video data that it is about to receive.  Subclass should
44  *     setup for encoding and configure base class as appropriate
45  *     (e.g. latency). While unlikely, it might be called more than once,
46  *     if changing input parameters require reconfiguration.  Baseclass
47  *     will ensure that processing of current configuration is finished.
48  *   </para></listitem>
49  *   <listitem><para>
50  *     GstVideoEncoder calls @stop at end of all processing.
51  *   </para></listitem>
52  *   </itemizedlist>
53  * </listitem>
54  * <listitem>
55  *   <itemizedlist>
56  *   <title>Data processing</title>
57  *     <listitem><para>
58  *       Base class collects input data and metadata into a frame and hands
59  *       this to subclass' @handle_frame.
60  *     </para></listitem>
61  *     <listitem><para>
62  *       If codec processing results in encoded data, subclass should call
63  *       @gst_video_encoder_finish_frame to have encoded data pushed
64  *       downstream.
65  *     </para></listitem>
66  *     <listitem><para>
67  *       If implemented, baseclass calls subclass @pre_push just prior to
68  *       pushing to allow subclasses to modify some metadata on the buffer.
69  *       If it returns GST_FLOW_OK, the buffer is pushed downstream.
70  *     </para></listitem>
71  *     <listitem><para>
72  *       GstVideoEncoderClass will handle both srcpad and sinkpad events.
73  *       Sink events will be passed to subclass if @event callback has been
74  *       provided.
75  *     </para></listitem>
76  *   </itemizedlist>
77  * </listitem>
78  * <listitem>
79  *   <itemizedlist><title>Shutdown phase</title>
80  *   <listitem><para>
81  *     GstVideoEncoder class calls @stop to inform the subclass that data
82  *     parsing will be stopped.
83  *   </para></listitem>
84  *   </itemizedlist>
85  * </listitem>
86  * </orderedlist>
87  *
88  * Subclass is responsible for providing pad template caps for
89  * source and sink pads. The pads need to be named "sink" and "src". It should
90  * also be able to provide fixed src pad caps in @getcaps by the time it calls
91  * @gst_video_encoder_finish_frame.
92  *
93  * Things that subclass need to take care of:
94  * <itemizedlist>
95  *   <listitem><para>Provide pad templates</para></listitem>
96  *   <listitem><para>
97  *      Provide source pad caps before pushing the first buffer
98  *   </para></listitem>
99  *   <listitem><para>
100  *      Accept data in @handle_frame and provide encoded results to
101  *      @gst_video_encoder_finish_frame.
102  *   </para></listitem>
103  * </itemizedlist>
104  *
105  */
106
107 #ifdef HAVE_CONFIG_H
108 #include "config.h"
109 #endif
110
111 /* TODO
112  *
113  * * Change _set_output_format() to steal the reference of the provided caps
114  * * Calculate actual latency based on input/output timestamp/frame_number
115  *   and if it exceeds the recorded one, save it and emit a GST_MESSAGE_LATENCY
116  */
117
118 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
119  * with newer GLib versions (>= 2.31.0) */
120 #define GLIB_DISABLE_DEPRECATION_WARNINGS
121
122 #include "gstvideoencoder.h"
123 #include "gstvideoutils.h"
124
125 #include <gst/video/gstvideometa.h>
126
127 #include <string.h>
128
129 GST_DEBUG_CATEGORY (videoencoder_debug);
130 #define GST_CAT_DEFAULT videoencoder_debug
131
132 #define GST_VIDEO_ENCODER_GET_PRIVATE(obj)  \
133     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_VIDEO_ENCODER, \
134         GstVideoEncoderPrivate))
135
136 struct _GstVideoEncoderPrivate
137 {
138   guint64 presentation_frame_number;
139   int distance_from_sync;
140
141   /* FIXME : (and introduce a context ?) */
142   gboolean drained;
143   gboolean at_eos;
144
145   gint64 min_latency;
146   gint64 max_latency;
147
148   GList *current_frame_events;
149
150   GList *headers;
151   gboolean new_headers;         /* Whether new headers were just set */
152
153   GList *force_key_unit;        /* List of pending forced keyunits */
154
155   guint64 system_frame_number;
156
157   GList *frames;                /* Protected with OBJECT_LOCK */
158   GstVideoCodecState *input_state;
159   GstVideoCodecState *output_state;
160   gboolean output_state_changed;
161
162   gint64 bytes;
163   gint64 time;
164 };
165
166 typedef struct _ForcedKeyUnitEvent ForcedKeyUnitEvent;
167 struct _ForcedKeyUnitEvent
168 {
169   GstClockTime running_time;
170   gboolean pending;             /* TRUE if this was requested already */
171   gboolean all_headers;
172   guint count;
173 };
174
175 static void
176 forced_key_unit_event_free (ForcedKeyUnitEvent * evt)
177 {
178   g_slice_free (ForcedKeyUnitEvent, evt);
179 }
180
181 static ForcedKeyUnitEvent *
182 forced_key_unit_event_new (GstClockTime running_time, gboolean all_headers,
183     guint count)
184 {
185   ForcedKeyUnitEvent *evt = g_slice_new0 (ForcedKeyUnitEvent);
186
187   evt->running_time = running_time;
188   evt->all_headers = all_headers;
189   evt->count = count;
190
191   return evt;
192 }
193
194 static GstElementClass *parent_class = NULL;
195 static void gst_video_encoder_class_init (GstVideoEncoderClass * klass);
196 static void gst_video_encoder_init (GstVideoEncoder * enc,
197     GstVideoEncoderClass * klass);
198
199 static void gst_video_encoder_finalize (GObject * object);
200
201 static gboolean gst_video_encoder_setcaps (GstVideoEncoder * enc,
202     GstCaps * caps);
203 static GstCaps *gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder,
204     GstCaps * filter);
205 static gboolean gst_video_encoder_src_event (GstPad * pad, GstObject * parent,
206     GstEvent * event);
207 static gboolean gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
208     GstEvent * event);
209 static GstFlowReturn gst_video_encoder_chain (GstPad * pad, GstObject * parent,
210     GstBuffer * buf);
211 static GstStateChangeReturn gst_video_encoder_change_state (GstElement *
212     element, GstStateChange transition);
213 static gboolean gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
214     GstQuery * query);
215 static gboolean gst_video_encoder_src_query (GstPad * pad, GstObject * parent,
216     GstQuery * query);
217 static GstVideoCodecFrame *gst_video_encoder_new_frame (GstVideoEncoder *
218     encoder, GstBuffer * buf, GstClockTime pts, GstClockTime dts,
219     GstClockTime duration);
220
221 static gboolean gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
222     GstEvent * event);
223 static gboolean gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
224     GstEvent * event);
225 static gboolean gst_video_encoder_propose_allocation_default (GstVideoEncoder *
226     encoder, GstQuery * query);
227
228 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
229  * method to get to the padtemplates */
230 GType
231 gst_video_encoder_get_type (void)
232 {
233   static volatile gsize type = 0;
234
235   if (g_once_init_enter (&type)) {
236     GType _type;
237     static const GTypeInfo info = {
238       sizeof (GstVideoEncoderClass),
239       NULL,
240       NULL,
241       (GClassInitFunc) gst_video_encoder_class_init,
242       NULL,
243       NULL,
244       sizeof (GstVideoEncoder),
245       0,
246       (GInstanceInitFunc) gst_video_encoder_init,
247     };
248     const GInterfaceInfo preset_interface_info = {
249       NULL,                     /* interface_init */
250       NULL,                     /* interface_finalize */
251       NULL                      /* interface_data */
252     };
253
254     _type = g_type_register_static (GST_TYPE_ELEMENT,
255         "GstVideoEncoder", &info, G_TYPE_FLAG_ABSTRACT);
256     g_type_add_interface_static (_type, GST_TYPE_PRESET,
257         &preset_interface_info);
258     g_once_init_leave (&type, _type);
259   }
260   return type;
261 }
262
263 static void
264 gst_video_encoder_class_init (GstVideoEncoderClass * klass)
265 {
266   GObjectClass *gobject_class;
267   GstElementClass *gstelement_class;
268
269   gobject_class = G_OBJECT_CLASS (klass);
270   gstelement_class = GST_ELEMENT_CLASS (klass);
271
272   GST_DEBUG_CATEGORY_INIT (videoencoder_debug, "videoencoder", 0,
273       "Base Video Encoder");
274
275   parent_class = g_type_class_peek_parent (klass);
276
277   g_type_class_add_private (klass, sizeof (GstVideoEncoderPrivate));
278
279   gobject_class->finalize = gst_video_encoder_finalize;
280
281   gstelement_class->change_state =
282       GST_DEBUG_FUNCPTR (gst_video_encoder_change_state);
283
284   klass->sink_event = gst_video_encoder_sink_event_default;
285   klass->src_event = gst_video_encoder_src_event_default;
286   klass->propose_allocation = gst_video_encoder_propose_allocation_default;
287 }
288
289 static void
290 gst_video_encoder_reset (GstVideoEncoder * encoder)
291 {
292   GstVideoEncoderPrivate *priv = encoder->priv;
293   GList *g;
294
295   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
296
297   priv->presentation_frame_number = 0;
298   priv->distance_from_sync = 0;
299
300   g_list_foreach (priv->force_key_unit, (GFunc) forced_key_unit_event_free,
301       NULL);
302   g_list_free (priv->force_key_unit);
303   priv->force_key_unit = NULL;
304
305   priv->drained = TRUE;
306   priv->min_latency = 0;
307   priv->max_latency = 0;
308
309   g_list_foreach (priv->headers, (GFunc) gst_event_unref, NULL);
310   g_list_free (priv->headers);
311   priv->headers = NULL;
312   priv->new_headers = FALSE;
313
314   g_list_foreach (priv->current_frame_events, (GFunc) gst_event_unref, NULL);
315   g_list_free (priv->current_frame_events);
316   priv->current_frame_events = NULL;
317
318   for (g = priv->frames; g; g = g->next) {
319     gst_video_codec_frame_unref ((GstVideoCodecFrame *) g->data);
320   }
321   g_list_free (priv->frames);
322   priv->frames = NULL;
323
324   priv->bytes = 0;
325   priv->time = 0;
326
327   if (priv->input_state)
328     gst_video_codec_state_unref (priv->input_state);
329   priv->input_state = NULL;
330   if (priv->output_state)
331     gst_video_codec_state_unref (priv->output_state);
332   priv->output_state = NULL;
333
334   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
335 }
336
337 static void
338 gst_video_encoder_init (GstVideoEncoder * encoder, GstVideoEncoderClass * klass)
339 {
340   GstVideoEncoderPrivate *priv;
341   GstPadTemplate *pad_template;
342   GstPad *pad;
343
344   GST_DEBUG_OBJECT (encoder, "gst_video_encoder_init");
345
346   priv = encoder->priv = GST_VIDEO_ENCODER_GET_PRIVATE (encoder);
347
348   pad_template =
349       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
350   g_return_if_fail (pad_template != NULL);
351
352   encoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
353
354   gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_video_encoder_chain));
355   gst_pad_set_event_function (pad,
356       GST_DEBUG_FUNCPTR (gst_video_encoder_sink_event));
357   gst_pad_set_query_function (pad,
358       GST_DEBUG_FUNCPTR (gst_video_encoder_sink_query));
359   gst_element_add_pad (GST_ELEMENT (encoder), encoder->sinkpad);
360
361   pad_template =
362       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
363   g_return_if_fail (pad_template != NULL);
364
365   encoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
366
367   gst_pad_set_query_function (pad,
368       GST_DEBUG_FUNCPTR (gst_video_encoder_src_query));
369   gst_pad_set_event_function (pad,
370       GST_DEBUG_FUNCPTR (gst_video_encoder_src_event));
371   gst_element_add_pad (GST_ELEMENT (encoder), encoder->srcpad);
372
373   gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
374   gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
375
376   g_rec_mutex_init (&encoder->stream_lock);
377
378   priv->at_eos = FALSE;
379   priv->headers = NULL;
380   priv->new_headers = FALSE;
381
382   gst_video_encoder_reset (encoder);
383 }
384
385 static gboolean
386 gst_video_encoded_video_convert (gint64 bytes, gint64 time,
387     GstFormat src_format, gint64 src_value, GstFormat * dest_format,
388     gint64 * dest_value)
389 {
390   gboolean res = FALSE;
391
392   g_return_val_if_fail (dest_format != NULL, FALSE);
393   g_return_val_if_fail (dest_value != NULL, FALSE);
394
395   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
396           src_value == -1)) {
397     if (dest_value)
398       *dest_value = src_value;
399     return TRUE;
400   }
401
402   if (bytes <= 0 || time <= 0) {
403     GST_DEBUG ("not enough metadata yet to convert");
404     goto exit;
405   }
406
407   switch (src_format) {
408     case GST_FORMAT_BYTES:
409       switch (*dest_format) {
410         case GST_FORMAT_TIME:
411           *dest_value = gst_util_uint64_scale (src_value, time, bytes);
412           res = TRUE;
413           break;
414         default:
415           res = FALSE;
416       }
417       break;
418     case GST_FORMAT_TIME:
419       switch (*dest_format) {
420         case GST_FORMAT_BYTES:
421           *dest_value = gst_util_uint64_scale (src_value, bytes, time);
422           res = TRUE;
423           break;
424         default:
425           res = FALSE;
426       }
427       break;
428     default:
429       GST_DEBUG ("unhandled conversion from %d to %d", src_format,
430           *dest_format);
431       res = FALSE;
432   }
433
434 exit:
435   return res;
436 }
437
438 /**
439  * gst_video_encoder_set_headers:
440  * @encoder: a #GstVideoEncoder
441  * @headers: (transfer full) (element-type GstBuffer): a list of #GstBuffer containing the codec header
442  *
443  * Set the codec headers to be sent downstream whenever requested.
444  *
445  * Since: 0.10.36
446  */
447 void
448 gst_video_encoder_set_headers (GstVideoEncoder * video_encoder, GList * headers)
449 {
450   GST_VIDEO_ENCODER_STREAM_LOCK (video_encoder);
451
452   GST_DEBUG_OBJECT (video_encoder, "new headers %p", headers);
453   if (video_encoder->priv->headers) {
454     g_list_foreach (video_encoder->priv->headers, (GFunc) gst_buffer_unref,
455         NULL);
456     g_list_free (video_encoder->priv->headers);
457   }
458   video_encoder->priv->headers = headers;
459   video_encoder->priv->new_headers = TRUE;
460
461   GST_VIDEO_ENCODER_STREAM_UNLOCK (video_encoder);
462 }
463
464 static gboolean
465 gst_video_encoder_drain (GstVideoEncoder * enc)
466 {
467   GstVideoEncoderPrivate *priv;
468   GstVideoEncoderClass *enc_class;
469   gboolean ret = TRUE;
470
471   enc_class = GST_VIDEO_ENCODER_GET_CLASS (enc);
472   priv = enc->priv;
473
474   GST_DEBUG_OBJECT (enc, "draining");
475
476   if (priv->drained) {
477     GST_DEBUG_OBJECT (enc, "already drained");
478     return TRUE;
479   }
480
481   if (enc_class->reset) {
482     GST_DEBUG_OBJECT (enc, "requesting subclass to finish");
483     ret = enc_class->reset (enc, TRUE);
484   }
485   /* everything should be away now */
486   if (priv->frames) {
487     /* not fatal/impossible though if subclass/enc eats stuff */
488     g_list_foreach (priv->frames, (GFunc) gst_video_codec_frame_unref, NULL);
489     g_list_free (priv->frames);
490     priv->frames = NULL;
491   }
492
493   return ret;
494 }
495
496 static GstVideoCodecState *
497 _new_output_state (GstCaps * caps, GstVideoCodecState * reference)
498 {
499   GstVideoCodecState *state;
500
501   state = g_slice_new0 (GstVideoCodecState);
502   state->ref_count = 1;
503   gst_video_info_init (&state->info);
504   gst_video_info_set_format (&state->info, GST_VIDEO_FORMAT_ENCODED, 0, 0);
505
506   state->caps = caps;
507
508   if (reference) {
509     GstVideoInfo *tgt, *ref;
510
511     tgt = &state->info;
512     ref = &reference->info;
513
514     /* Copy over extra fields from reference state */
515     tgt->interlace_mode = ref->interlace_mode;
516     tgt->flags = ref->flags;
517     tgt->width = ref->width;
518     tgt->height = ref->height;
519     tgt->chroma_site = ref->chroma_site;
520     tgt->colorimetry = ref->colorimetry;
521     tgt->par_n = ref->par_n;
522     tgt->par_d = ref->par_d;
523     tgt->fps_n = ref->fps_n;
524     tgt->fps_d = ref->fps_d;
525   }
526
527   return state;
528 }
529
530 static GstVideoCodecState *
531 _new_input_state (GstCaps * caps)
532 {
533   GstVideoCodecState *state;
534
535   state = g_slice_new0 (GstVideoCodecState);
536   state->ref_count = 1;
537   gst_video_info_init (&state->info);
538   if (G_UNLIKELY (!gst_video_info_from_caps (&state->info, caps)))
539     goto parse_fail;
540   state->caps = gst_caps_ref (caps);
541
542   return state;
543
544 parse_fail:
545   {
546     g_slice_free (GstVideoCodecState, state);
547     return NULL;
548   }
549 }
550
551 static gboolean
552 gst_video_encoder_setcaps (GstVideoEncoder * encoder, GstCaps * caps)
553 {
554   GstVideoEncoderClass *encoder_class;
555   GstVideoCodecState *state;
556   gboolean ret;
557   gboolean samecaps = FALSE;
558
559   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
560
561   /* subclass should do something here ... */
562   g_return_val_if_fail (encoder_class->set_format != NULL, FALSE);
563
564   GST_DEBUG_OBJECT (encoder, "setcaps %" GST_PTR_FORMAT, caps);
565
566   state = _new_input_state (caps);
567   if (G_UNLIKELY (!state))
568     goto parse_fail;
569
570   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
571
572   if (encoder->priv->input_state)
573     samecaps =
574         gst_video_info_is_equal (&state->info,
575         &encoder->priv->input_state->info);
576
577   if (!samecaps) {
578     /* arrange draining pending frames */
579     gst_video_encoder_drain (encoder);
580
581     /* and subclass should be ready to configure format at any time around */
582     ret = encoder_class->set_format (encoder, state);
583     if (ret) {
584       if (encoder->priv->input_state)
585         gst_video_codec_state_unref (encoder->priv->input_state);
586       encoder->priv->input_state = state;
587     } else
588       gst_video_codec_state_unref (state);
589   } else {
590     /* no need to stir things up */
591     GST_DEBUG_OBJECT (encoder,
592         "new video format identical to configured format");
593     gst_video_codec_state_unref (state);
594     ret = TRUE;
595   }
596
597   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
598
599   if (!ret)
600     GST_WARNING_OBJECT (encoder, "rejected caps %" GST_PTR_FORMAT, caps);
601
602   return ret;
603
604 parse_fail:
605   {
606     GST_WARNING_OBJECT (encoder, "Failed to parse caps");
607     return FALSE;
608   }
609 }
610
611 /**
612  * gst_video_encoder_proxy_getcaps:
613  * @enc: a #GstVideoEncoder
614  * @caps: initial caps
615  *
616  * Returns caps that express @caps (or sink template caps if @caps == NULL)
617  * restricted to resolution/format/... combinations supported by downstream
618  * elements (e.g. muxers).
619  *
620  * Returns: a #GstCaps owned by caller
621  *
622  * Since: 0.10.36
623  */
624 GstCaps *
625 gst_video_encoder_proxy_getcaps (GstVideoEncoder * encoder, GstCaps * caps,
626     GstCaps * filter)
627 {
628   GstCaps *templ_caps;
629   GstCaps *allowed;
630   GstCaps *fcaps, *filter_caps;
631   gint i, j;
632
633   /* Allow downstream to specify width/height/framerate/PAR constraints
634    * and forward them upstream for video converters to handle
635    */
636   templ_caps =
637       caps ? gst_caps_ref (caps) :
638       gst_pad_get_pad_template_caps (encoder->sinkpad);
639   allowed = gst_pad_get_allowed_caps (encoder->srcpad);
640
641   if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
642     fcaps = templ_caps;
643     goto done;
644   }
645
646   GST_LOG_OBJECT (encoder, "template caps %" GST_PTR_FORMAT, templ_caps);
647   GST_LOG_OBJECT (encoder, "allowed caps %" GST_PTR_FORMAT, allowed);
648
649   filter_caps = gst_caps_new_empty ();
650
651   for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
652     GQuark q_name =
653         gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
654
655     for (j = 0; j < gst_caps_get_size (allowed); j++) {
656       const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
657       const GValue *val;
658       GstStructure *s;
659
660       s = gst_structure_new_id_empty (q_name);
661       if ((val = gst_structure_get_value (allowed_s, "width")))
662         gst_structure_set_value (s, "width", val);
663       if ((val = gst_structure_get_value (allowed_s, "height")))
664         gst_structure_set_value (s, "height", val);
665       if ((val = gst_structure_get_value (allowed_s, "framerate")))
666         gst_structure_set_value (s, "framerate", val);
667       if ((val = gst_structure_get_value (allowed_s, "pixel-aspect-ratio")))
668         gst_structure_set_value (s, "pixel-aspect-ratio", val);
669
670       filter_caps = gst_caps_merge_structure (filter_caps, s);
671     }
672   }
673
674   fcaps = gst_caps_intersect (filter_caps, templ_caps);
675   gst_caps_unref (filter_caps);
676   gst_caps_unref (templ_caps);
677
678   if (filter) {
679     GST_LOG_OBJECT (encoder, "intersecting with %" GST_PTR_FORMAT, filter);
680     filter_caps = gst_caps_intersect (fcaps, filter);
681     gst_caps_unref (fcaps);
682     fcaps = filter_caps;
683   }
684
685 done:
686   gst_caps_replace (&allowed, NULL);
687
688   GST_LOG_OBJECT (encoder, "proxy caps %" GST_PTR_FORMAT, fcaps);
689
690   return fcaps;
691 }
692
693 static GstCaps *
694 gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder, GstCaps * filter)
695 {
696   GstVideoEncoderClass *klass;
697   GstCaps *caps;
698
699   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
700
701   if (klass->getcaps)
702     caps = klass->getcaps (encoder, filter);
703   else
704     caps = gst_video_encoder_proxy_getcaps (encoder, NULL, filter);
705
706   GST_LOG_OBJECT (encoder, "Returning caps %" GST_PTR_FORMAT, caps);
707
708   return caps;
709 }
710
711 static gboolean
712 gst_video_encoder_propose_allocation_default (GstVideoEncoder * encoder,
713     GstQuery * query)
714 {
715   return TRUE;
716 }
717
718 static gboolean
719 gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
720     GstQuery * query)
721 {
722   GstVideoEncoder *encoder;
723   gboolean res = FALSE;
724
725   encoder = GST_VIDEO_ENCODER (parent);
726
727   switch (GST_QUERY_TYPE (query)) {
728     case GST_QUERY_CAPS:
729     {
730       GstCaps *filter, *caps;
731
732       gst_query_parse_caps (query, &filter);
733       caps = gst_video_encoder_sink_getcaps (encoder, filter);
734       gst_query_set_caps_result (query, caps);
735       gst_caps_unref (caps);
736       res = TRUE;
737       break;
738     }
739     case GST_QUERY_ALLOCATION:
740     {
741       GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
742
743       if (klass->propose_allocation)
744         res = klass->propose_allocation (encoder, query);
745       break;
746     }
747     default:
748       res = gst_pad_query_default (pad, parent, query);
749       break;
750   }
751   return res;
752 }
753
754 static void
755 gst_video_encoder_finalize (GObject * object)
756 {
757   GstVideoEncoder *encoder;
758
759   GST_DEBUG_OBJECT (object, "finalize");
760
761   encoder = GST_VIDEO_ENCODER (object);
762   if (encoder->priv->headers) {
763     g_list_foreach (encoder->priv->headers, (GFunc) gst_buffer_unref, NULL);
764     g_list_free (encoder->priv->headers);
765   }
766   g_rec_mutex_clear (&encoder->stream_lock);
767
768   G_OBJECT_CLASS (parent_class)->finalize (object);
769 }
770
771 static gboolean
772 gst_video_encoder_push_event (GstVideoEncoder * encoder, GstEvent * event)
773 {
774   switch (GST_EVENT_TYPE (event)) {
775     case GST_EVENT_SEGMENT:
776     {
777       GstSegment segment;
778
779       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
780
781       gst_event_copy_segment (event, &segment);
782
783       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
784
785       if (segment.format != GST_FORMAT_TIME) {
786         GST_DEBUG_OBJECT (encoder, "received non TIME segment");
787         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
788         break;
789       }
790
791       encoder->output_segment = segment;
792       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
793       break;
794     }
795     default:
796       break;
797   }
798
799   return gst_pad_push_event (encoder->srcpad, event);
800 }
801
802 static gboolean
803 gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
804     GstEvent * event)
805 {
806   GstVideoEncoderClass *encoder_class;
807   gboolean ret = FALSE;
808
809   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
810
811   switch (GST_EVENT_TYPE (event)) {
812     case GST_EVENT_CAPS:
813     {
814       GstCaps *caps;
815
816       gst_event_parse_caps (event, &caps);
817       ret = gst_video_encoder_setcaps (encoder, caps);
818       gst_event_unref (event);
819       event = NULL;
820       break;
821     }
822     case GST_EVENT_EOS:
823     {
824       GstFlowReturn flow_ret;
825
826       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
827       encoder->priv->at_eos = TRUE;
828
829       if (encoder_class->finish) {
830         flow_ret = encoder_class->finish (encoder);
831       } else {
832         flow_ret = GST_FLOW_OK;
833       }
834
835       ret = (flow_ret == GST_FLOW_OK);
836       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
837       break;
838     }
839     case GST_EVENT_SEGMENT:
840     {
841       GstSegment segment;
842
843       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
844
845       gst_event_copy_segment (event, &segment);
846
847       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
848
849       if (segment.format != GST_FORMAT_TIME) {
850         GST_DEBUG_OBJECT (encoder, "received non TIME newsegment");
851         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
852         break;
853       }
854
855       encoder->priv->at_eos = FALSE;
856
857       encoder->input_segment = segment;
858       ret = TRUE;
859       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
860       break;
861     }
862     case GST_EVENT_CUSTOM_DOWNSTREAM:
863     {
864       if (gst_video_event_is_force_key_unit (event)) {
865         GstClockTime running_time;
866         gboolean all_headers;
867         guint count;
868
869         if (gst_video_event_parse_downstream_force_key_unit (event,
870                 NULL, NULL, &running_time, &all_headers, &count)) {
871           ForcedKeyUnitEvent *fevt;
872
873           GST_OBJECT_LOCK (encoder);
874           fevt = forced_key_unit_event_new (running_time, all_headers, count);
875           encoder->priv->force_key_unit =
876               g_list_append (encoder->priv->force_key_unit, fevt);
877           GST_OBJECT_UNLOCK (encoder);
878
879           GST_DEBUG_OBJECT (encoder,
880               "force-key-unit event: running-time %" GST_TIME_FORMAT
881               ", all_headers %d, count %u",
882               GST_TIME_ARGS (running_time), all_headers, count);
883         }
884         gst_event_unref (event);
885         event = NULL;
886         ret = TRUE;
887       }
888       break;
889     }
890     default:
891       break;
892   }
893
894   /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
895    * For EOS this is required because no buffer or serialized event
896    * will come after EOS and nothing could trigger another
897    * _finish_frame() call.   *
898    * If the subclass handles sending of EOS manually it can simply
899    * not chain up to the parent class' event handler
900    *
901    * For FLUSH_STOP this is required because it is expected
902    * to be forwarded immediately and no buffers are queued anyway.
903    */
904   if (event) {
905     if (!GST_EVENT_IS_SERIALIZED (event)
906         || GST_EVENT_TYPE (event) == GST_EVENT_EOS
907         || GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_STOP) {
908       ret = gst_video_encoder_push_event (encoder, event);
909     } else {
910       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
911       encoder->priv->current_frame_events =
912           g_list_prepend (encoder->priv->current_frame_events, event);
913       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
914       ret = TRUE;
915     }
916   }
917
918   return ret;
919 }
920
921 static gboolean
922 gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
923     GstEvent * event)
924 {
925   GstVideoEncoder *enc;
926   GstVideoEncoderClass *klass;
927   gboolean ret = TRUE;
928
929   enc = GST_VIDEO_ENCODER (parent);
930   klass = GST_VIDEO_ENCODER_GET_CLASS (enc);
931
932   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
933       GST_EVENT_TYPE_NAME (event));
934
935   if (klass->sink_event)
936     ret = klass->sink_event (enc, event);
937
938   return ret;
939 }
940
941 static gboolean
942 gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
943     GstEvent * event)
944 {
945   gboolean ret = FALSE;
946
947   switch (GST_EVENT_TYPE (event)) {
948     case GST_EVENT_CUSTOM_UPSTREAM:
949     {
950       if (gst_video_event_is_force_key_unit (event)) {
951         GstClockTime running_time;
952         gboolean all_headers;
953         guint count;
954
955         if (gst_video_event_parse_upstream_force_key_unit (event,
956                 &running_time, &all_headers, &count)) {
957           ForcedKeyUnitEvent *fevt;
958
959           GST_OBJECT_LOCK (encoder);
960           fevt = forced_key_unit_event_new (running_time, all_headers, count);
961           encoder->priv->force_key_unit =
962               g_list_append (encoder->priv->force_key_unit, fevt);
963           GST_OBJECT_UNLOCK (encoder);
964
965           GST_DEBUG_OBJECT (encoder,
966               "force-key-unit event: running-time %" GST_TIME_FORMAT
967               ", all_headers %d, count %u",
968               GST_TIME_ARGS (running_time), all_headers, count);
969         }
970         gst_event_unref (event);
971         event = NULL;
972         ret = TRUE;
973       }
974       break;
975     }
976     default:
977       break;
978   }
979
980   if (event)
981     ret =
982         gst_pad_event_default (encoder->srcpad, GST_OBJECT_CAST (encoder),
983         event);
984
985   return ret;
986 }
987
988 static gboolean
989 gst_video_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
990 {
991   GstVideoEncoder *encoder;
992   GstVideoEncoderClass *klass;
993   gboolean ret = FALSE;
994
995   encoder = GST_VIDEO_ENCODER (parent);
996   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
997
998   GST_LOG_OBJECT (encoder, "handling event: %" GST_PTR_FORMAT, event);
999
1000   if (klass->src_event)
1001     ret = klass->src_event (encoder, event);
1002
1003   return ret;
1004 }
1005
1006 static gboolean
1007 gst_video_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1008 {
1009   GstVideoEncoderPrivate *priv;
1010   GstVideoEncoder *enc;
1011   gboolean res;
1012
1013   enc = GST_VIDEO_ENCODER (parent);
1014   priv = enc->priv;
1015
1016   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1017
1018   switch (GST_QUERY_TYPE (query)) {
1019     case GST_QUERY_CONVERT:
1020     {
1021       GstFormat src_fmt, dest_fmt;
1022       gint64 src_val, dest_val;
1023
1024       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1025       res =
1026           gst_video_encoded_video_convert (priv->bytes, priv->time, src_fmt,
1027           src_val, &dest_fmt, &dest_val);
1028       if (!res)
1029         goto error;
1030       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1031       break;
1032     }
1033     case GST_QUERY_LATENCY:
1034     {
1035       gboolean live;
1036       GstClockTime min_latency, max_latency;
1037
1038       res = gst_pad_peer_query (enc->sinkpad, query);
1039       if (res) {
1040         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1041         GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1042             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1043             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1044
1045         GST_OBJECT_LOCK (enc);
1046         min_latency += priv->min_latency;
1047         if (enc->priv->max_latency == GST_CLOCK_TIME_NONE) {
1048           max_latency = GST_CLOCK_TIME_NONE;
1049         } else if (max_latency != GST_CLOCK_TIME_NONE) {
1050           max_latency += enc->priv->max_latency;
1051         }
1052         GST_OBJECT_UNLOCK (enc);
1053
1054         gst_query_set_latency (query, live, min_latency, max_latency);
1055       }
1056     }
1057       break;
1058     default:
1059       res = gst_pad_query_default (pad, parent, query);
1060   }
1061   return res;
1062
1063 error:
1064   GST_DEBUG_OBJECT (enc, "query failed");
1065   return res;
1066 }
1067
1068 static GstVideoCodecFrame *
1069 gst_video_encoder_new_frame (GstVideoEncoder * encoder, GstBuffer * buf,
1070     GstClockTime pts, GstClockTime dts, GstClockTime duration)
1071 {
1072   GstVideoEncoderPrivate *priv = encoder->priv;
1073   GstVideoCodecFrame *frame;
1074
1075   frame = g_slice_new0 (GstVideoCodecFrame);
1076
1077   frame->ref_count = 1;
1078
1079   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1080   frame->system_frame_number = priv->system_frame_number;
1081   priv->system_frame_number++;
1082
1083   frame->presentation_frame_number = priv->presentation_frame_number;
1084   priv->presentation_frame_number++;
1085   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1086
1087   frame->events = priv->current_frame_events;
1088   priv->current_frame_events = NULL;
1089   frame->input_buffer = buf;
1090   frame->pts = pts;
1091   frame->dts = dts;
1092   frame->duration = duration;
1093
1094   return frame;
1095 }
1096
1097
1098 static GstFlowReturn
1099 gst_video_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1100 {
1101   GstVideoEncoder *encoder;
1102   GstVideoEncoderPrivate *priv;
1103   GstVideoEncoderClass *klass;
1104   GstVideoCodecFrame *frame;
1105   GstClockTime pts, dts, duration;
1106   GstFlowReturn ret = GST_FLOW_OK;
1107   guint64 start, stop, cstart, cstop;
1108
1109   encoder = GST_VIDEO_ENCODER (parent);
1110   priv = encoder->priv;
1111   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1112
1113   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1114
1115   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1116
1117   pts = GST_BUFFER_PTS (buf);
1118   dts = GST_BUFFER_DTS (buf);
1119   duration = GST_BUFFER_DURATION (buf);
1120
1121   GST_LOG_OBJECT (encoder,
1122       "received buffer of size %" G_GSIZE_FORMAT " with PTS %" GST_TIME_FORMAT
1123       ", PTS %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1124       gst_buffer_get_size (buf), GST_TIME_ARGS (pts), GST_TIME_ARGS (dts),
1125       GST_TIME_ARGS (duration));
1126
1127   if (priv->at_eos) {
1128     ret = GST_FLOW_EOS;
1129     goto done;
1130   }
1131
1132   start = pts;
1133   if (GST_CLOCK_TIME_IS_VALID (duration))
1134     stop = start + duration;
1135   else
1136     stop = GST_CLOCK_TIME_NONE;
1137
1138   /* Drop buffers outside of segment */
1139   if (!gst_segment_clip (&encoder->output_segment,
1140           GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
1141     GST_DEBUG_OBJECT (encoder, "clipping to segment dropped frame");
1142     gst_buffer_unref (buf);
1143     goto done;
1144   }
1145
1146   frame =
1147       gst_video_encoder_new_frame (encoder, buf, cstart, dts, cstop - cstart);
1148
1149   GST_OBJECT_LOCK (encoder);
1150   if (priv->force_key_unit) {
1151     ForcedKeyUnitEvent *fevt = NULL;
1152     GstClockTime running_time;
1153     GList *l;
1154
1155     running_time =
1156         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1157         cstart);
1158
1159     for (l = priv->force_key_unit; l; l = l->next) {
1160       ForcedKeyUnitEvent *tmp = l->data;
1161
1162       /* Skip pending keyunits */
1163       if (tmp->pending)
1164         continue;
1165
1166       /* Simple case, keyunit ASAP */
1167       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1168         fevt = tmp;
1169         break;
1170       }
1171
1172       /* Event for before this frame */
1173       if (tmp->running_time <= running_time) {
1174         fevt = tmp;
1175         break;
1176       }
1177     }
1178
1179     if (fevt) {
1180       GST_DEBUG_OBJECT (encoder,
1181           "Forcing a key unit at running time %" GST_TIME_FORMAT,
1182           GST_TIME_ARGS (running_time));
1183       GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME (frame);
1184       if (fevt->all_headers)
1185         GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME_HEADERS (frame);
1186       fevt->pending = TRUE;
1187     }
1188   }
1189   GST_OBJECT_UNLOCK (encoder);
1190
1191   gst_video_codec_frame_ref (frame);
1192   priv->frames = g_list_append (priv->frames, frame);
1193
1194   /* new data, more finish needed */
1195   priv->drained = FALSE;
1196
1197   GST_LOG_OBJECT (encoder, "passing frame pfn %d to subclass",
1198       frame->presentation_frame_number);
1199
1200   ret = klass->handle_frame (encoder, frame);
1201
1202 done:
1203   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1204
1205   return ret;
1206 }
1207
1208 static GstStateChangeReturn
1209 gst_video_encoder_change_state (GstElement * element, GstStateChange transition)
1210 {
1211   GstVideoEncoder *encoder;
1212   GstVideoEncoderClass *encoder_class;
1213   GstStateChangeReturn ret;
1214
1215   encoder = GST_VIDEO_ENCODER (element);
1216   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (element);
1217
1218   switch (transition) {
1219     case GST_STATE_CHANGE_NULL_TO_READY:
1220       /* open device/library if needed */
1221       if (encoder_class->open && !encoder_class->open (encoder))
1222         goto open_failed;
1223       break;
1224     case GST_STATE_CHANGE_READY_TO_PAUSED:
1225       /* Initialize device/library if needed */
1226       if (encoder_class->start && !encoder_class->start (encoder))
1227         goto start_failed;
1228       break;
1229     default:
1230       break;
1231   }
1232
1233   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1234
1235   switch (transition) {
1236     case GST_STATE_CHANGE_PAUSED_TO_READY:
1237       gst_video_encoder_reset (encoder);
1238       if (encoder_class->stop && !encoder_class->stop (encoder))
1239         goto stop_failed;
1240       break;
1241     case GST_STATE_CHANGE_READY_TO_NULL:
1242       /* close device/library if needed */
1243       if (encoder_class->close && !encoder_class->close (encoder))
1244         goto close_failed;
1245       break;
1246     default:
1247       break;
1248   }
1249
1250   return ret;
1251
1252   /* Errors */
1253
1254 open_failed:
1255   {
1256     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1257         ("Failed to open encoder"));
1258     return GST_STATE_CHANGE_FAILURE;
1259   }
1260
1261 start_failed:
1262   {
1263     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1264         ("Failed to start encoder"));
1265     return GST_STATE_CHANGE_FAILURE;
1266   }
1267
1268 stop_failed:
1269   {
1270     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1271         ("Failed to stop encoder"));
1272     return GST_STATE_CHANGE_FAILURE;
1273   }
1274
1275 close_failed:
1276   {
1277     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1278         ("Failed to close encoder"));
1279     return GST_STATE_CHANGE_FAILURE;
1280   }
1281 }
1282
1283 static gboolean
1284 gst_video_encoder_set_src_caps (GstVideoEncoder * encoder)
1285 {
1286   gboolean ret;
1287   GstVideoCodecState *state = encoder->priv->output_state;
1288   GstVideoInfo *info = &state->info;
1289
1290   g_return_val_if_fail (state->caps != NULL, FALSE);
1291
1292   if (encoder->priv->output_state_changed) {
1293     state->caps = gst_caps_make_writable (state->caps);
1294
1295     /* Fill caps */
1296     gst_caps_set_simple (state->caps, "width", G_TYPE_INT, info->width,
1297         "height", G_TYPE_INT, info->height,
1298         "pixel-aspect-ratio", GST_TYPE_FRACTION,
1299         info->par_n, info->par_d, NULL);
1300     if (info->flags & GST_VIDEO_FLAG_VARIABLE_FPS && info->fps_n != 0) {
1301       /* variable fps with a max-framerate */
1302       gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION, 0, 1,
1303           "max-framerate", GST_TYPE_FRACTION, info->fps_n, info->fps_d, NULL);
1304     } else {
1305       /* no variable fps or no max-framerate */
1306       gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION,
1307           info->fps_n, info->fps_d, NULL);
1308     }
1309     if (state->codec_data)
1310       gst_caps_set_simple (state->caps, "codec_data", GST_TYPE_BUFFER,
1311           state->codec_data, NULL);
1312     encoder->priv->output_state_changed = FALSE;
1313   }
1314
1315   ret = gst_pad_set_caps (encoder->srcpad, state->caps);
1316
1317   return ret;
1318 }
1319
1320 /**
1321  * gst_video_encoder_finish_frame:
1322  * @encoder: a #GstVideoEncoder
1323  * @frame: (transfer full): an encoded #GstVideoCodecFrame 
1324  *
1325  * @frame must have a valid encoded data buffer, whose metadata fields
1326  * are then appropriately set according to frame data or no buffer at
1327  * all if the frame should be dropped.
1328  * It is subsequently pushed downstream or provided to @pre_push.
1329  * In any case, the frame is considered finished and released.
1330  *
1331  * After calling this function the output buffer of the frame is to be
1332  * considered read-only. This function will also change the metadata
1333  * of the buffer.
1334  *
1335  * Returns: a #GstFlowReturn resulting from sending data downstream
1336  *
1337  * Since: 0.10.36
1338  */
1339 GstFlowReturn
1340 gst_video_encoder_finish_frame (GstVideoEncoder * encoder,
1341     GstVideoCodecFrame * frame)
1342 {
1343   GstVideoEncoderPrivate *priv = encoder->priv;
1344   GstFlowReturn ret = GST_FLOW_OK;
1345   GstVideoEncoderClass *encoder_class;
1346   GList *l;
1347   gboolean send_headers = FALSE;
1348   gboolean discont = (frame->presentation_frame_number == 0);
1349
1350   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1351
1352   GST_LOG_OBJECT (encoder,
1353       "finish frame fpn %d", frame->presentation_frame_number);
1354
1355   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1356
1357   if (G_UNLIKELY (priv->output_state_changed))
1358     gst_video_encoder_set_src_caps (encoder);
1359
1360   if (G_UNLIKELY (priv->output_state == NULL))
1361     goto no_output_state;
1362
1363   /* Push all pending events that arrived before this frame */
1364   for (l = priv->frames; l; l = l->next) {
1365     GstVideoCodecFrame *tmp = l->data;
1366
1367     if (tmp->events) {
1368       GList *k;
1369
1370       for (k = g_list_last (tmp->events); k; k = k->prev)
1371         gst_video_encoder_push_event (encoder, k->data);
1372       g_list_free (tmp->events);
1373       tmp->events = NULL;
1374     }
1375
1376     if (tmp == frame)
1377       break;
1378   }
1379
1380   /* no buffer data means this frame is skipped/dropped */
1381   if (!frame->output_buffer) {
1382     GST_DEBUG_OBJECT (encoder, "skipping frame %" GST_TIME_FORMAT,
1383         GST_TIME_ARGS (frame->pts));
1384     goto done;
1385   }
1386
1387   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame) && priv->force_key_unit) {
1388     GstClockTime stream_time, running_time;
1389     GstEvent *ev;
1390     ForcedKeyUnitEvent *fevt = NULL;
1391     GList *l;
1392
1393     running_time =
1394         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1395         frame->pts);
1396
1397     GST_OBJECT_LOCK (encoder);
1398     for (l = priv->force_key_unit; l; l = l->next) {
1399       ForcedKeyUnitEvent *tmp = l->data;
1400
1401       /* Skip non-pending keyunits */
1402       if (!tmp->pending)
1403         continue;
1404
1405       /* Simple case, keyunit ASAP */
1406       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1407         fevt = tmp;
1408         break;
1409       }
1410
1411       /* Event for before this frame */
1412       if (tmp->running_time <= running_time) {
1413         fevt = tmp;
1414         break;
1415       }
1416     }
1417
1418     if (fevt) {
1419       priv->force_key_unit = g_list_remove (priv->force_key_unit, fevt);
1420     }
1421     GST_OBJECT_UNLOCK (encoder);
1422
1423     if (fevt) {
1424       stream_time =
1425           gst_segment_to_stream_time (&encoder->output_segment, GST_FORMAT_TIME,
1426           frame->pts);
1427
1428       ev = gst_video_event_new_downstream_force_key_unit
1429           (frame->pts, stream_time, running_time,
1430           fevt->all_headers, fevt->count);
1431
1432       gst_video_encoder_push_event (encoder, ev);
1433
1434       if (fevt->all_headers)
1435         send_headers = TRUE;
1436
1437       GST_DEBUG_OBJECT (encoder,
1438           "Forced key unit: running-time %" GST_TIME_FORMAT
1439           ", all_headers %d, count %u",
1440           GST_TIME_ARGS (running_time), fevt->all_headers, fevt->count);
1441       forced_key_unit_event_free (fevt);
1442     }
1443   }
1444
1445   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
1446     priv->distance_from_sync = 0;
1447     GST_BUFFER_FLAG_UNSET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1448     /* For keyframes, DTS = PTS */
1449     frame->dts = frame->pts;
1450   } else {
1451     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
1452   }
1453
1454   frame->distance_from_sync = priv->distance_from_sync;
1455   priv->distance_from_sync++;
1456
1457   GST_BUFFER_PTS (frame->output_buffer) = frame->pts;
1458   GST_BUFFER_DTS (frame->output_buffer) = frame->dts;
1459   GST_BUFFER_DURATION (frame->output_buffer) = frame->duration;
1460
1461   /* update rate estimate */
1462   priv->bytes += gst_buffer_get_size (frame->output_buffer);
1463   if (GST_CLOCK_TIME_IS_VALID (frame->duration)) {
1464     priv->time += frame->duration;
1465   } else {
1466     /* better none than nothing valid */
1467     priv->time = GST_CLOCK_TIME_NONE;
1468   }
1469
1470   if (G_UNLIKELY (send_headers || priv->new_headers)) {
1471     GList *tmp, *copy = NULL;
1472
1473     GST_DEBUG_OBJECT (encoder, "Sending headers");
1474
1475     /* First make all buffers metadata-writable */
1476     for (tmp = priv->headers; tmp; tmp = tmp->next) {
1477       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1478
1479       copy = g_list_append (copy, gst_buffer_make_writable (tmpbuf));
1480     }
1481     g_list_free (priv->headers);
1482     priv->headers = copy;
1483
1484     for (tmp = priv->headers; tmp; tmp = tmp->next) {
1485       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
1486
1487       gst_buffer_ref (tmpbuf);
1488       priv->bytes += gst_buffer_get_size (tmpbuf);
1489       if (G_UNLIKELY (discont)) {
1490         GST_LOG_OBJECT (encoder, "marking discont");
1491         GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
1492         discont = FALSE;
1493       }
1494
1495       gst_pad_push (encoder->srcpad, tmpbuf);
1496     }
1497     priv->new_headers = FALSE;
1498   }
1499
1500   if (G_UNLIKELY (discont)) {
1501     GST_LOG_OBJECT (encoder, "marking discont");
1502     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DISCONT);
1503   }
1504
1505   if (encoder_class->pre_push)
1506     ret = encoder_class->pre_push (encoder, frame);
1507
1508   /* A reference always needs to be owned by the frame on the buffer.
1509    * For that reason, we use a complete sub-buffer (zero-cost) to push
1510    * downstream.
1511    * The original buffer will be free-ed only when downstream AND the
1512    * current implementation are done with the frame. */
1513   if (ret == GST_FLOW_OK)
1514     ret = gst_pad_push (encoder->srcpad, gst_buffer_ref (frame->output_buffer));
1515
1516 done:
1517   /* handed out */
1518
1519   /* unref once from the list */
1520   l = g_list_find (priv->frames, frame);
1521   if (l) {
1522     gst_video_codec_frame_unref (frame);
1523     priv->frames = g_list_delete_link (priv->frames, l);
1524   }
1525   /* unref because this function takes ownership */
1526   gst_video_codec_frame_unref (frame);
1527
1528   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1529
1530   return ret;
1531
1532   /* ERRORS */
1533 no_output_state:
1534   {
1535     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1536     GST_ERROR_OBJECT (encoder, "Output state was not configured");
1537     return GST_FLOW_ERROR;
1538   }
1539 }
1540
1541 /**
1542  * gst_video_encoder_get_output_state:
1543  * @encoder: a #GstVideoEncoder
1544  *
1545  * Get the current #GstVideoCodecState
1546  *
1547  * Returns: (transfer full): #GstVideoCodecState describing format of video data.
1548  *
1549  * Since: 0.10.36
1550  */
1551 GstVideoCodecState *
1552 gst_video_encoder_get_output_state (GstVideoEncoder * encoder)
1553 {
1554   GstVideoCodecState *state;
1555
1556   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1557   state = gst_video_codec_state_ref (encoder->priv->output_state);
1558   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1559
1560   return state;
1561 }
1562
1563 /**
1564  * gst_video_encoder_set_output_state:
1565  * @encoder: a #GstVideoEncoder
1566  * @caps: (transfer full): the #GstCaps to use for the output
1567  * @reference: (allow-none) (transfer none): An optional reference @GstVideoCodecState
1568  *
1569  * Creates a new #GstVideoCodecState with the specified caps as the output state
1570  * for the encoder.
1571  * Any previously set output state on @decoder will be replaced by the newly
1572  * created one.
1573  *
1574  * The specified @caps should not contain any resolution, pixel-aspect-ratio,
1575  * framerate, codec-data, .... Those should be specified instead in the returned
1576  * #GstVideoCodecState.
1577  *
1578  * If the subclass wishes to copy over existing fields (like pixel aspect ratio,
1579  * or framerate) from an existing #GstVideoCodecState, it can be provided as a
1580  * @reference.
1581  *
1582  * If the subclass wishes to override some fields from the output state (like
1583  * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
1584  *
1585  * The new output state will only take effect (set on pads and buffers) starting
1586  * from the next call to #gst_video_encoder_finish_frame().
1587  *
1588  * Returns: (transfer full): the newly configured output state.
1589  *
1590  * Since: 0.10.36
1591  */
1592 GstVideoCodecState *
1593 gst_video_encoder_set_output_state (GstVideoEncoder * encoder, GstCaps * caps,
1594     GstVideoCodecState * reference)
1595 {
1596   GstVideoEncoderPrivate *priv = encoder->priv;
1597   GstVideoCodecState *state;
1598
1599   g_return_val_if_fail (caps != NULL, NULL);
1600
1601   state = _new_output_state (caps, reference);
1602
1603   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1604   if (priv->output_state)
1605     gst_video_codec_state_unref (priv->output_state);
1606   priv->output_state = gst_video_codec_state_ref (state);
1607
1608   priv->output_state_changed = TRUE;
1609   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1610
1611   return state;
1612 }
1613
1614 /**
1615  * gst_video_encoder_set_latency:
1616  * @encoder: a #GstVideoEncoder
1617  * @min_latency: minimum latency
1618  * @max_latency: maximum latency
1619  *
1620  * Informs baseclass of encoding latency.
1621  *
1622  * Since: 0.10.36
1623  */
1624 void
1625 gst_video_encoder_set_latency (GstVideoEncoder * encoder,
1626     GstClockTime min_latency, GstClockTime max_latency)
1627 {
1628   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
1629   g_return_if_fail (max_latency >= min_latency);
1630
1631   GST_OBJECT_LOCK (encoder);
1632   encoder->priv->min_latency = min_latency;
1633   encoder->priv->max_latency = max_latency;
1634   GST_OBJECT_UNLOCK (encoder);
1635
1636   gst_element_post_message (GST_ELEMENT_CAST (encoder),
1637       gst_message_new_latency (GST_OBJECT_CAST (encoder)));
1638 }
1639
1640 /**
1641  * gst_video_encoder_get_latency:
1642  * @encoder: a #GstVideoEncoder
1643  * @min_latency: (out) (allow-none): address of variable in which to store the
1644  *     configured minimum latency, or %NULL
1645  * @max_latency: (out) (allow-none): address of variable in which to store the
1646  *     configured maximum latency, or %NULL
1647  *
1648  * Query the configured encoding latency. Results will be returned via
1649  * @min_latency and @max_latency.
1650  *
1651  * Since: 0.10.36
1652  */
1653 void
1654 gst_video_encoder_get_latency (GstVideoEncoder * encoder,
1655     GstClockTime * min_latency, GstClockTime * max_latency)
1656 {
1657   GST_OBJECT_LOCK (encoder);
1658   if (min_latency)
1659     *min_latency = encoder->priv->min_latency;
1660   if (max_latency)
1661     *max_latency = encoder->priv->max_latency;
1662   GST_OBJECT_UNLOCK (encoder);
1663 }
1664
1665 /**
1666  * gst_video_encoder_get_oldest_frame:
1667  * @encoder: a #GstVideoEncoder
1668  *
1669  * Get the oldest unfinished pending #GstVideoCodecFrame
1670  *
1671  * Returns: (transfer full): oldest unfinished pending #GstVideoCodecFrame
1672  *
1673  * Since: 0.10.36
1674  */
1675 GstVideoCodecFrame *
1676 gst_video_encoder_get_oldest_frame (GstVideoEncoder * encoder)
1677 {
1678   GstVideoCodecFrame *frame = NULL;
1679
1680   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1681   if (encoder->priv->frames)
1682     frame = gst_video_codec_frame_ref (encoder->priv->frames->data);
1683   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1684
1685   return (GstVideoCodecFrame *) frame;
1686 }
1687
1688 /**
1689  * gst_video_encoder_get_frame:
1690  * @encoder: a #GstVideoEnccoder
1691  * @frame_number: system_frame_number of a frame
1692  *
1693  * Get a pending unfinished #GstVideoCodecFrame
1694  * 
1695  * Returns: (transfer full): pending unfinished #GstVideoCodecFrame identified by @frame_number.
1696  *
1697  * Since: 0.10.36
1698  */
1699 GstVideoCodecFrame *
1700 gst_video_encoder_get_frame (GstVideoEncoder * encoder, int frame_number)
1701 {
1702   GList *g;
1703   GstVideoCodecFrame *frame = NULL;
1704
1705   GST_DEBUG_OBJECT (encoder, "frame_number : %d", frame_number);
1706
1707   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1708   for (g = encoder->priv->frames; g; g = g->next) {
1709     GstVideoCodecFrame *tmp = g->data;
1710
1711     if (tmp->system_frame_number == frame_number) {
1712       frame = gst_video_codec_frame_ref (tmp);
1713       break;
1714     }
1715   }
1716   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1717
1718   return frame;
1719 }