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