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