video(en|de)coder: Return TRUE when we consumed a tag event without creating a new...
[platform/upstream/gstreamer.git] / gst-libs / gst / video / gstvideoencoder.c
1 /* GStreamer
2  * Copyright (C) 2008 David Schleef <ds@schleef.org>
3  * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>.
4  * Copyright (C) 2011 Nokia Corporation. All rights reserved.
5  *   Contact: Stefan Kost <stefan.kost@nokia.com>
6  * Copyright (C) 2012 Collabora Ltd.
7  *      Author : Edward Hervey <edward@collabora.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /**
26  * SECTION:gstvideoencoder
27  * @short_description: Base class for video encoders
28  * @see_also:
29  *
30  * This base class is for video encoders turning raw video into
31  * encoded video data.
32  *
33  * GstVideoEncoder and subclass should cooperate as follows.
34  * <orderedlist>
35  * <listitem>
36  *   <itemizedlist><title>Configuration</title>
37  *   <listitem><para>
38  *     Initially, GstVideoEncoder calls @start when the encoder element
39  *     is activated, which allows subclass to perform any global setup.
40  *   </para></listitem>
41  *   <listitem><para>
42  *     GstVideoEncoder calls @set_format to inform subclass of the format
43  *     of input video data that it is about to receive.  Subclass should
44  *     setup for encoding and configure base class as appropriate
45  *     (e.g. latency). While unlikely, it might be called more than once,
46  *     if changing input parameters require reconfiguration.  Baseclass
47  *     will ensure that processing of current configuration is finished.
48  *   </para></listitem>
49  *   <listitem><para>
50  *     GstVideoEncoder calls @stop at end of all processing.
51  *   </para></listitem>
52  *   </itemizedlist>
53  * </listitem>
54  * <listitem>
55  *   <itemizedlist>
56  *   <title>Data processing</title>
57  *     <listitem><para>
58  *       Base class collects input data and metadata into a frame and hands
59  *       this to subclass' @handle_frame.
60  *     </para></listitem>
61  *     <listitem><para>
62  *       If codec processing results in encoded data, subclass should call
63  *       @gst_video_encoder_finish_frame to have encoded data pushed
64  *       downstream.
65  *     </para></listitem>
66  *     <listitem><para>
67  *       If implemented, baseclass calls subclass @pre_push just prior to
68  *       pushing to allow subclasses to modify some metadata on the buffer.
69  *       If it returns GST_FLOW_OK, the buffer is pushed downstream.
70  *     </para></listitem>
71  *     <listitem><para>
72  *       GstVideoEncoderClass will handle both srcpad and sinkpad events.
73  *       Sink events will be passed to subclass if @event callback has been
74  *       provided.
75  *     </para></listitem>
76  *   </itemizedlist>
77  * </listitem>
78  * <listitem>
79  *   <itemizedlist><title>Shutdown phase</title>
80  *   <listitem><para>
81  *     GstVideoEncoder class calls @stop to inform the subclass that data
82  *     parsing will be stopped.
83  *   </para></listitem>
84  *   </itemizedlist>
85  * </listitem>
86  * </orderedlist>
87  *
88  * Subclass is responsible for providing pad template caps for
89  * source and sink pads. The pads need to be named "sink" and "src". It should
90  * also be able to provide fixed src pad caps in @getcaps by the time it calls
91  * @gst_video_encoder_finish_frame.
92  *
93  * Things that subclass need to take care of:
94  * <itemizedlist>
95  *   <listitem><para>Provide pad templates</para></listitem>
96  *   <listitem><para>
97  *      Provide source pad caps before pushing the first buffer
98  *   </para></listitem>
99  *   <listitem><para>
100  *      Accept data in @handle_frame and provide encoded results to
101  *      @gst_video_encoder_finish_frame.
102  *   </para></listitem>
103  * </itemizedlist>
104  *
105  */
106
107 #ifdef HAVE_CONFIG_H
108 #include "config.h"
109 #endif
110
111 /* TODO
112  *
113  * * Calculate actual latency based on input/output timestamp/frame_number
114  *   and if it exceeds the recorded one, save it and emit a GST_MESSAGE_LATENCY
115  */
116
117 #include <gst/video/video.h>
118 #include "gstvideoencoder.h"
119 #include "gstvideoutils.h"
120 #include "gstvideoutilsprivate.h"
121
122 #include <gst/video/gstvideometa.h>
123 #include <gst/video/gstvideopool.h>
124
125 #include <string.h>
126
127 GST_DEBUG_CATEGORY (videoencoder_debug);
128 #define GST_CAT_DEFAULT videoencoder_debug
129
130 #define GST_VIDEO_ENCODER_GET_PRIVATE(obj)  \
131     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_VIDEO_ENCODER, \
132         GstVideoEncoderPrivate))
133
134 struct _GstVideoEncoderPrivate
135 {
136   guint64 presentation_frame_number;
137   int distance_from_sync;
138
139   /* FIXME : (and introduce a context ?) */
140   gboolean drained;
141
142   gint64 min_latency;
143   gint64 max_latency;
144
145   GList *current_frame_events;
146
147   GList *headers;
148   gboolean new_headers;         /* Whether new headers were just set */
149
150   GList *force_key_unit;        /* List of pending forced keyunits */
151
152   guint32 system_frame_number;
153
154   GList *frames;                /* Protected with OBJECT_LOCK */
155   GstVideoCodecState *input_state;
156   GstVideoCodecState *output_state;
157   gboolean output_state_changed;
158
159   gint64 bytes;
160   gint64 time;
161
162   GstAllocator *allocator;
163   GstAllocationParams params;
164
165   /* upstream stream tags (global tags are passed through as-is) */
166   GstTagList *upstream_tags;
167
168   /* subclass tags */
169   GstTagList *tags;
170   GstTagMergeMode tags_merge_mode;
171
172   gboolean tags_changed;
173
174   GstClockTime min_pts;
175   /* adjustment needed on pts, dts, segment start and stop to accomodate
176    * min_pts */
177   GstClockTime time_adjustment;
178 };
179
180 typedef struct _ForcedKeyUnitEvent ForcedKeyUnitEvent;
181 struct _ForcedKeyUnitEvent
182 {
183   GstClockTime running_time;
184   gboolean pending;             /* TRUE if this was requested already */
185   gboolean all_headers;
186   guint count;
187   guint32 frame_id;
188 };
189
190 static void
191 forced_key_unit_event_free (ForcedKeyUnitEvent * evt)
192 {
193   g_slice_free (ForcedKeyUnitEvent, evt);
194 }
195
196 static ForcedKeyUnitEvent *
197 forced_key_unit_event_new (GstClockTime running_time, gboolean all_headers,
198     guint count)
199 {
200   ForcedKeyUnitEvent *evt = g_slice_new0 (ForcedKeyUnitEvent);
201
202   evt->running_time = running_time;
203   evt->all_headers = all_headers;
204   evt->count = count;
205
206   return evt;
207 }
208
209 static GstElementClass *parent_class = NULL;
210 static void gst_video_encoder_class_init (GstVideoEncoderClass * klass);
211 static void gst_video_encoder_init (GstVideoEncoder * enc,
212     GstVideoEncoderClass * klass);
213
214 static void gst_video_encoder_finalize (GObject * object);
215
216 static gboolean gst_video_encoder_setcaps (GstVideoEncoder * enc,
217     GstCaps * caps);
218 static GstCaps *gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder,
219     GstCaps * filter);
220 static gboolean gst_video_encoder_src_event (GstPad * pad, GstObject * parent,
221     GstEvent * event);
222 static gboolean gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
223     GstEvent * event);
224 static GstFlowReturn gst_video_encoder_chain (GstPad * pad, GstObject * parent,
225     GstBuffer * buf);
226 static GstStateChangeReturn gst_video_encoder_change_state (GstElement *
227     element, GstStateChange transition);
228 static gboolean gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
229     GstQuery * query);
230 static gboolean gst_video_encoder_src_query (GstPad * pad, GstObject * parent,
231     GstQuery * query);
232 static GstVideoCodecFrame *gst_video_encoder_new_frame (GstVideoEncoder *
233     encoder, GstBuffer * buf, GstClockTime pts, GstClockTime dts,
234     GstClockTime duration);
235
236 static gboolean gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
237     GstEvent * event);
238 static gboolean gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
239     GstEvent * event);
240 static gboolean gst_video_encoder_decide_allocation_default (GstVideoEncoder *
241     encoder, GstQuery * query);
242 static gboolean gst_video_encoder_propose_allocation_default (GstVideoEncoder *
243     encoder, GstQuery * query);
244 static gboolean gst_video_encoder_negotiate_default (GstVideoEncoder * encoder);
245 static gboolean gst_video_encoder_negotiate_unlocked (GstVideoEncoder *
246     encoder);
247
248 static gboolean gst_video_encoder_sink_query_default (GstVideoEncoder * encoder,
249     GstQuery * query);
250 static gboolean gst_video_encoder_src_query_default (GstVideoEncoder * encoder,
251     GstQuery * query);
252
253 static gboolean gst_video_encoder_transform_meta_default (GstVideoEncoder *
254     encoder, GstVideoCodecFrame * frame, GstMeta * meta);
255
256 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
257  * method to get to the padtemplates */
258 GType
259 gst_video_encoder_get_type (void)
260 {
261   static volatile gsize type = 0;
262
263   if (g_once_init_enter (&type)) {
264     GType _type;
265     static const GTypeInfo info = {
266       sizeof (GstVideoEncoderClass),
267       NULL,
268       NULL,
269       (GClassInitFunc) gst_video_encoder_class_init,
270       NULL,
271       NULL,
272       sizeof (GstVideoEncoder),
273       0,
274       (GInstanceInitFunc) gst_video_encoder_init,
275     };
276     const GInterfaceInfo preset_interface_info = {
277       NULL,                     /* interface_init */
278       NULL,                     /* interface_finalize */
279       NULL                      /* interface_data */
280     };
281
282     _type = g_type_register_static (GST_TYPE_ELEMENT,
283         "GstVideoEncoder", &info, G_TYPE_FLAG_ABSTRACT);
284     g_type_add_interface_static (_type, GST_TYPE_PRESET,
285         &preset_interface_info);
286     g_once_init_leave (&type, _type);
287   }
288   return type;
289 }
290
291 static void
292 gst_video_encoder_class_init (GstVideoEncoderClass * klass)
293 {
294   GObjectClass *gobject_class;
295   GstElementClass *gstelement_class;
296
297   gobject_class = G_OBJECT_CLASS (klass);
298   gstelement_class = GST_ELEMENT_CLASS (klass);
299
300   GST_DEBUG_CATEGORY_INIT (videoencoder_debug, "videoencoder", 0,
301       "Base Video Encoder");
302
303   parent_class = g_type_class_peek_parent (klass);
304
305   g_type_class_add_private (klass, sizeof (GstVideoEncoderPrivate));
306
307   gobject_class->finalize = gst_video_encoder_finalize;
308
309   gstelement_class->change_state =
310       GST_DEBUG_FUNCPTR (gst_video_encoder_change_state);
311
312   klass->sink_event = gst_video_encoder_sink_event_default;
313   klass->src_event = gst_video_encoder_src_event_default;
314   klass->propose_allocation = gst_video_encoder_propose_allocation_default;
315   klass->decide_allocation = gst_video_encoder_decide_allocation_default;
316   klass->negotiate = gst_video_encoder_negotiate_default;
317   klass->sink_query = gst_video_encoder_sink_query_default;
318   klass->src_query = gst_video_encoder_src_query_default;
319   klass->transform_meta = gst_video_encoder_transform_meta_default;
320 }
321
322 static GList *
323 _flush_events (GstPad * pad, GList * events)
324 {
325   GList *tmp;
326
327   for (tmp = events; tmp; tmp = tmp->next) {
328     if (GST_EVENT_TYPE (tmp->data) != GST_EVENT_EOS &&
329         GST_EVENT_TYPE (tmp->data) != GST_EVENT_SEGMENT &&
330         GST_EVENT_IS_STICKY (tmp->data)) {
331       gst_pad_store_sticky_event (pad, GST_EVENT_CAST (tmp->data));
332     }
333     gst_event_unref (tmp->data);
334   }
335   g_list_free (events);
336
337   return NULL;
338 }
339
340 static gboolean
341 gst_video_encoder_reset (GstVideoEncoder * encoder, gboolean hard)
342 {
343   GstVideoEncoderPrivate *priv = encoder->priv;
344   gboolean ret = TRUE;
345
346   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
347
348   priv->presentation_frame_number = 0;
349   priv->distance_from_sync = 0;
350
351   g_list_foreach (priv->force_key_unit, (GFunc) forced_key_unit_event_free,
352       NULL);
353   g_list_free (priv->force_key_unit);
354   priv->force_key_unit = NULL;
355
356   priv->drained = TRUE;
357
358   priv->bytes = 0;
359   priv->time = 0;
360
361   priv->time_adjustment = GST_CLOCK_TIME_NONE;
362
363   if (hard) {
364     gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
365     gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
366
367     if (priv->input_state)
368       gst_video_codec_state_unref (priv->input_state);
369     priv->input_state = NULL;
370     if (priv->output_state)
371       gst_video_codec_state_unref (priv->output_state);
372     priv->output_state = NULL;
373
374     if (priv->upstream_tags) {
375       gst_tag_list_unref (priv->upstream_tags);
376       priv->upstream_tags = NULL;
377     }
378     if (priv->tags)
379       gst_tag_list_unref (priv->tags);
380     priv->tags = NULL;
381     priv->tags_merge_mode = GST_TAG_MERGE_APPEND;
382     priv->tags_changed = FALSE;
383
384     g_list_foreach (priv->headers, (GFunc) gst_event_unref, NULL);
385     g_list_free (priv->headers);
386     priv->headers = NULL;
387     priv->new_headers = FALSE;
388
389     if (priv->allocator) {
390       gst_object_unref (priv->allocator);
391       priv->allocator = NULL;
392     }
393
394     g_list_foreach (priv->current_frame_events, (GFunc) gst_event_unref, NULL);
395     g_list_free (priv->current_frame_events);
396     priv->current_frame_events = NULL;
397
398   } else {
399     GList *l;
400
401     for (l = priv->frames; l; l = l->next) {
402       GstVideoCodecFrame *frame = l->data;
403
404       frame->events = _flush_events (encoder->srcpad, frame->events);
405     }
406     priv->current_frame_events = _flush_events (encoder->srcpad,
407         encoder->priv->current_frame_events);
408   }
409
410   g_list_foreach (priv->frames, (GFunc) gst_video_codec_frame_unref, NULL);
411   g_list_free (priv->frames);
412   priv->frames = NULL;
413
414   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
415
416   return ret;
417 }
418
419 /* Always call reset() in one way or another after this */
420 static gboolean
421 gst_video_encoder_flush (GstVideoEncoder * encoder)
422 {
423   GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
424   gboolean ret = TRUE;
425
426   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
427   if (klass->flush)
428     ret = klass->flush (encoder);
429
430   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
431   return ret;
432 }
433
434 static void
435 gst_video_encoder_init (GstVideoEncoder * encoder, GstVideoEncoderClass * klass)
436 {
437   GstVideoEncoderPrivate *priv;
438   GstPadTemplate *pad_template;
439   GstPad *pad;
440
441   GST_DEBUG_OBJECT (encoder, "gst_video_encoder_init");
442
443   priv = encoder->priv = GST_VIDEO_ENCODER_GET_PRIVATE (encoder);
444
445   pad_template =
446       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
447   g_return_if_fail (pad_template != NULL);
448
449   encoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
450
451   gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_video_encoder_chain));
452   gst_pad_set_event_function (pad,
453       GST_DEBUG_FUNCPTR (gst_video_encoder_sink_event));
454   gst_pad_set_query_function (pad,
455       GST_DEBUG_FUNCPTR (gst_video_encoder_sink_query));
456   gst_element_add_pad (GST_ELEMENT (encoder), encoder->sinkpad);
457
458   pad_template =
459       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
460   g_return_if_fail (pad_template != NULL);
461
462   encoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
463
464   gst_pad_set_query_function (pad,
465       GST_DEBUG_FUNCPTR (gst_video_encoder_src_query));
466   gst_pad_set_event_function (pad,
467       GST_DEBUG_FUNCPTR (gst_video_encoder_src_event));
468   gst_element_add_pad (GST_ELEMENT (encoder), encoder->srcpad);
469
470   gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
471   gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
472
473   g_rec_mutex_init (&encoder->stream_lock);
474
475   priv->headers = NULL;
476   priv->new_headers = FALSE;
477
478   priv->min_latency = 0;
479   priv->max_latency = 0;
480   priv->min_pts = GST_CLOCK_TIME_NONE;
481   priv->time_adjustment = GST_CLOCK_TIME_NONE;
482
483   gst_video_encoder_reset (encoder, TRUE);
484 }
485
486 static gboolean
487 gst_video_encoded_video_convert (gint64 bytes, gint64 time,
488     GstFormat src_format, gint64 src_value, GstFormat * dest_format,
489     gint64 * dest_value)
490 {
491   gboolean res = FALSE;
492
493   g_return_val_if_fail (dest_format != NULL, FALSE);
494   g_return_val_if_fail (dest_value != NULL, FALSE);
495
496   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
497           src_value == -1)) {
498     if (dest_value)
499       *dest_value = src_value;
500     return TRUE;
501   }
502
503   if (bytes <= 0 || time <= 0) {
504     GST_DEBUG ("not enough metadata yet to convert");
505     goto exit;
506   }
507
508   switch (src_format) {
509     case GST_FORMAT_BYTES:
510       switch (*dest_format) {
511         case GST_FORMAT_TIME:
512           *dest_value = gst_util_uint64_scale (src_value, time, bytes);
513           res = TRUE;
514           break;
515         default:
516           res = FALSE;
517       }
518       break;
519     case GST_FORMAT_TIME:
520       switch (*dest_format) {
521         case GST_FORMAT_BYTES:
522           *dest_value = gst_util_uint64_scale (src_value, bytes, time);
523           res = TRUE;
524           break;
525         default:
526           res = FALSE;
527       }
528       break;
529     default:
530       GST_DEBUG ("unhandled conversion from %d to %d", src_format,
531           *dest_format);
532       res = FALSE;
533   }
534
535 exit:
536   return res;
537 }
538
539 /**
540  * gst_video_encoder_set_headers:
541  * @encoder: a #GstVideoEncoder
542  * @headers: (transfer full) (element-type GstBuffer): a list of #GstBuffer containing the codec header
543  *
544  * Set the codec headers to be sent downstream whenever requested.
545  */
546 void
547 gst_video_encoder_set_headers (GstVideoEncoder * video_encoder, GList * headers)
548 {
549   GST_VIDEO_ENCODER_STREAM_LOCK (video_encoder);
550
551   GST_DEBUG_OBJECT (video_encoder, "new headers %p", headers);
552   if (video_encoder->priv->headers) {
553     g_list_foreach (video_encoder->priv->headers, (GFunc) gst_buffer_unref,
554         NULL);
555     g_list_free (video_encoder->priv->headers);
556   }
557   video_encoder->priv->headers = headers;
558   video_encoder->priv->new_headers = TRUE;
559
560   GST_VIDEO_ENCODER_STREAM_UNLOCK (video_encoder);
561 }
562
563 static GstVideoCodecState *
564 _new_output_state (GstCaps * caps, GstVideoCodecState * reference)
565 {
566   GstVideoCodecState *state;
567
568   state = g_slice_new0 (GstVideoCodecState);
569   state->ref_count = 1;
570   gst_video_info_init (&state->info);
571   gst_video_info_set_format (&state->info, GST_VIDEO_FORMAT_ENCODED, 0, 0);
572
573   state->caps = caps;
574
575   if (reference) {
576     GstVideoInfo *tgt, *ref;
577
578     tgt = &state->info;
579     ref = &reference->info;
580
581     /* Copy over extra fields from reference state */
582     tgt->interlace_mode = ref->interlace_mode;
583     tgt->flags = ref->flags;
584     tgt->width = ref->width;
585     tgt->height = ref->height;
586     tgt->chroma_site = ref->chroma_site;
587     tgt->colorimetry = ref->colorimetry;
588     tgt->par_n = ref->par_n;
589     tgt->par_d = ref->par_d;
590     tgt->fps_n = ref->fps_n;
591     tgt->fps_d = ref->fps_d;
592
593     GST_VIDEO_INFO_MULTIVIEW_MODE (tgt) = GST_VIDEO_INFO_MULTIVIEW_MODE (ref);
594     GST_VIDEO_INFO_MULTIVIEW_FLAGS (tgt) = GST_VIDEO_INFO_MULTIVIEW_FLAGS (ref);
595   }
596
597   return state;
598 }
599
600 static GstVideoCodecState *
601 _new_input_state (GstCaps * caps)
602 {
603   GstVideoCodecState *state;
604
605   state = g_slice_new0 (GstVideoCodecState);
606   state->ref_count = 1;
607   gst_video_info_init (&state->info);
608   if (G_UNLIKELY (!gst_video_info_from_caps (&state->info, caps)))
609     goto parse_fail;
610   state->caps = gst_caps_ref (caps);
611
612   return state;
613
614 parse_fail:
615   {
616     g_slice_free (GstVideoCodecState, state);
617     return NULL;
618   }
619 }
620
621 static gboolean
622 gst_video_encoder_setcaps (GstVideoEncoder * encoder, GstCaps * caps)
623 {
624   GstVideoEncoderClass *encoder_class;
625   GstVideoCodecState *state;
626   gboolean ret;
627
628   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
629
630   /* subclass should do something here ... */
631   g_return_val_if_fail (encoder_class->set_format != NULL, FALSE);
632
633   GST_DEBUG_OBJECT (encoder, "setcaps %" GST_PTR_FORMAT, caps);
634
635   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
636
637   if (encoder->priv->input_state) {
638     GST_DEBUG_OBJECT (encoder,
639         "Checking if caps changed old %" GST_PTR_FORMAT " new %" GST_PTR_FORMAT,
640         encoder->priv->input_state->caps, caps);
641     if (gst_caps_is_equal (encoder->priv->input_state->caps, caps))
642       goto caps_not_changed;
643   }
644
645   state = _new_input_state (caps);
646   if (G_UNLIKELY (!state))
647     goto parse_fail;
648
649   if (encoder->priv->input_state
650       && gst_video_info_is_equal (&state->info,
651           &encoder->priv->input_state->info)) {
652     gst_video_codec_state_unref (state);
653     goto caps_not_changed;
654   }
655
656   if (encoder_class->reset) {
657     GST_FIXME_OBJECT (encoder, "GstVideoEncoder::reset() is deprecated");
658     encoder_class->reset (encoder, TRUE);
659   }
660
661   /* and subclass should be ready to configure format at any time around */
662   ret = encoder_class->set_format (encoder, state);
663   if (ret) {
664     if (encoder->priv->input_state)
665       gst_video_codec_state_unref (encoder->priv->input_state);
666     encoder->priv->input_state = state;
667   } else {
668     gst_video_codec_state_unref (state);
669   }
670
671   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
672
673   if (!ret)
674     GST_WARNING_OBJECT (encoder, "rejected caps %" GST_PTR_FORMAT, caps);
675
676   return ret;
677
678 caps_not_changed:
679   {
680     GST_DEBUG_OBJECT (encoder, "Caps did not change - ignore");
681     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
682     return TRUE;
683   }
684
685   /* ERRORS */
686 parse_fail:
687   {
688     GST_WARNING_OBJECT (encoder, "Failed to parse caps");
689     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
690     return FALSE;
691   }
692 }
693
694 /**
695  * gst_video_encoder_proxy_getcaps:
696  * @enc: a #GstVideoEncoder
697  * @caps: (allow-none): initial caps
698  * @filter: (allow-none): filter caps
699  *
700  * Returns caps that express @caps (or sink template caps if @caps == NULL)
701  * restricted to resolution/format/... combinations supported by downstream
702  * elements (e.g. muxers).
703  *
704  * Returns: (transfer full): a #GstCaps owned by caller
705  */
706 GstCaps *
707 gst_video_encoder_proxy_getcaps (GstVideoEncoder * encoder, GstCaps * caps,
708     GstCaps * filter)
709 {
710   return __gst_video_element_proxy_getcaps (GST_ELEMENT_CAST (encoder),
711       GST_VIDEO_ENCODER_SINK_PAD (encoder),
712       GST_VIDEO_ENCODER_SRC_PAD (encoder), caps, filter);
713 }
714
715 static GstCaps *
716 gst_video_encoder_sink_getcaps (GstVideoEncoder * encoder, GstCaps * filter)
717 {
718   GstVideoEncoderClass *klass;
719   GstCaps *caps;
720
721   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
722
723   if (klass->getcaps)
724     caps = klass->getcaps (encoder, filter);
725   else
726     caps = gst_video_encoder_proxy_getcaps (encoder, NULL, filter);
727
728   GST_LOG_OBJECT (encoder, "Returning caps %" GST_PTR_FORMAT, caps);
729
730   return caps;
731 }
732
733 static gboolean
734 gst_video_encoder_decide_allocation_default (GstVideoEncoder * encoder,
735     GstQuery * query)
736 {
737   GstAllocator *allocator = NULL;
738   GstAllocationParams params;
739   gboolean update_allocator;
740
741   /* we got configuration from our peer or the decide_allocation method,
742    * parse them */
743   if (gst_query_get_n_allocation_params (query) > 0) {
744     /* try the allocator */
745     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
746     update_allocator = TRUE;
747   } else {
748     allocator = NULL;
749     gst_allocation_params_init (&params);
750     update_allocator = FALSE;
751   }
752
753   if (update_allocator)
754     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
755   else
756     gst_query_add_allocation_param (query, allocator, &params);
757   if (allocator)
758     gst_object_unref (allocator);
759
760   return TRUE;
761 }
762
763 static gboolean
764 gst_video_encoder_propose_allocation_default (GstVideoEncoder * encoder,
765     GstQuery * query)
766 {
767   GstCaps *caps;
768   GstVideoInfo info;
769   GstBufferPool *pool;
770   guint size;
771
772   gst_query_parse_allocation (query, &caps, NULL);
773
774   if (caps == NULL)
775     return FALSE;
776
777   if (!gst_video_info_from_caps (&info, caps))
778     return FALSE;
779
780   size = GST_VIDEO_INFO_SIZE (&info);
781
782   if (gst_query_get_n_allocation_pools (query) == 0) {
783     GstStructure *structure;
784     GstAllocator *allocator = NULL;
785     GstAllocationParams params = { 0, 15, 0, 0 };
786
787     if (gst_query_get_n_allocation_params (query) > 0)
788       gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
789     else
790       gst_query_add_allocation_param (query, allocator, &params);
791
792     pool = gst_video_buffer_pool_new ();
793
794     structure = gst_buffer_pool_get_config (pool);
795     gst_buffer_pool_config_set_params (structure, caps, size, 0, 0);
796     gst_buffer_pool_config_set_allocator (structure, allocator, &params);
797
798     if (allocator)
799       gst_object_unref (allocator);
800
801     if (!gst_buffer_pool_set_config (pool, structure))
802       goto config_failed;
803
804     gst_query_add_allocation_pool (query, pool, size, 0, 0);
805     gst_object_unref (pool);
806     gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
807   }
808
809   return TRUE;
810
811   /* ERRORS */
812 config_failed:
813   {
814     GST_ERROR_OBJECT (encoder, "failed to set config");
815     gst_object_unref (pool);
816     return FALSE;
817   }
818 }
819
820 static gboolean
821 gst_video_encoder_sink_query_default (GstVideoEncoder * encoder,
822     GstQuery * query)
823 {
824   GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (encoder);
825   gboolean res = FALSE;
826
827   switch (GST_QUERY_TYPE (query)) {
828     case GST_QUERY_CAPS:
829     {
830       GstCaps *filter, *caps;
831
832       gst_query_parse_caps (query, &filter);
833       caps = gst_video_encoder_sink_getcaps (encoder, filter);
834       gst_query_set_caps_result (query, caps);
835       gst_caps_unref (caps);
836       res = TRUE;
837       break;
838     }
839     case GST_QUERY_ALLOCATION:
840     {
841       GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
842
843       if (klass->propose_allocation)
844         res = klass->propose_allocation (encoder, query);
845       break;
846     }
847     default:
848       res = gst_pad_query_default (pad, GST_OBJECT (encoder), query);
849       break;
850   }
851   return res;
852 }
853
854 static gboolean
855 gst_video_encoder_sink_query (GstPad * pad, GstObject * parent,
856     GstQuery * query)
857 {
858   GstVideoEncoder *encoder;
859   GstVideoEncoderClass *encoder_class;
860   gboolean ret = FALSE;
861
862   encoder = GST_VIDEO_ENCODER (parent);
863   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
864
865   GST_DEBUG_OBJECT (encoder, "received query %d, %s", GST_QUERY_TYPE (query),
866       GST_QUERY_TYPE_NAME (query));
867
868   if (encoder_class->sink_query)
869     ret = encoder_class->sink_query (encoder, query);
870
871   return ret;
872 }
873
874 static void
875 gst_video_encoder_finalize (GObject * object)
876 {
877   GstVideoEncoder *encoder;
878
879   GST_DEBUG_OBJECT (object, "finalize");
880
881   encoder = GST_VIDEO_ENCODER (object);
882   g_rec_mutex_clear (&encoder->stream_lock);
883
884   if (encoder->priv->allocator) {
885     gst_object_unref (encoder->priv->allocator);
886     encoder->priv->allocator = NULL;
887   }
888
889   G_OBJECT_CLASS (parent_class)->finalize (object);
890 }
891
892 static gboolean
893 gst_video_encoder_push_event (GstVideoEncoder * encoder, GstEvent * event)
894 {
895   switch (GST_EVENT_TYPE (event)) {
896     case GST_EVENT_SEGMENT:
897     {
898       GstSegment segment;
899
900       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
901
902       gst_event_copy_segment (event, &segment);
903
904       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
905
906       if (segment.format != GST_FORMAT_TIME) {
907         GST_DEBUG_OBJECT (encoder, "received non TIME segment");
908         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
909         break;
910       }
911
912       if (encoder->priv->time_adjustment != GST_CLOCK_TIME_NONE) {
913         segment.start += encoder->priv->time_adjustment;
914         if (GST_CLOCK_TIME_IS_VALID (segment.stop)) {
915           segment.stop += encoder->priv->time_adjustment;
916         }
917       }
918
919       encoder->output_segment = segment;
920       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
921
922       gst_event_unref (event);
923       event = gst_event_new_segment (&encoder->output_segment);
924
925       break;
926     }
927     default:
928       break;
929   }
930
931   return gst_pad_push_event (encoder->srcpad, event);
932 }
933
934 static GstEvent *
935 gst_video_encoder_create_merged_tags_event (GstVideoEncoder * enc)
936 {
937   GstTagList *merged_tags;
938
939   GST_LOG_OBJECT (enc, "upstream : %" GST_PTR_FORMAT, enc->priv->upstream_tags);
940   GST_LOG_OBJECT (enc, "encoder  : %" GST_PTR_FORMAT, enc->priv->tags);
941   GST_LOG_OBJECT (enc, "mode     : %d", enc->priv->tags_merge_mode);
942
943   merged_tags =
944       gst_tag_list_merge (enc->priv->upstream_tags, enc->priv->tags,
945       enc->priv->tags_merge_mode);
946
947   GST_DEBUG_OBJECT (enc, "merged   : %" GST_PTR_FORMAT, merged_tags);
948
949   if (merged_tags == NULL)
950     return NULL;
951
952   if (gst_tag_list_is_empty (merged_tags)) {
953     gst_tag_list_unref (merged_tags);
954     return NULL;
955   }
956
957   return gst_event_new_tag (merged_tags);
958 }
959
960 static inline void
961 gst_video_encoder_check_and_push_tags (GstVideoEncoder * encoder)
962 {
963   if (encoder->priv->tags_changed) {
964     GstEvent *tags_event;
965
966     tags_event = gst_video_encoder_create_merged_tags_event (encoder);
967
968     if (tags_event != NULL)
969       gst_video_encoder_push_event (encoder, tags_event);
970
971     encoder->priv->tags_changed = FALSE;
972   }
973 }
974
975 static gboolean
976 gst_video_encoder_sink_event_default (GstVideoEncoder * encoder,
977     GstEvent * event)
978 {
979   GstVideoEncoderClass *encoder_class;
980   gboolean ret = FALSE;
981
982   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
983
984   switch (GST_EVENT_TYPE (event)) {
985     case GST_EVENT_CAPS:
986     {
987       GstCaps *caps;
988
989       gst_event_parse_caps (event, &caps);
990       ret = gst_video_encoder_setcaps (encoder, caps);
991
992       gst_event_unref (event);
993       event = NULL;
994       break;
995     }
996     case GST_EVENT_EOS:
997     {
998       GstFlowReturn flow_ret;
999
1000       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1001
1002       if (encoder_class->finish) {
1003         flow_ret = encoder_class->finish (encoder);
1004       } else {
1005         flow_ret = GST_FLOW_OK;
1006       }
1007
1008       if (encoder->priv->current_frame_events) {
1009         GList *l;
1010
1011         for (l = g_list_last (encoder->priv->current_frame_events); l;
1012             l = g_list_previous (l)) {
1013           GstEvent *event = GST_EVENT (l->data);
1014
1015           gst_video_encoder_push_event (encoder, event);
1016         }
1017       }
1018       g_list_free (encoder->priv->current_frame_events);
1019       encoder->priv->current_frame_events = NULL;
1020
1021       gst_video_encoder_check_and_push_tags (encoder);
1022
1023       ret = (flow_ret == GST_FLOW_OK);
1024       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1025       break;
1026     }
1027     case GST_EVENT_SEGMENT:
1028     {
1029       GstSegment segment;
1030
1031       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1032
1033       gst_event_copy_segment (event, &segment);
1034
1035       GST_DEBUG_OBJECT (encoder, "segment %" GST_SEGMENT_FORMAT, &segment);
1036
1037       if (segment.format != GST_FORMAT_TIME) {
1038         GST_DEBUG_OBJECT (encoder, "received non TIME newsegment");
1039         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1040         break;
1041       }
1042
1043       encoder->input_segment = segment;
1044       ret = TRUE;
1045       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1046       break;
1047     }
1048     case GST_EVENT_CUSTOM_DOWNSTREAM:
1049     {
1050       if (gst_video_event_is_force_key_unit (event)) {
1051         GstClockTime running_time;
1052         gboolean all_headers;
1053         guint count;
1054
1055         if (gst_video_event_parse_downstream_force_key_unit (event,
1056                 NULL, NULL, &running_time, &all_headers, &count)) {
1057           ForcedKeyUnitEvent *fevt;
1058
1059           GST_OBJECT_LOCK (encoder);
1060           fevt = forced_key_unit_event_new (running_time, all_headers, count);
1061           encoder->priv->force_key_unit =
1062               g_list_append (encoder->priv->force_key_unit, fevt);
1063           GST_OBJECT_UNLOCK (encoder);
1064
1065           GST_DEBUG_OBJECT (encoder,
1066               "force-key-unit event: running-time %" GST_TIME_FORMAT
1067               ", all_headers %d, count %u",
1068               GST_TIME_ARGS (running_time), all_headers, count);
1069         }
1070         gst_event_unref (event);
1071         event = NULL;
1072         ret = TRUE;
1073       }
1074       break;
1075     }
1076     case GST_EVENT_STREAM_START:
1077     {
1078       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1079       /* Flush upstream tags after a STREAM_START */
1080       GST_DEBUG_OBJECT (encoder, "STREAM_START, clearing upstream tags");
1081       if (encoder->priv->upstream_tags) {
1082         gst_tag_list_unref (encoder->priv->upstream_tags);
1083         encoder->priv->upstream_tags = NULL;
1084         encoder->priv->tags_changed = TRUE;
1085       }
1086       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1087       break;
1088     }
1089     case GST_EVENT_TAG:
1090     {
1091       GstTagList *tags;
1092
1093       gst_event_parse_tag (event, &tags);
1094
1095       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
1096         GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1097         if (encoder->priv->upstream_tags != tags) {
1098           tags = gst_tag_list_copy (tags);
1099
1100           /* FIXME: make generic based on GST_TAG_FLAG_ENCODED */
1101           gst_tag_list_remove_tag (tags, GST_TAG_CODEC);
1102           gst_tag_list_remove_tag (tags, GST_TAG_AUDIO_CODEC);
1103           gst_tag_list_remove_tag (tags, GST_TAG_VIDEO_CODEC);
1104           gst_tag_list_remove_tag (tags, GST_TAG_SUBTITLE_CODEC);
1105           gst_tag_list_remove_tag (tags, GST_TAG_CONTAINER_FORMAT);
1106           gst_tag_list_remove_tag (tags, GST_TAG_BITRATE);
1107           gst_tag_list_remove_tag (tags, GST_TAG_NOMINAL_BITRATE);
1108           gst_tag_list_remove_tag (tags, GST_TAG_MAXIMUM_BITRATE);
1109           gst_tag_list_remove_tag (tags, GST_TAG_MINIMUM_BITRATE);
1110           gst_tag_list_remove_tag (tags, GST_TAG_ENCODER);
1111           gst_tag_list_remove_tag (tags, GST_TAG_ENCODER_VERSION);
1112
1113           if (encoder->priv->upstream_tags)
1114             gst_tag_list_unref (encoder->priv->upstream_tags);
1115           encoder->priv->upstream_tags = tags;
1116           GST_INFO_OBJECT (encoder, "upstream tags: %" GST_PTR_FORMAT, tags);
1117         }
1118         gst_event_unref (event);
1119         event = gst_video_encoder_create_merged_tags_event (encoder);
1120         GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1121         if (!event)
1122           ret = TRUE;
1123       }
1124       break;
1125     }
1126     case GST_EVENT_FLUSH_STOP:{
1127       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1128       gst_video_encoder_flush (encoder);
1129       gst_segment_init (&encoder->input_segment, GST_FORMAT_TIME);
1130       gst_segment_init (&encoder->output_segment, GST_FORMAT_TIME);
1131       gst_video_encoder_reset (encoder, FALSE);
1132       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1133       break;
1134     }
1135     default:
1136       break;
1137   }
1138
1139   /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
1140    * For EOS this is required because no buffer or serialized event
1141    * will come after EOS and nothing could trigger another
1142    * _finish_frame() call.   *
1143    * If the subclass handles sending of EOS manually it can simply
1144    * not chain up to the parent class' event handler
1145    *
1146    * For FLUSH_STOP this is required because it is expected
1147    * to be forwarded immediately and no buffers are queued anyway.
1148    */
1149   if (event) {
1150     if (!GST_EVENT_IS_SERIALIZED (event)
1151         || GST_EVENT_TYPE (event) == GST_EVENT_EOS
1152         || GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_STOP) {
1153       ret = gst_video_encoder_push_event (encoder, event);
1154     } else {
1155       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1156       encoder->priv->current_frame_events =
1157           g_list_prepend (encoder->priv->current_frame_events, event);
1158       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1159       ret = TRUE;
1160     }
1161   }
1162
1163   return ret;
1164 }
1165
1166 static gboolean
1167 gst_video_encoder_sink_event (GstPad * pad, GstObject * parent,
1168     GstEvent * event)
1169 {
1170   GstVideoEncoder *enc;
1171   GstVideoEncoderClass *klass;
1172   gboolean ret = TRUE;
1173
1174   enc = GST_VIDEO_ENCODER (parent);
1175   klass = GST_VIDEO_ENCODER_GET_CLASS (enc);
1176
1177   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1178       GST_EVENT_TYPE_NAME (event));
1179
1180   if (klass->sink_event)
1181     ret = klass->sink_event (enc, event);
1182
1183   return ret;
1184 }
1185
1186 static gboolean
1187 gst_video_encoder_src_event_default (GstVideoEncoder * encoder,
1188     GstEvent * event)
1189 {
1190   gboolean ret = FALSE;
1191
1192   switch (GST_EVENT_TYPE (event)) {
1193     case GST_EVENT_CUSTOM_UPSTREAM:
1194     {
1195       if (gst_video_event_is_force_key_unit (event)) {
1196         GstClockTime running_time;
1197         gboolean all_headers;
1198         guint count;
1199
1200         if (gst_video_event_parse_upstream_force_key_unit (event,
1201                 &running_time, &all_headers, &count)) {
1202           ForcedKeyUnitEvent *fevt;
1203
1204           GST_OBJECT_LOCK (encoder);
1205           fevt = forced_key_unit_event_new (running_time, all_headers, count);
1206           encoder->priv->force_key_unit =
1207               g_list_append (encoder->priv->force_key_unit, fevt);
1208           GST_OBJECT_UNLOCK (encoder);
1209
1210           GST_DEBUG_OBJECT (encoder,
1211               "force-key-unit event: running-time %" GST_TIME_FORMAT
1212               ", all_headers %d, count %u",
1213               GST_TIME_ARGS (running_time), all_headers, count);
1214         }
1215         gst_event_unref (event);
1216         event = NULL;
1217         ret = TRUE;
1218       }
1219       break;
1220     }
1221     default:
1222       break;
1223   }
1224
1225   if (event)
1226     ret =
1227         gst_pad_event_default (encoder->srcpad, GST_OBJECT_CAST (encoder),
1228         event);
1229
1230   return ret;
1231 }
1232
1233 static gboolean
1234 gst_video_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1235 {
1236   GstVideoEncoder *encoder;
1237   GstVideoEncoderClass *klass;
1238   gboolean ret = FALSE;
1239
1240   encoder = GST_VIDEO_ENCODER (parent);
1241   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1242
1243   GST_LOG_OBJECT (encoder, "handling event: %" GST_PTR_FORMAT, event);
1244
1245   if (klass->src_event)
1246     ret = klass->src_event (encoder, event);
1247
1248   return ret;
1249 }
1250
1251 static gboolean
1252 gst_video_encoder_src_query_default (GstVideoEncoder * enc, GstQuery * query)
1253 {
1254   GstPad *pad = GST_VIDEO_ENCODER_SRC_PAD (enc);
1255   GstVideoEncoderPrivate *priv;
1256   gboolean res;
1257
1258   priv = enc->priv;
1259
1260   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1261
1262   switch (GST_QUERY_TYPE (query)) {
1263     case GST_QUERY_CONVERT:
1264     {
1265       GstFormat src_fmt, dest_fmt;
1266       gint64 src_val, dest_val;
1267
1268       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1269       res =
1270           gst_video_encoded_video_convert (priv->bytes, priv->time, src_fmt,
1271           src_val, &dest_fmt, &dest_val);
1272       if (!res)
1273         goto error;
1274       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1275       break;
1276     }
1277     case GST_QUERY_LATENCY:
1278     {
1279       gboolean live;
1280       GstClockTime min_latency, max_latency;
1281
1282       res = gst_pad_peer_query (enc->sinkpad, query);
1283       if (res) {
1284         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1285         GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1286             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1287             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1288
1289         GST_OBJECT_LOCK (enc);
1290         min_latency += priv->min_latency;
1291         if (max_latency == GST_CLOCK_TIME_NONE
1292             || enc->priv->max_latency == GST_CLOCK_TIME_NONE)
1293           max_latency = GST_CLOCK_TIME_NONE;
1294         else
1295           max_latency += enc->priv->max_latency;
1296         GST_OBJECT_UNLOCK (enc);
1297
1298         gst_query_set_latency (query, live, min_latency, max_latency);
1299       }
1300     }
1301       break;
1302     default:
1303       res = gst_pad_query_default (pad, GST_OBJECT (enc), query);
1304   }
1305   return res;
1306
1307 error:
1308   GST_DEBUG_OBJECT (enc, "query failed");
1309   return res;
1310 }
1311
1312 static gboolean
1313 gst_video_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1314 {
1315   GstVideoEncoder *encoder;
1316   GstVideoEncoderClass *encoder_class;
1317   gboolean ret = FALSE;
1318
1319   encoder = GST_VIDEO_ENCODER (parent);
1320   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1321
1322   GST_DEBUG_OBJECT (encoder, "received query %d, %s", GST_QUERY_TYPE (query),
1323       GST_QUERY_TYPE_NAME (query));
1324
1325   if (encoder_class->src_query)
1326     ret = encoder_class->src_query (encoder, query);
1327
1328   return ret;
1329 }
1330
1331 static GstVideoCodecFrame *
1332 gst_video_encoder_new_frame (GstVideoEncoder * encoder, GstBuffer * buf,
1333     GstClockTime pts, GstClockTime dts, GstClockTime duration)
1334 {
1335   GstVideoEncoderPrivate *priv = encoder->priv;
1336   GstVideoCodecFrame *frame;
1337
1338   frame = g_slice_new0 (GstVideoCodecFrame);
1339
1340   frame->ref_count = 1;
1341
1342   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1343   frame->system_frame_number = priv->system_frame_number;
1344   priv->system_frame_number++;
1345
1346   frame->presentation_frame_number = priv->presentation_frame_number;
1347   priv->presentation_frame_number++;
1348   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1349
1350   frame->events = priv->current_frame_events;
1351   priv->current_frame_events = NULL;
1352   frame->input_buffer = buf;
1353   frame->pts = pts;
1354   frame->dts = dts;
1355   frame->duration = duration;
1356   frame->abidata.ABI.ts = pts;
1357
1358   return frame;
1359 }
1360
1361
1362 static GstFlowReturn
1363 gst_video_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1364 {
1365   GstVideoEncoder *encoder;
1366   GstVideoEncoderPrivate *priv;
1367   GstVideoEncoderClass *klass;
1368   GstVideoCodecFrame *frame;
1369   GstClockTime pts, duration;
1370   GstFlowReturn ret = GST_FLOW_OK;
1371   guint64 start, stop, cstart, cstop;
1372
1373   encoder = GST_VIDEO_ENCODER (parent);
1374   priv = encoder->priv;
1375   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1376
1377   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1378
1379   if (!encoder->priv->input_state)
1380     goto not_negotiated;
1381
1382   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1383
1384   pts = GST_BUFFER_PTS (buf);
1385   duration = GST_BUFFER_DURATION (buf);
1386
1387   GST_LOG_OBJECT (encoder,
1388       "received buffer of size %" G_GSIZE_FORMAT " with PTS %" GST_TIME_FORMAT
1389       ", DTS %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1390       gst_buffer_get_size (buf), GST_TIME_ARGS (pts),
1391       GST_TIME_ARGS (GST_BUFFER_DTS (buf)), GST_TIME_ARGS (duration));
1392
1393   start = pts;
1394   if (GST_CLOCK_TIME_IS_VALID (duration))
1395     stop = start + duration;
1396   else
1397     stop = GST_CLOCK_TIME_NONE;
1398
1399   /* Drop buffers outside of segment */
1400   if (!gst_segment_clip (&encoder->input_segment,
1401           GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
1402     GST_DEBUG_OBJECT (encoder, "clipping to segment dropped frame");
1403     gst_buffer_unref (buf);
1404     goto done;
1405   }
1406
1407   if (GST_CLOCK_TIME_IS_VALID (cstop))
1408     duration = cstop - cstart;
1409   else
1410     duration = GST_CLOCK_TIME_NONE;
1411
1412   if (priv->min_pts != GST_CLOCK_TIME_NONE
1413       && priv->time_adjustment == GST_CLOCK_TIME_NONE) {
1414     if (cstart < priv->min_pts) {
1415       priv->time_adjustment = priv->min_pts - cstart;
1416     }
1417   }
1418
1419   if (priv->time_adjustment != GST_CLOCK_TIME_NONE) {
1420     cstart += priv->time_adjustment;
1421   }
1422
1423   /* incoming DTS is not really relevant and does not make sense anyway,
1424    * so pass along _NONE and maybe come up with something better later on */
1425   frame = gst_video_encoder_new_frame (encoder, buf, cstart,
1426       GST_CLOCK_TIME_NONE, duration);
1427
1428   GST_OBJECT_LOCK (encoder);
1429   if (priv->force_key_unit) {
1430     ForcedKeyUnitEvent *fevt = NULL;
1431     GstClockTime running_time;
1432     GList *l;
1433
1434     running_time =
1435         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
1436         cstart);
1437
1438     for (l = priv->force_key_unit; l; l = l->next) {
1439       ForcedKeyUnitEvent *tmp = l->data;
1440
1441       /* Skip pending keyunits */
1442       if (tmp->pending)
1443         continue;
1444
1445       /* Simple case, keyunit ASAP */
1446       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
1447         fevt = tmp;
1448         break;
1449       }
1450
1451       /* Event for before this frame */
1452       if (tmp->running_time <= running_time) {
1453         fevt = tmp;
1454         break;
1455       }
1456     }
1457
1458     if (fevt) {
1459       fevt->frame_id = frame->system_frame_number;
1460       GST_DEBUG_OBJECT (encoder,
1461           "Forcing a key unit at running time %" GST_TIME_FORMAT,
1462           GST_TIME_ARGS (running_time));
1463       GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME (frame);
1464       if (fevt->all_headers)
1465         GST_VIDEO_CODEC_FRAME_SET_FORCE_KEYFRAME_HEADERS (frame);
1466       fevt->pending = TRUE;
1467     }
1468   }
1469   GST_OBJECT_UNLOCK (encoder);
1470
1471   gst_video_codec_frame_ref (frame);
1472   priv->frames = g_list_append (priv->frames, frame);
1473
1474   /* new data, more finish needed */
1475   priv->drained = FALSE;
1476
1477   GST_LOG_OBJECT (encoder, "passing frame pfn %d to subclass",
1478       frame->presentation_frame_number);
1479
1480   ret = klass->handle_frame (encoder, frame);
1481
1482 done:
1483   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1484
1485   return ret;
1486
1487   /* ERRORS */
1488 not_negotiated:
1489   {
1490     GST_ELEMENT_ERROR (encoder, CORE, NEGOTIATION, (NULL),
1491         ("encoder not initialized"));
1492     gst_buffer_unref (buf);
1493     return GST_FLOW_NOT_NEGOTIATED;
1494   }
1495 }
1496
1497 static GstStateChangeReturn
1498 gst_video_encoder_change_state (GstElement * element, GstStateChange transition)
1499 {
1500   GstVideoEncoder *encoder;
1501   GstVideoEncoderClass *encoder_class;
1502   GstStateChangeReturn ret;
1503
1504   encoder = GST_VIDEO_ENCODER (element);
1505   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (element);
1506
1507   switch (transition) {
1508     case GST_STATE_CHANGE_NULL_TO_READY:
1509       /* open device/library if needed */
1510       if (encoder_class->open && !encoder_class->open (encoder))
1511         goto open_failed;
1512       break;
1513     case GST_STATE_CHANGE_READY_TO_PAUSED:
1514       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1515       gst_video_encoder_reset (encoder, TRUE);
1516       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1517
1518       /* Initialize device/library if needed */
1519       if (encoder_class->start && !encoder_class->start (encoder))
1520         goto start_failed;
1521       break;
1522     default:
1523       break;
1524   }
1525
1526   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1527
1528   switch (transition) {
1529     case GST_STATE_CHANGE_PAUSED_TO_READY:{
1530       gboolean stopped = TRUE;
1531
1532       if (encoder_class->stop)
1533         stopped = encoder_class->stop (encoder);
1534
1535       GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1536       gst_video_encoder_reset (encoder, TRUE);
1537       GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1538
1539       if (!stopped)
1540         goto stop_failed;
1541       break;
1542     }
1543     case GST_STATE_CHANGE_READY_TO_NULL:
1544       /* close device/library if needed */
1545       if (encoder_class->close && !encoder_class->close (encoder))
1546         goto close_failed;
1547       break;
1548     default:
1549       break;
1550   }
1551
1552   return ret;
1553
1554   /* Errors */
1555
1556 open_failed:
1557   {
1558     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1559         ("Failed to open encoder"));
1560     return GST_STATE_CHANGE_FAILURE;
1561   }
1562
1563 start_failed:
1564   {
1565     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1566         ("Failed to start encoder"));
1567     return GST_STATE_CHANGE_FAILURE;
1568   }
1569
1570 stop_failed:
1571   {
1572     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1573         ("Failed to stop encoder"));
1574     return GST_STATE_CHANGE_FAILURE;
1575   }
1576
1577 close_failed:
1578   {
1579     GST_ELEMENT_ERROR (encoder, LIBRARY, INIT, (NULL),
1580         ("Failed to close encoder"));
1581     return GST_STATE_CHANGE_FAILURE;
1582   }
1583 }
1584
1585 static gboolean
1586 gst_video_encoder_negotiate_default (GstVideoEncoder * encoder)
1587 {
1588   GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1589   GstAllocator *allocator;
1590   GstAllocationParams params;
1591   gboolean ret = TRUE;
1592   GstVideoCodecState *state = encoder->priv->output_state;
1593   GstVideoInfo *info = &state->info;
1594   GstQuery *query = NULL;
1595   GstVideoCodecFrame *frame;
1596   GstCaps *prevcaps;
1597
1598   g_return_val_if_fail (state->caps != NULL, FALSE);
1599
1600   if (encoder->priv->output_state_changed) {
1601     state->caps = gst_caps_make_writable (state->caps);
1602
1603     /* Fill caps */
1604     gst_caps_set_simple (state->caps, "width", G_TYPE_INT, info->width,
1605         "height", G_TYPE_INT, info->height,
1606         "pixel-aspect-ratio", GST_TYPE_FRACTION,
1607         info->par_n, info->par_d, NULL);
1608     if (info->flags & GST_VIDEO_FLAG_VARIABLE_FPS && info->fps_n != 0) {
1609       /* variable fps with a max-framerate */
1610       gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION, 0, 1,
1611           "max-framerate", GST_TYPE_FRACTION, info->fps_n, info->fps_d, NULL);
1612     } else {
1613       /* no variable fps or no max-framerate */
1614       gst_caps_set_simple (state->caps, "framerate", GST_TYPE_FRACTION,
1615           info->fps_n, info->fps_d, NULL);
1616     }
1617     if (state->codec_data)
1618       gst_caps_set_simple (state->caps, "codec_data", GST_TYPE_BUFFER,
1619           state->codec_data, NULL);
1620
1621     if (GST_VIDEO_INFO_MULTIVIEW_MODE (info) != GST_VIDEO_MULTIVIEW_MODE_NONE) {
1622       const gchar *caps_mview_mode =
1623           gst_video_multiview_mode_to_caps_string (GST_VIDEO_INFO_MULTIVIEW_MODE
1624           (info));
1625
1626       gst_caps_set_simple (state->caps, "multiview-mode", G_TYPE_STRING,
1627           caps_mview_mode, "multiview-flags", GST_TYPE_VIDEO_MULTIVIEW_FLAGSET,
1628           GST_VIDEO_INFO_MULTIVIEW_FLAGS (info), GST_FLAG_SET_MASK_EXACT, NULL);
1629     }
1630     encoder->priv->output_state_changed = FALSE;
1631   }
1632
1633   /* Push all pending pre-caps events of the oldest frame before
1634    * setting caps */
1635   frame = encoder->priv->frames ? encoder->priv->frames->data : NULL;
1636   if (frame || encoder->priv->current_frame_events) {
1637     GList **events, *l;
1638
1639     if (frame) {
1640       events = &frame->events;
1641     } else {
1642       events = &encoder->priv->current_frame_events;
1643     }
1644
1645     for (l = g_list_last (*events); l;) {
1646       GstEvent *event = GST_EVENT (l->data);
1647       GList *tmp;
1648
1649       if (GST_EVENT_TYPE (event) < GST_EVENT_CAPS) {
1650         gst_video_encoder_push_event (encoder, event);
1651         tmp = l;
1652         l = l->prev;
1653         *events = g_list_delete_link (*events, tmp);
1654       } else {
1655         l = l->prev;
1656       }
1657     }
1658   }
1659
1660   prevcaps = gst_pad_get_current_caps (encoder->srcpad);
1661   if (!prevcaps || !gst_caps_is_equal (prevcaps, state->caps))
1662     ret = gst_pad_set_caps (encoder->srcpad, state->caps);
1663   else
1664     ret = TRUE;
1665   if (prevcaps)
1666     gst_caps_unref (prevcaps);
1667
1668   if (!ret)
1669     goto done;
1670
1671   query = gst_query_new_allocation (state->caps, TRUE);
1672   if (!gst_pad_peer_query (encoder->srcpad, query)) {
1673     GST_DEBUG_OBJECT (encoder, "didn't get downstream ALLOCATION hints");
1674   }
1675
1676   g_assert (klass->decide_allocation != NULL);
1677   ret = klass->decide_allocation (encoder, query);
1678
1679   GST_DEBUG_OBJECT (encoder, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, ret,
1680       query);
1681
1682   if (!ret)
1683     goto no_decide_allocation;
1684
1685   /* we got configuration from our peer or the decide_allocation method,
1686    * parse them */
1687   if (gst_query_get_n_allocation_params (query) > 0) {
1688     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
1689   } else {
1690     allocator = NULL;
1691     gst_allocation_params_init (&params);
1692   }
1693
1694   if (encoder->priv->allocator)
1695     gst_object_unref (encoder->priv->allocator);
1696   encoder->priv->allocator = allocator;
1697   encoder->priv->params = params;
1698
1699 done:
1700   if (query)
1701     gst_query_unref (query);
1702
1703   return ret;
1704
1705   /* Errors */
1706 no_decide_allocation:
1707   {
1708     GST_WARNING_OBJECT (encoder, "Subclass failed to decide allocation");
1709     goto done;
1710   }
1711 }
1712
1713 static gboolean
1714 gst_video_encoder_negotiate_unlocked (GstVideoEncoder * encoder)
1715 {
1716   GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1717   gboolean ret = TRUE;
1718
1719   if (G_LIKELY (klass->negotiate))
1720     ret = klass->negotiate (encoder);
1721
1722   return ret;
1723 }
1724
1725 /**
1726  * gst_video_encoder_negotiate:
1727  * @encoder: a #GstVideoEncoder
1728  *
1729  * Negotiate with downstream elements to currently configured #GstVideoCodecState.
1730  * Unmark GST_PAD_FLAG_NEED_RECONFIGURE in any case. But mark it again if
1731  * negotiate fails.
1732  *
1733  * Returns: #TRUE if the negotiation succeeded, else #FALSE.
1734  */
1735 gboolean
1736 gst_video_encoder_negotiate (GstVideoEncoder * encoder)
1737 {
1738   GstVideoEncoderClass *klass;
1739   gboolean ret = TRUE;
1740
1741   g_return_val_if_fail (GST_IS_VIDEO_ENCODER (encoder), FALSE);
1742   g_return_val_if_fail (encoder->priv->output_state, FALSE);
1743
1744   klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1745
1746   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1747   gst_pad_check_reconfigure (encoder->srcpad);
1748   if (klass->negotiate) {
1749     ret = klass->negotiate (encoder);
1750     if (!ret)
1751       gst_pad_mark_reconfigure (encoder->srcpad);
1752   }
1753   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1754
1755   return ret;
1756 }
1757
1758 /**
1759  * gst_video_encoder_allocate_output_buffer:
1760  * @encoder: a #GstVideoEncoder
1761  * @size: size of the buffer
1762  *
1763  * Helper function that allocates a buffer to hold an encoded video frame
1764  * for @encoder's current #GstVideoCodecState.
1765  *
1766  * Returns: (transfer full): allocated buffer
1767  */
1768 GstBuffer *
1769 gst_video_encoder_allocate_output_buffer (GstVideoEncoder * encoder, gsize size)
1770 {
1771   GstBuffer *buffer;
1772   gboolean needs_reconfigure = FALSE;
1773
1774   g_return_val_if_fail (size > 0, NULL);
1775
1776   GST_DEBUG ("alloc src buffer");
1777
1778   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1779   needs_reconfigure = gst_pad_check_reconfigure (encoder->srcpad);
1780   if (G_UNLIKELY (encoder->priv->output_state_changed
1781           || (encoder->priv->output_state && needs_reconfigure))) {
1782     if (!gst_video_encoder_negotiate_unlocked (encoder)) {
1783       GST_DEBUG_OBJECT (encoder, "Failed to negotiate, fallback allocation");
1784       gst_pad_mark_reconfigure (encoder->srcpad);
1785       goto fallback;
1786     }
1787   }
1788
1789   buffer =
1790       gst_buffer_new_allocate (encoder->priv->allocator, size,
1791       &encoder->priv->params);
1792   if (!buffer) {
1793     GST_INFO_OBJECT (encoder, "couldn't allocate output buffer");
1794     goto fallback;
1795   }
1796
1797   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1798
1799   return buffer;
1800
1801 fallback:
1802   buffer = gst_buffer_new_allocate (NULL, size, NULL);
1803
1804   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1805
1806   return buffer;
1807 }
1808
1809 /**
1810  * gst_video_encoder_allocate_output_frame:
1811  * @encoder: a #GstVideoEncoder
1812  * @frame: a #GstVideoCodecFrame
1813  * @size: size of the buffer
1814  *
1815  * Helper function that allocates a buffer to hold an encoded video frame for @encoder's
1816  * current #GstVideoCodecState.  Subclass should already have configured video
1817  * state and set src pad caps.
1818  *
1819  * The buffer allocated here is owned by the frame and you should only
1820  * keep references to the frame, not the buffer.
1821  *
1822  * Returns: %GST_FLOW_OK if an output buffer could be allocated
1823  */
1824 GstFlowReturn
1825 gst_video_encoder_allocate_output_frame (GstVideoEncoder *
1826     encoder, GstVideoCodecFrame * frame, gsize size)
1827 {
1828   gboolean needs_reconfigure = FALSE;
1829
1830   g_return_val_if_fail (frame->output_buffer == NULL, GST_FLOW_ERROR);
1831
1832   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1833   needs_reconfigure = gst_pad_check_reconfigure (encoder->srcpad);
1834   if (G_UNLIKELY (encoder->priv->output_state_changed
1835           || (encoder->priv->output_state && needs_reconfigure))) {
1836     if (!gst_video_encoder_negotiate_unlocked (encoder)) {
1837       GST_DEBUG_OBJECT (encoder, "Failed to negotiate, fallback allocation");
1838       gst_pad_mark_reconfigure (encoder->srcpad);
1839     }
1840   }
1841
1842   GST_LOG_OBJECT (encoder, "alloc buffer size %" G_GSIZE_FORMAT, size);
1843
1844   frame->output_buffer =
1845       gst_buffer_new_allocate (encoder->priv->allocator, size,
1846       &encoder->priv->params);
1847
1848   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
1849
1850   return frame->output_buffer ? GST_FLOW_OK : GST_FLOW_ERROR;
1851 }
1852
1853 static void
1854 gst_video_encoder_release_frame (GstVideoEncoder * enc,
1855     GstVideoCodecFrame * frame)
1856 {
1857   GList *link;
1858
1859   /* unref once from the list */
1860   link = g_list_find (enc->priv->frames, frame);
1861   if (link) {
1862     gst_video_codec_frame_unref (frame);
1863     enc->priv->frames = g_list_delete_link (enc->priv->frames, link);
1864   }
1865   /* unref because this function takes ownership */
1866   gst_video_codec_frame_unref (frame);
1867 }
1868
1869 static gboolean
1870 gst_video_encoder_transform_meta_default (GstVideoEncoder *
1871     encoder, GstVideoCodecFrame * frame, GstMeta * meta)
1872 {
1873   const GstMetaInfo *info = meta->info;
1874   const gchar *const *tags;
1875
1876   tags = gst_meta_api_type_get_tags (info->api);
1877
1878   if (!tags || (g_strv_length ((gchar **) tags) == 1
1879           && gst_meta_api_type_has_tag (info->api,
1880               g_quark_from_string (GST_META_TAG_VIDEO_STR))))
1881     return TRUE;
1882
1883   return FALSE;
1884 }
1885
1886 typedef struct
1887 {
1888   GstVideoEncoder *encoder;
1889   GstVideoCodecFrame *frame;
1890 } CopyMetaData;
1891
1892 static gboolean
1893 foreach_metadata (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
1894 {
1895   CopyMetaData *data = user_data;
1896   GstVideoEncoder *encoder = data->encoder;
1897   GstVideoEncoderClass *klass = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1898   GstVideoCodecFrame *frame = data->frame;
1899   const GstMetaInfo *info = (*meta)->info;
1900   gboolean do_copy = FALSE;
1901
1902   if (gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory)) {
1903     /* never call the transform_meta with memory specific metadata */
1904     GST_DEBUG_OBJECT (encoder, "not copying memory specific metadata %s",
1905         g_type_name (info->api));
1906     do_copy = FALSE;
1907   } else if (klass->transform_meta) {
1908     do_copy = klass->transform_meta (encoder, frame, *meta);
1909     GST_DEBUG_OBJECT (encoder, "transformed metadata %s: copy: %d",
1910         g_type_name (info->api), do_copy);
1911   }
1912
1913   /* we only copy metadata when the subclass implemented a transform_meta
1914    * function and when it returns %TRUE */
1915   if (do_copy) {
1916     GstMetaTransformCopy copy_data = { FALSE, 0, -1 };
1917     GST_DEBUG_OBJECT (encoder, "copy metadata %s", g_type_name (info->api));
1918     /* simply copy then */
1919     info->transform_func (frame->output_buffer, *meta, inbuf,
1920         _gst_meta_transform_copy, &copy_data);
1921   }
1922   return TRUE;
1923 }
1924
1925 /**
1926  * gst_video_encoder_finish_frame:
1927  * @encoder: a #GstVideoEncoder
1928  * @frame: (transfer full): an encoded #GstVideoCodecFrame 
1929  *
1930  * @frame must have a valid encoded data buffer, whose metadata fields
1931  * are then appropriately set according to frame data or no buffer at
1932  * all if the frame should be dropped.
1933  * It is subsequently pushed downstream or provided to @pre_push.
1934  * In any case, the frame is considered finished and released.
1935  *
1936  * After calling this function the output buffer of the frame is to be
1937  * considered read-only. This function will also change the metadata
1938  * of the buffer.
1939  *
1940  * Returns: a #GstFlowReturn resulting from sending data downstream
1941  */
1942 GstFlowReturn
1943 gst_video_encoder_finish_frame (GstVideoEncoder * encoder,
1944     GstVideoCodecFrame * frame)
1945 {
1946   GstVideoEncoderPrivate *priv = encoder->priv;
1947   GstFlowReturn ret = GST_FLOW_OK;
1948   GstVideoEncoderClass *encoder_class;
1949   GList *l;
1950   gboolean send_headers = FALSE;
1951   gboolean discont = (frame->presentation_frame_number == 0);
1952   GstBuffer *buffer;
1953   gboolean needs_reconfigure = FALSE;
1954
1955   encoder_class = GST_VIDEO_ENCODER_GET_CLASS (encoder);
1956
1957   GST_LOG_OBJECT (encoder,
1958       "finish frame fpn %d", frame->presentation_frame_number);
1959
1960   GST_LOG_OBJECT (encoder, "frame PTS %" GST_TIME_FORMAT
1961       ", DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (frame->pts),
1962       GST_TIME_ARGS (frame->dts));
1963
1964   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
1965
1966   needs_reconfigure = gst_pad_check_reconfigure (encoder->srcpad);
1967   if (G_UNLIKELY (priv->output_state_changed || (priv->output_state
1968               && needs_reconfigure))) {
1969     if (!gst_video_encoder_negotiate_unlocked (encoder)) {
1970       gst_pad_mark_reconfigure (encoder->srcpad);
1971       if (GST_PAD_IS_FLUSHING (encoder->srcpad))
1972         ret = GST_FLOW_FLUSHING;
1973       else
1974         ret = GST_FLOW_NOT_NEGOTIATED;
1975       goto done;
1976     }
1977   }
1978
1979   if (G_UNLIKELY (priv->output_state == NULL))
1980     goto no_output_state;
1981
1982   /* Push all pending events that arrived before this frame */
1983   for (l = priv->frames; l; l = l->next) {
1984     GstVideoCodecFrame *tmp = l->data;
1985
1986     if (tmp->events) {
1987       GList *k;
1988
1989       for (k = g_list_last (tmp->events); k; k = k->prev)
1990         gst_video_encoder_push_event (encoder, k->data);
1991       g_list_free (tmp->events);
1992       tmp->events = NULL;
1993     }
1994
1995     if (tmp == frame)
1996       break;
1997   }
1998
1999   gst_video_encoder_check_and_push_tags (encoder);
2000
2001   /* no buffer data means this frame is skipped/dropped */
2002   if (!frame->output_buffer) {
2003     GST_DEBUG_OBJECT (encoder, "skipping frame %" GST_TIME_FORMAT,
2004         GST_TIME_ARGS (frame->pts));
2005     goto done;
2006   }
2007
2008   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame) && priv->force_key_unit) {
2009     GstClockTime stream_time, running_time;
2010     GstEvent *ev;
2011     ForcedKeyUnitEvent *fevt = NULL;
2012     GList *l;
2013
2014     running_time =
2015         gst_segment_to_running_time (&encoder->output_segment, GST_FORMAT_TIME,
2016         frame->pts);
2017
2018     GST_OBJECT_LOCK (encoder);
2019     for (l = priv->force_key_unit; l; l = l->next) {
2020       ForcedKeyUnitEvent *tmp = l->data;
2021
2022       /* Skip non-pending keyunits */
2023       if (!tmp->pending)
2024         continue;
2025
2026       /* Exact match using the frame id */
2027       if (frame->system_frame_number == tmp->frame_id) {
2028         fevt = tmp;
2029         break;
2030       }
2031
2032       /* Simple case, keyunit ASAP */
2033       if (tmp->running_time == GST_CLOCK_TIME_NONE) {
2034         fevt = tmp;
2035         break;
2036       }
2037
2038       /* Event for before this frame */
2039       if (tmp->running_time <= running_time) {
2040         fevt = tmp;
2041         break;
2042       }
2043     }
2044
2045     if (fevt) {
2046       priv->force_key_unit = g_list_remove (priv->force_key_unit, fevt);
2047     }
2048     GST_OBJECT_UNLOCK (encoder);
2049
2050     if (fevt) {
2051       stream_time =
2052           gst_segment_to_stream_time (&encoder->output_segment, GST_FORMAT_TIME,
2053           frame->pts);
2054
2055       ev = gst_video_event_new_downstream_force_key_unit
2056           (frame->pts, stream_time, running_time,
2057           fevt->all_headers, fevt->count);
2058
2059       gst_video_encoder_push_event (encoder, ev);
2060
2061       if (fevt->all_headers)
2062         send_headers = TRUE;
2063
2064       GST_DEBUG_OBJECT (encoder,
2065           "Forced key unit: running-time %" GST_TIME_FORMAT
2066           ", all_headers %d, count %u",
2067           GST_TIME_ARGS (running_time), fevt->all_headers, fevt->count);
2068       forced_key_unit_event_free (fevt);
2069     }
2070   }
2071
2072   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
2073     priv->distance_from_sync = 0;
2074     GST_BUFFER_FLAG_UNSET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2075     /* For keyframes, DTS = PTS, if encoder doesn't decide otherwise */
2076     if (!GST_CLOCK_TIME_IS_VALID (frame->dts)) {
2077       frame->dts = frame->pts;
2078     }
2079   } else {
2080     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2081   }
2082
2083   /* DTS is expected monotone ascending,
2084    * so a good guess is the lowest unsent PTS (all being OK) */
2085   {
2086     GstClockTime min_ts = GST_CLOCK_TIME_NONE;
2087     GstVideoCodecFrame *oframe = NULL;
2088     gboolean seen_none = FALSE;
2089
2090     /* some maintenance regardless */
2091     for (l = priv->frames; l; l = l->next) {
2092       GstVideoCodecFrame *tmp = l->data;
2093
2094       if (!GST_CLOCK_TIME_IS_VALID (tmp->abidata.ABI.ts)) {
2095         seen_none = TRUE;
2096         continue;
2097       }
2098
2099       if (!GST_CLOCK_TIME_IS_VALID (min_ts) || tmp->abidata.ABI.ts < min_ts) {
2100         min_ts = tmp->abidata.ABI.ts;
2101         oframe = tmp;
2102       }
2103     }
2104     /* save a ts if needed */
2105     if (oframe && oframe != frame) {
2106       oframe->abidata.ABI.ts = frame->abidata.ABI.ts;
2107     }
2108
2109     /* and set if needed */
2110     if (!GST_CLOCK_TIME_IS_VALID (frame->dts) && !seen_none) {
2111       frame->dts = min_ts;
2112       GST_DEBUG_OBJECT (encoder,
2113           "no valid DTS, using oldest PTS %" GST_TIME_FORMAT,
2114           GST_TIME_ARGS (frame->pts));
2115     }
2116   }
2117
2118   frame->distance_from_sync = priv->distance_from_sync;
2119   priv->distance_from_sync++;
2120
2121   GST_BUFFER_PTS (frame->output_buffer) = frame->pts;
2122   GST_BUFFER_DTS (frame->output_buffer) = frame->dts;
2123   GST_BUFFER_DURATION (frame->output_buffer) = frame->duration;
2124
2125   /* update rate estimate */
2126   priv->bytes += gst_buffer_get_size (frame->output_buffer);
2127   if (GST_CLOCK_TIME_IS_VALID (frame->duration)) {
2128     priv->time += frame->duration;
2129   } else {
2130     /* better none than nothing valid */
2131     priv->time = GST_CLOCK_TIME_NONE;
2132   }
2133
2134   if (G_UNLIKELY (send_headers || priv->new_headers)) {
2135     GList *tmp, *copy = NULL;
2136
2137     GST_DEBUG_OBJECT (encoder, "Sending headers");
2138
2139     /* First make all buffers metadata-writable */
2140     for (tmp = priv->headers; tmp; tmp = tmp->next) {
2141       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
2142
2143       copy = g_list_append (copy, gst_buffer_make_writable (tmpbuf));
2144     }
2145     g_list_free (priv->headers);
2146     priv->headers = copy;
2147
2148     for (tmp = priv->headers; tmp; tmp = tmp->next) {
2149       GstBuffer *tmpbuf = GST_BUFFER (tmp->data);
2150
2151       priv->bytes += gst_buffer_get_size (tmpbuf);
2152       if (G_UNLIKELY (discont)) {
2153         GST_LOG_OBJECT (encoder, "marking discont");
2154         GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
2155         discont = FALSE;
2156       }
2157
2158       gst_pad_push (encoder->srcpad, gst_buffer_ref (tmpbuf));
2159     }
2160     priv->new_headers = FALSE;
2161   }
2162
2163   if (G_UNLIKELY (discont)) {
2164     GST_LOG_OBJECT (encoder, "marking discont");
2165     GST_BUFFER_FLAG_SET (frame->output_buffer, GST_BUFFER_FLAG_DISCONT);
2166   }
2167
2168   if (encoder_class->pre_push)
2169     ret = encoder_class->pre_push (encoder, frame);
2170
2171   if (encoder_class->transform_meta) {
2172     if (G_LIKELY (frame->input_buffer)) {
2173       CopyMetaData data;
2174
2175       data.encoder = encoder;
2176       data.frame = frame;
2177       gst_buffer_foreach_meta (frame->input_buffer, foreach_metadata, &data);
2178     } else {
2179       GST_WARNING_OBJECT (encoder,
2180           "Can't copy metadata because input frame disappeared");
2181     }
2182   }
2183
2184   /* Get an additional ref to the buffer, which is going to be pushed
2185    * downstream, the original ref is owned by the frame */
2186   buffer = gst_buffer_ref (frame->output_buffer);
2187
2188   /* Release frame so the buffer is writable when we push it downstream
2189    * if possible, i.e. if the subclass does not hold additional references
2190    * to the frame
2191    */
2192   gst_video_encoder_release_frame (encoder, frame);
2193   frame = NULL;
2194
2195   if (ret == GST_FLOW_OK)
2196     ret = gst_pad_push (encoder->srcpad, buffer);
2197
2198 done:
2199   /* handed out */
2200   if (frame)
2201     gst_video_encoder_release_frame (encoder, frame);
2202
2203   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2204
2205   return ret;
2206
2207   /* ERRORS */
2208 no_output_state:
2209   {
2210     gst_video_encoder_release_frame (encoder, frame);
2211     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2212     GST_ERROR_OBJECT (encoder, "Output state was not configured");
2213     return GST_FLOW_ERROR;
2214   }
2215 }
2216
2217 /**
2218  * gst_video_encoder_get_output_state:
2219  * @encoder: a #GstVideoEncoder
2220  *
2221  * Get the current #GstVideoCodecState
2222  *
2223  * Returns: (transfer full): #GstVideoCodecState describing format of video data.
2224  */
2225 GstVideoCodecState *
2226 gst_video_encoder_get_output_state (GstVideoEncoder * encoder)
2227 {
2228   GstVideoCodecState *state;
2229
2230   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2231   state = gst_video_codec_state_ref (encoder->priv->output_state);
2232   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2233
2234   return state;
2235 }
2236
2237 /**
2238  * gst_video_encoder_set_output_state:
2239  * @encoder: a #GstVideoEncoder
2240  * @caps: (transfer full): the #GstCaps to use for the output
2241  * @reference: (allow-none) (transfer none): An optional reference @GstVideoCodecState
2242  *
2243  * Creates a new #GstVideoCodecState with the specified caps as the output state
2244  * for the encoder.
2245  * Any previously set output state on @encoder will be replaced by the newly
2246  * created one.
2247  *
2248  * The specified @caps should not contain any resolution, pixel-aspect-ratio,
2249  * framerate, codec-data, .... Those should be specified instead in the returned
2250  * #GstVideoCodecState.
2251  *
2252  * If the subclass wishes to copy over existing fields (like pixel aspect ratio,
2253  * or framerate) from an existing #GstVideoCodecState, it can be provided as a
2254  * @reference.
2255  *
2256  * If the subclass wishes to override some fields from the output state (like
2257  * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
2258  *
2259  * The new output state will only take effect (set on pads and buffers) starting
2260  * from the next call to #gst_video_encoder_finish_frame().
2261  *
2262  * Returns: (transfer full): the newly configured output state.
2263  */
2264 GstVideoCodecState *
2265 gst_video_encoder_set_output_state (GstVideoEncoder * encoder, GstCaps * caps,
2266     GstVideoCodecState * reference)
2267 {
2268   GstVideoEncoderPrivate *priv = encoder->priv;
2269   GstVideoCodecState *state;
2270
2271   g_return_val_if_fail (caps != NULL, NULL);
2272
2273   state = _new_output_state (caps, reference);
2274
2275   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2276   if (priv->output_state)
2277     gst_video_codec_state_unref (priv->output_state);
2278   priv->output_state = gst_video_codec_state_ref (state);
2279
2280   priv->output_state_changed = TRUE;
2281   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2282
2283   return state;
2284 }
2285
2286 /**
2287  * gst_video_encoder_set_latency:
2288  * @encoder: a #GstVideoEncoder
2289  * @min_latency: minimum latency
2290  * @max_latency: maximum latency
2291  *
2292  * Informs baseclass of encoding latency.
2293  */
2294 void
2295 gst_video_encoder_set_latency (GstVideoEncoder * encoder,
2296     GstClockTime min_latency, GstClockTime max_latency)
2297 {
2298   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
2299   g_return_if_fail (max_latency >= min_latency);
2300
2301   GST_OBJECT_LOCK (encoder);
2302   encoder->priv->min_latency = min_latency;
2303   encoder->priv->max_latency = max_latency;
2304   GST_OBJECT_UNLOCK (encoder);
2305
2306   gst_element_post_message (GST_ELEMENT_CAST (encoder),
2307       gst_message_new_latency (GST_OBJECT_CAST (encoder)));
2308 }
2309
2310 /**
2311  * gst_video_encoder_get_latency:
2312  * @encoder: a #GstVideoEncoder
2313  * @min_latency: (out) (allow-none): address of variable in which to store the
2314  *     configured minimum latency, or %NULL
2315  * @max_latency: (out) (allow-none): address of variable in which to store the
2316  *     configured maximum latency, or %NULL
2317  *
2318  * Query the configured encoding latency. Results will be returned via
2319  * @min_latency and @max_latency.
2320  */
2321 void
2322 gst_video_encoder_get_latency (GstVideoEncoder * encoder,
2323     GstClockTime * min_latency, GstClockTime * max_latency)
2324 {
2325   GST_OBJECT_LOCK (encoder);
2326   if (min_latency)
2327     *min_latency = encoder->priv->min_latency;
2328   if (max_latency)
2329     *max_latency = encoder->priv->max_latency;
2330   GST_OBJECT_UNLOCK (encoder);
2331 }
2332
2333 /**
2334  * gst_video_encoder_get_oldest_frame:
2335  * @encoder: a #GstVideoEncoder
2336  *
2337  * Get the oldest unfinished pending #GstVideoCodecFrame
2338  *
2339  * Returns: (transfer full): oldest unfinished pending #GstVideoCodecFrame
2340  */
2341 GstVideoCodecFrame *
2342 gst_video_encoder_get_oldest_frame (GstVideoEncoder * encoder)
2343 {
2344   GstVideoCodecFrame *frame = NULL;
2345
2346   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2347   if (encoder->priv->frames)
2348     frame = gst_video_codec_frame_ref (encoder->priv->frames->data);
2349   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2350
2351   return (GstVideoCodecFrame *) frame;
2352 }
2353
2354 /**
2355  * gst_video_encoder_get_frame:
2356  * @encoder: a #GstVideoEnccoder
2357  * @frame_number: system_frame_number of a frame
2358  *
2359  * Get a pending unfinished #GstVideoCodecFrame
2360  * 
2361  * Returns: (transfer full): pending unfinished #GstVideoCodecFrame identified by @frame_number.
2362  */
2363 GstVideoCodecFrame *
2364 gst_video_encoder_get_frame (GstVideoEncoder * encoder, int frame_number)
2365 {
2366   GList *g;
2367   GstVideoCodecFrame *frame = NULL;
2368
2369   GST_DEBUG_OBJECT (encoder, "frame_number : %d", frame_number);
2370
2371   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2372   for (g = encoder->priv->frames; g; g = g->next) {
2373     GstVideoCodecFrame *tmp = g->data;
2374
2375     if (tmp->system_frame_number == frame_number) {
2376       frame = gst_video_codec_frame_ref (tmp);
2377       break;
2378     }
2379   }
2380   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2381
2382   return frame;
2383 }
2384
2385 /**
2386  * gst_video_encoder_get_frames:
2387  * @encoder: a #GstVideoEncoder
2388  *
2389  * Get all pending unfinished #GstVideoCodecFrame
2390  * 
2391  * Returns: (transfer full) (element-type GstVideoCodecFrame): pending unfinished #GstVideoCodecFrame.
2392  */
2393 GList *
2394 gst_video_encoder_get_frames (GstVideoEncoder * encoder)
2395 {
2396   GList *frames;
2397
2398   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2399   frames = g_list_copy (encoder->priv->frames);
2400   g_list_foreach (frames, (GFunc) gst_video_codec_frame_ref, NULL);
2401   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2402
2403   return frames;
2404 }
2405
2406 /**
2407  * gst_video_encoder_merge_tags:
2408  * @encoder: a #GstVideoEncoder
2409  * @tags: (allow-none): a #GstTagList to merge, or NULL to unset
2410  *     previously-set tags
2411  * @mode: the #GstTagMergeMode to use, usually #GST_TAG_MERGE_REPLACE
2412  *
2413  * Sets the video encoder tags and how they should be merged with any
2414  * upstream stream tags. This will override any tags previously-set
2415  * with gst_video_encoder_merge_tags().
2416  *
2417  * Note that this is provided for convenience, and the subclass is
2418  * not required to use this and can still do tag handling on its own.
2419  *
2420  * MT safe.
2421  */
2422 void
2423 gst_video_encoder_merge_tags (GstVideoEncoder * encoder,
2424     const GstTagList * tags, GstTagMergeMode mode)
2425 {
2426   g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
2427   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
2428   g_return_if_fail (tags == NULL || mode != GST_TAG_MERGE_UNDEFINED);
2429
2430   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
2431   if (encoder->priv->tags != tags) {
2432     if (encoder->priv->tags) {
2433       gst_tag_list_unref (encoder->priv->tags);
2434       encoder->priv->tags = NULL;
2435       encoder->priv->tags_merge_mode = GST_TAG_MERGE_APPEND;
2436     }
2437     if (tags) {
2438       encoder->priv->tags = gst_tag_list_ref ((GstTagList *) tags);
2439       encoder->priv->tags_merge_mode = mode;
2440     }
2441
2442     GST_DEBUG_OBJECT (encoder, "setting encoder tags to %" GST_PTR_FORMAT,
2443         tags);
2444     encoder->priv->tags_changed = TRUE;
2445   }
2446   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
2447 }
2448
2449 /**
2450  * gst_video_encoder_get_allocator:
2451  * @encoder: a #GstVideoEncoder
2452  * @allocator: (out) (allow-none) (transfer full): the #GstAllocator
2453  * used
2454  * @params: (out) (allow-none) (transfer full): the
2455  * #GstAllocatorParams of @allocator
2456  *
2457  * Lets #GstVideoEncoder sub-classes to know the memory @allocator
2458  * used by the base class and its @params.
2459  *
2460  * Unref the @allocator after use it.
2461  */
2462 void
2463 gst_video_encoder_get_allocator (GstVideoEncoder * encoder,
2464     GstAllocator ** allocator, GstAllocationParams * params)
2465 {
2466   g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
2467
2468   if (allocator)
2469     *allocator = encoder->priv->allocator ?
2470         gst_object_ref (encoder->priv->allocator) : NULL;
2471
2472   if (params)
2473     *params = encoder->priv->params;
2474 }
2475
2476 /**
2477  * gst_video_encoder_set_min_pts:
2478  * @encoder: a #GstVideoEncoder
2479  * @min_pts: minimal PTS that will be passed to handle_frame
2480  *
2481  * Request minimal value for PTS passed to handle_frame.
2482  *
2483  * For streams with reordered frames this can be used to ensure that there
2484  * is enough time to accomodate first DTS, which may be less than first PTS
2485  *
2486  * Since 1.6
2487  */
2488 void
2489 gst_video_encoder_set_min_pts (GstVideoEncoder * encoder, GstClockTime min_pts)
2490 {
2491   g_return_if_fail (GST_IS_VIDEO_ENCODER (encoder));
2492   encoder->priv->min_pts = min_pts;
2493   encoder->priv->time_adjustment = GST_CLOCK_TIME_NONE;
2494 }