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