v4l2videoenc: support force keyframe event in v4l2 encoder
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / sys / v4l2 / gstv4l2videoenc.c
1 /*
2  * Copyright (C) 2014-2017 SUMOMO Computer Association
3  *     Authors Ayaka <ayaka@soulik.info>
4  * Copyright (C) 2017 Collabora Ltd.
5  *     Author: Nicolas Dufresne <nicolas.dufresne@collabora.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <string.h>
33
34 #include "gstv4l2object.h"
35 #include "gstv4l2videoenc.h"
36
37 #include <string.h>
38 #include <glib/gi18n-lib.h>
39
40 GST_DEBUG_CATEGORY_STATIC (gst_v4l2_video_enc_debug);
41 #define GST_CAT_DEFAULT gst_v4l2_video_enc_debug
42
43 typedef struct
44 {
45   gchar *device;
46   GstCaps *sink_caps;
47   GstCaps *src_caps;
48   const GstV4l2Codec *codec;
49 } GstV4l2VideoEncCData;
50
51 enum
52 {
53   PROP_0,
54   V4L2_STD_OBJECT_PROPS,
55 };
56
57 #define gst_v4l2_video_enc_parent_class parent_class
58 G_DEFINE_ABSTRACT_TYPE (GstV4l2VideoEnc, gst_v4l2_video_enc,
59     GST_TYPE_VIDEO_ENCODER);
60
61 static void
62 gst_v4l2_video_enc_set_property (GObject * object,
63     guint prop_id, const GValue * value, GParamSpec * pspec)
64 {
65   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
66
67   switch (prop_id) {
68     case PROP_CAPTURE_IO_MODE:
69       if (!gst_v4l2_object_set_property_helper (self->v4l2capture,
70               prop_id, value, pspec)) {
71         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
72       }
73       break;
74
75       /* By default, only set on output */
76     default:
77       if (!gst_v4l2_object_set_property_helper (self->v4l2output,
78               prop_id, value, pspec)) {
79         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
80       }
81       break;
82   }
83 }
84
85 static void
86 gst_v4l2_video_enc_get_property (GObject * object,
87     guint prop_id, GValue * value, GParamSpec * pspec)
88 {
89   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
90
91   switch (prop_id) {
92     case PROP_CAPTURE_IO_MODE:
93       if (!gst_v4l2_object_get_property_helper (self->v4l2capture,
94               prop_id, value, pspec)) {
95         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
96       }
97       break;
98
99       /* By default read from output */
100     default:
101       if (!gst_v4l2_object_get_property_helper (self->v4l2output,
102               prop_id, value, pspec)) {
103         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
104       }
105       break;
106   }
107 }
108
109 static gboolean
110 gst_v4l2_video_enc_open (GstVideoEncoder * encoder)
111 {
112   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
113   GstV4l2Error error = GST_V4L2_ERROR_INIT;
114   GstCaps *codec_caps;
115
116   GST_DEBUG_OBJECT (self, "Opening");
117
118   if (!gst_v4l2_object_open (self->v4l2output, &error))
119     goto failure;
120
121   if (!gst_v4l2_object_open_shared (self->v4l2capture, self->v4l2output))
122     goto failure;
123
124   self->probed_sinkcaps = gst_v4l2_object_probe_caps (self->v4l2output,
125       gst_v4l2_object_get_raw_caps ());
126
127   if (gst_caps_is_empty (self->probed_sinkcaps))
128     goto no_raw_format;
129
130   codec_caps = gst_pad_get_pad_template_caps (encoder->srcpad);
131   self->probed_srccaps = gst_v4l2_object_probe_caps (self->v4l2capture,
132       codec_caps);
133   gst_caps_unref (codec_caps);
134
135   if (gst_caps_is_empty (self->probed_srccaps))
136     goto no_encoded_format;
137
138   return TRUE;
139
140 no_encoded_format:
141   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
142       (_("Encoder on device %s has no supported output format"),
143           self->v4l2output->videodev), (NULL));
144   goto failure;
145
146
147 no_raw_format:
148   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
149       (_("Encoder on device %s has no supported input format"),
150           self->v4l2output->videodev), (NULL));
151   goto failure;
152
153 failure:
154   if (GST_V4L2_IS_OPEN (self->v4l2output))
155     gst_v4l2_object_close (self->v4l2output);
156
157   if (GST_V4L2_IS_OPEN (self->v4l2capture))
158     gst_v4l2_object_close (self->v4l2capture);
159
160   gst_caps_replace (&self->probed_srccaps, NULL);
161   gst_caps_replace (&self->probed_sinkcaps, NULL);
162
163   gst_v4l2_error (self, &error);
164
165   return FALSE;
166 }
167
168 static gboolean
169 gst_v4l2_video_enc_close (GstVideoEncoder * encoder)
170 {
171   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
172
173   GST_DEBUG_OBJECT (self, "Closing");
174
175   gst_v4l2_object_close (self->v4l2output);
176   gst_v4l2_object_close (self->v4l2capture);
177   gst_caps_replace (&self->probed_srccaps, NULL);
178   gst_caps_replace (&self->probed_sinkcaps, NULL);
179
180   return TRUE;
181 }
182
183 static gboolean
184 gst_v4l2_video_enc_start (GstVideoEncoder * encoder)
185 {
186   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
187
188   GST_DEBUG_OBJECT (self, "Starting");
189
190   gst_v4l2_object_unlock (self->v4l2output);
191   g_atomic_int_set (&self->active, TRUE);
192   self->output_flow = GST_FLOW_OK;
193
194   return TRUE;
195 }
196
197 static gboolean
198 gst_v4l2_video_enc_stop (GstVideoEncoder * encoder)
199 {
200   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
201
202   GST_DEBUG_OBJECT (self, "Stopping");
203
204   gst_v4l2_object_unlock (self->v4l2output);
205   gst_v4l2_object_unlock (self->v4l2capture);
206
207   /* Wait for capture thread to stop */
208   gst_pad_stop_task (encoder->srcpad);
209
210   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
211   self->output_flow = GST_FLOW_OK;
212   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
213
214   /* Should have been flushed already */
215   g_assert (g_atomic_int_get (&self->active) == FALSE);
216   g_assert (g_atomic_int_get (&self->processing) == FALSE);
217
218   gst_v4l2_object_stop (self->v4l2output);
219   gst_v4l2_object_stop (self->v4l2capture);
220
221   if (self->input_state) {
222     gst_video_codec_state_unref (self->input_state);
223     self->input_state = NULL;
224   }
225
226   GST_DEBUG_OBJECT (self, "Stopped");
227
228   return TRUE;
229 }
230
231 static gboolean
232 gst_v4l2_encoder_cmd (GstV4l2Object * v4l2object, guint cmd, guint flags)
233 {
234   struct v4l2_encoder_cmd ecmd = { 0, };
235
236   GST_DEBUG_OBJECT (v4l2object->element,
237       "sending v4l2 encoder command %u with flags %u", cmd, flags);
238
239   if (!GST_V4L2_IS_OPEN (v4l2object))
240     return FALSE;
241
242   ecmd.cmd = cmd;
243   ecmd.flags = flags;
244   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_ENCODER_CMD, &ecmd) < 0)
245     goto ecmd_failed;
246
247   return TRUE;
248
249 ecmd_failed:
250   if (errno == ENOTTY) {
251     GST_INFO_OBJECT (v4l2object->element,
252         "Failed to send encoder command %u with flags %u for '%s'. (%s)",
253         cmd, flags, v4l2object->videodev, g_strerror (errno));
254   } else {
255     GST_ERROR_OBJECT (v4l2object->element,
256         "Failed to send encoder command %u with flags %u for '%s'. (%s)",
257         cmd, flags, v4l2object->videodev, g_strerror (errno));
258   }
259   return FALSE;
260 }
261
262 static GstFlowReturn
263 gst_v4l2_video_enc_finish (GstVideoEncoder * encoder)
264 {
265   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
266   GstFlowReturn ret = GST_FLOW_OK;
267
268   if (gst_pad_get_task_state (encoder->srcpad) != GST_TASK_STARTED)
269     goto done;
270
271   GST_DEBUG_OBJECT (self, "Finishing encoding");
272
273   /* drop the stream lock while draining, so remaining buffers can be
274    * pushed from the src pad task thread */
275   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
276
277   if (gst_v4l2_encoder_cmd (self->v4l2capture, V4L2_ENC_CMD_STOP, 0)) {
278     GstTask *task = encoder->srcpad->task;
279
280     /* Wait for the task to be drained */
281     GST_DEBUG_OBJECT (self, "Waiting for encoder stop");
282     GST_OBJECT_LOCK (task);
283     while (GST_TASK_STATE (task) == GST_TASK_STARTED)
284       GST_TASK_WAIT (task);
285     GST_OBJECT_UNLOCK (task);
286     ret = GST_FLOW_FLUSHING;
287   }
288
289   /* and ensure the processing thread has stopped in case another error
290    * occurred. */
291   gst_v4l2_object_unlock (self->v4l2capture);
292   gst_pad_stop_task (encoder->srcpad);
293   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
294
295   if (ret == GST_FLOW_FLUSHING)
296     ret = self->output_flow;
297
298   GST_DEBUG_OBJECT (encoder, "Done draining buffers");
299
300 done:
301   return ret;
302 }
303
304 static gboolean
305 gst_v4l2_video_enc_set_format (GstVideoEncoder * encoder,
306     GstVideoCodecState * state)
307 {
308   gboolean ret = TRUE;
309   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
310   GstV4l2Error error = GST_V4L2_ERROR_INIT;
311   GstCaps *outcaps;
312   GstVideoCodecState *output;
313
314   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
315
316   if (self->input_state) {
317     if (gst_v4l2_object_caps_equal (self->v4l2output, state->caps)) {
318       GST_DEBUG_OBJECT (self, "Compatible caps");
319       return TRUE;
320     }
321
322     if (gst_v4l2_video_enc_finish (encoder) != GST_FLOW_OK)
323       return FALSE;
324
325     gst_v4l2_object_stop (self->v4l2output);
326     gst_v4l2_object_stop (self->v4l2capture);
327
328     gst_video_codec_state_unref (self->input_state);
329     self->input_state = NULL;
330   }
331
332   outcaps = gst_pad_get_pad_template_caps (encoder->srcpad);
333   outcaps = gst_caps_make_writable (outcaps);
334   output = gst_video_encoder_set_output_state (encoder, outcaps, state);
335   gst_video_codec_state_unref (output);
336
337   if (!gst_video_encoder_negotiate (encoder))
338     return FALSE;
339
340   if (!gst_v4l2_object_set_format (self->v4l2output, state->caps, &error)) {
341     gst_v4l2_error (self, &error);
342     return FALSE;
343   }
344
345   /* best effort */
346   gst_v4l2_object_setup_padding (self->v4l2output);
347
348   self->input_state = gst_video_codec_state_ref (state);
349
350   GST_DEBUG_OBJECT (self, "output caps: %" GST_PTR_FORMAT, state->caps);
351
352   return ret;
353 }
354
355 static gboolean
356 gst_v4l2_video_enc_flush (GstVideoEncoder * encoder)
357 {
358   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
359
360   GST_DEBUG_OBJECT (self, "Flushing");
361
362   /* Ensure the processing thread has stopped for the reverse playback
363    * iscount case */
364   if (g_atomic_int_get (&self->processing)) {
365     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
366
367     gst_v4l2_object_unlock_stop (self->v4l2output);
368     gst_v4l2_object_unlock_stop (self->v4l2capture);
369     gst_pad_stop_task (encoder->srcpad);
370
371     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
372
373   }
374
375   self->output_flow = GST_FLOW_OK;
376
377   gst_v4l2_object_unlock_stop (self->v4l2output);
378   gst_v4l2_object_unlock_stop (self->v4l2capture);
379
380   return TRUE;
381 }
382
383 struct ProfileLevelCtx
384 {
385   GstV4l2VideoEnc *self;
386   const gchar *profile;
387   const gchar *level;
388 };
389
390 static gboolean
391 get_string_list (GstStructure * s, const gchar * field, GQueue * queue)
392 {
393   const GValue *value;
394
395   value = gst_structure_get_value (s, field);
396
397   if (!value)
398     return FALSE;
399
400   if (GST_VALUE_HOLDS_LIST (value)) {
401     guint i;
402
403     if (gst_value_list_get_size (value) == 0)
404       return FALSE;
405
406     for (i = 0; i < gst_value_list_get_size (value); i++) {
407       const GValue *item = gst_value_list_get_value (value, i);
408
409       if (G_VALUE_HOLDS_STRING (item))
410         g_queue_push_tail (queue, g_value_dup_string (item));
411     }
412   } else if (G_VALUE_HOLDS_STRING (value)) {
413     g_queue_push_tail (queue, g_value_dup_string (value));
414   }
415
416   return TRUE;
417 }
418
419 static gboolean
420 negotiate_profile_and_level (GstCapsFeatures * features, GstStructure * s,
421     gpointer user_data)
422 {
423   struct ProfileLevelCtx *ctx = user_data;
424   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (ctx->self);
425   GstV4l2Object *v4l2object = GST_V4L2_VIDEO_ENC (ctx->self)->v4l2output;
426   GQueue profiles = G_QUEUE_INIT;
427   GQueue levels = G_QUEUE_INIT;
428   gboolean failed = FALSE;
429   const GstV4l2Codec *codec = klass->codec;
430
431   if (codec->profile_cid && get_string_list (s, "profile", &profiles)) {
432     GList *l;
433
434     for (l = profiles.head; l; l = l->next) {
435       struct v4l2_control control = { 0, };
436       gint v4l2_profile;
437       const gchar *profile = l->data;
438
439       GST_TRACE_OBJECT (ctx->self, "Trying profile %s", profile);
440
441       control.id = codec->profile_cid;
442
443       control.value = v4l2_profile = codec->profile_from_string (profile);
444
445       if (control.value < 0)
446         continue;
447
448       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
449         GST_WARNING_OBJECT (ctx->self, "Failed to set %s profile: '%s'",
450             klass->codec_name, g_strerror (errno));
451         break;
452       }
453
454       profile = codec->profile_to_string (control.value);
455
456       if (control.value == v4l2_profile) {
457         ctx->profile = profile;
458         break;
459       }
460
461       if (g_list_find_custom (l, profile, g_str_equal)) {
462         ctx->profile = profile;
463         break;
464       }
465     }
466
467     if (profiles.length && !ctx->profile)
468       failed = TRUE;
469
470     g_queue_foreach (&profiles, (GFunc) g_free, NULL);
471     g_queue_clear (&profiles);
472   }
473
474   if (!failed && codec->level_cid && get_string_list (s, "level", &levels)) {
475     GList *l;
476
477     for (l = levels.head; l; l = l->next) {
478       struct v4l2_control control = { 0, };
479       gint v4l2_level;
480       const gchar *level = l->data;
481
482       GST_TRACE_OBJECT (ctx->self, "Trying level %s", level);
483
484       control.id = codec->level_cid;
485       control.value = v4l2_level = codec->level_from_string (level);
486
487       if (control.value < 0)
488         continue;
489
490       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
491         GST_WARNING_OBJECT (ctx->self, "Failed to set %s level: '%s'",
492             klass->codec_name, g_strerror (errno));
493         break;
494       }
495
496       level = codec->level_to_string (control.value);
497
498       if (control.value == v4l2_level) {
499         ctx->level = level;
500         break;
501       }
502
503       if (g_list_find_custom (l, level, g_str_equal)) {
504         ctx->level = level;
505         break;
506       }
507     }
508
509     if (levels.length && !ctx->level)
510       failed = TRUE;
511
512     g_queue_foreach (&levels, (GFunc) g_free, NULL);
513     g_queue_clear (&levels);
514   }
515
516   /* If it failed, we continue */
517   return failed;
518 }
519
520 static gboolean
521 gst_v4l2_video_enc_negotiate (GstVideoEncoder * encoder)
522 {
523   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (encoder);
524   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
525   GstV4l2Object *v4l2object = self->v4l2output;
526   GstCaps *allowed_caps;
527   struct ProfileLevelCtx ctx = { self, NULL, NULL };
528   GstVideoCodecState *state;
529   GstStructure *s;
530   const GstV4l2Codec *codec = klass->codec;
531
532   GST_DEBUG_OBJECT (self, "Negotiating %s profile and level.",
533       klass->codec_name);
534
535   /* Only renegotiate on upstream changes */
536   if (self->input_state)
537     return TRUE;
538
539   if (!codec)
540     goto done;
541
542   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (encoder));
543
544   if (allowed_caps) {
545
546     if (gst_caps_is_empty (allowed_caps))
547       goto not_negotiated;
548
549     allowed_caps = gst_caps_make_writable (allowed_caps);
550
551     /* negotiate_profile_and_level() will return TRUE on failure to keep
552      * iterating, if gst_caps_foreach() returns TRUE it means there was no
553      * compatible profile and level in any of the structure */
554     if (gst_caps_foreach (allowed_caps, negotiate_profile_and_level, &ctx)) {
555       goto no_profile_level;
556     }
557
558     gst_caps_unref (allowed_caps);
559     allowed_caps = NULL;
560   }
561
562   if (codec->profile_cid && !ctx.profile) {
563     struct v4l2_control control = { 0, };
564
565     control.id = codec->profile_cid;
566
567     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
568       goto g_ctrl_failed;
569
570     ctx.profile = codec->profile_to_string (control.value);
571   }
572
573   if (codec->level_cid && !ctx.level) {
574     struct v4l2_control control = { 0, };
575
576     control.id = codec->level_cid;
577
578     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
579       goto g_ctrl_failed;
580
581     ctx.level = codec->level_to_string (control.value);
582   }
583
584   GST_DEBUG_OBJECT (self, "Selected %s profile %s at level %s",
585       klass->codec_name, ctx.profile, ctx.level);
586
587   state = gst_video_encoder_get_output_state (encoder);
588   s = gst_caps_get_structure (state->caps, 0);
589
590   if (codec->profile_cid)
591     gst_structure_set (s, "profile", G_TYPE_STRING, ctx.profile, NULL);
592
593   if (codec->level_cid)
594     gst_structure_set (s, "level", G_TYPE_STRING, ctx.level, NULL);
595
596 done:
597   if (!GST_VIDEO_ENCODER_CLASS (parent_class)->negotiate (encoder))
598     return FALSE;
599
600   return TRUE;
601
602 g_ctrl_failed:
603   GST_WARNING_OBJECT (self, "Failed to get %s profile and level: '%s'",
604       klass->codec_name, g_strerror (errno));
605   goto not_negotiated;
606
607 no_profile_level:
608   GST_WARNING_OBJECT (self, "No compatible level and profile in caps: %"
609       GST_PTR_FORMAT, allowed_caps);
610   goto not_negotiated;
611
612 not_negotiated:
613   if (allowed_caps)
614     gst_caps_unref (allowed_caps);
615   return FALSE;
616 }
617
618 static gboolean
619 check_system_frame_number_too_old (guint32 current, guint32 old)
620 {
621   guint32 absdiff = current > old ? current - old : old - current;
622
623   /* More than 100 frames in the past, or current wrapped around */
624   if (absdiff > 100) {
625     /* Wraparound and difference is actually smaller than 100 */
626     if (absdiff > G_MAXUINT32 - 100)
627       return FALSE;
628     return TRUE;
629   }
630
631   return FALSE;
632 }
633
634 static void
635 gst_v4l2_video_enc_loop (GstVideoEncoder * encoder)
636 {
637   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
638   GstVideoCodecFrame *frame;
639   GstBuffer *buffer = NULL;
640   GstFlowReturn ret;
641
642   GST_LOG_OBJECT (encoder, "Allocate output buffer");
643
644   buffer = gst_video_encoder_allocate_output_buffer (encoder,
645       self->v4l2capture->info.size);
646
647   if (NULL == buffer) {
648     ret = GST_FLOW_FLUSHING;
649     goto beach;
650   }
651
652   /* FIXME Check if buffer isn't the last one here */
653
654   GST_LOG_OBJECT (encoder, "Process output buffer");
655   {
656     GstV4l2BufferPool *cpool =
657         GST_V4L2_BUFFER_POOL (gst_v4l2_object_get_buffer_pool
658         (self->v4l2capture));
659     ret = gst_v4l2_buffer_pool_process (cpool, &buffer, NULL);
660     if (cpool)
661       gst_object_unref (cpool);
662   }
663   if (ret != GST_FLOW_OK)
664     goto beach;
665
666   if (GST_BUFFER_TIMESTAMP (buffer) % GST_SECOND != 0)
667     GST_ERROR_OBJECT (encoder,
668         "Driver bug detected - check driver with v4l2-compliance from http://git.linuxtv.org/v4l-utils.git");
669   GST_LOG_OBJECT (encoder, "Got buffer for frame number %u",
670       (guint32) (GST_BUFFER_PTS (buffer) / GST_SECOND));
671   frame =
672       gst_video_encoder_get_frame (encoder,
673       GST_BUFFER_TIMESTAMP (buffer) / GST_SECOND);
674
675   if (frame) {
676     GstVideoCodecFrame *oldest_frame;
677     gboolean warned = FALSE;
678
679     /* Garbage collect old frames in case of codec bugs */
680     while ((oldest_frame = gst_video_encoder_get_oldest_frame (encoder)) &&
681         check_system_frame_number_too_old (frame->system_frame_number,
682             oldest_frame->system_frame_number)) {
683       gst_video_encoder_finish_frame (encoder, oldest_frame);
684       oldest_frame = NULL;
685
686       if (!warned) {
687         g_warning ("%s: Too old frames, bug in encoder -- please file a bug",
688             GST_ELEMENT_NAME (encoder));
689         warned = TRUE;
690       }
691     }
692     if (oldest_frame)
693       gst_video_codec_frame_unref (oldest_frame);
694
695     /* At this point, the delta unit buffer flag is already correctly set by
696      * gst_v4l2_buffer_pool_process. Since gst_video_encoder_finish_frame
697      * will overwrite it from GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame),
698      * set that here.
699      */
700     if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
701       GST_VIDEO_CODEC_FRAME_UNSET_SYNC_POINT (frame);
702     else
703       GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (frame);
704     frame->output_buffer = buffer;
705     buffer = NULL;
706     ret = gst_video_encoder_finish_frame (encoder, frame);
707
708     if (ret != GST_FLOW_OK)
709       goto beach;
710   } else {
711     GST_WARNING_OBJECT (encoder, "Encoder is producing too many buffers");
712     gst_buffer_unref (buffer);
713   }
714
715   return;
716
717 beach:
718   GST_DEBUG_OBJECT (encoder, "Leaving output thread");
719
720   gst_buffer_replace (&buffer, NULL);
721   self->output_flow = ret;
722   g_atomic_int_set (&self->processing, FALSE);
723   gst_v4l2_object_unlock (self->v4l2output);
724   gst_pad_pause_task (encoder->srcpad);
725 }
726
727 static void
728 gst_v4l2_video_enc_loop_stopped (GstV4l2VideoEnc * self)
729 {
730   if (g_atomic_int_get (&self->processing)) {
731     GST_DEBUG_OBJECT (self, "Early stop of encoding thread");
732     self->output_flow = GST_FLOW_FLUSHING;
733     g_atomic_int_set (&self->processing, FALSE);
734   }
735
736   GST_DEBUG_OBJECT (self, "Encoding task destroyed: %s",
737       gst_flow_get_name (self->output_flow));
738
739 }
740
741 static GstFlowReturn
742 gst_v4l2_video_enc_handle_frame (GstVideoEncoder * encoder,
743     GstVideoCodecFrame * frame)
744 {
745   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
746   GstFlowReturn ret = GST_FLOW_OK;
747   GstTaskState task_state;
748   gboolean active;
749
750   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
751
752   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
753     goto flushing;
754
755   task_state = gst_pad_get_task_state (GST_VIDEO_ENCODER_SRC_PAD (self));
756   if (task_state == GST_TASK_STOPPED || task_state == GST_TASK_PAUSED) {
757     GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (self->v4l2output);
758
759     /* It is possible that the processing thread stopped due to an error or
760      * when the last buffer has been met during the draining process. */
761     if (self->output_flow != GST_FLOW_OK &&
762         self->output_flow != GST_FLOW_FLUSHING &&
763         self->output_flow != GST_V4L2_FLOW_LAST_BUFFER) {
764       GST_DEBUG_OBJECT (self, "Processing loop stopped with error: %s, leaving",
765           gst_flow_get_name (self->output_flow));
766       ret = self->output_flow;
767       if (pool)
768         gst_object_unref (pool);
769       goto drop;
770     }
771
772     /* Ensure input internal pool is active */
773     if (!gst_buffer_pool_is_active (pool)) {
774       GstStructure *config = gst_buffer_pool_get_config (pool);
775       guint min = MAX (self->v4l2output->min_buffers,
776           GST_V4L2_MIN_BUFFERS (self->v4l2output));
777
778       gst_buffer_pool_config_set_params (config, self->input_state->caps,
779           self->v4l2output->info.size, min, min);
780
781       /* There is no reason to refuse this config */
782       if (!gst_buffer_pool_set_config (pool, config)) {
783         if (pool)
784           gst_object_unref (pool);
785         goto activate_failed;
786       }
787
788       if (!gst_buffer_pool_set_active (pool, TRUE)) {
789         if (pool)
790           gst_object_unref (pool);
791         goto activate_failed;
792       }
793       if (pool)
794         gst_object_unref (pool);
795     }
796
797     {
798       GstBufferPool *cpool =
799           gst_v4l2_object_get_buffer_pool (self->v4l2capture);
800       active = gst_buffer_pool_set_active (cpool, TRUE);
801       if (cpool)
802         gst_object_unref (cpool);
803     }
804     if (!active) {
805       GST_WARNING_OBJECT (self, "Could not activate capture buffer pool.");
806       goto activate_failed;
807     }
808
809     GST_DEBUG_OBJECT (self, "Starting encoding thread");
810
811     /* Start the processing task, when it quits, the task will disable input
812      * processing to unlock input if draining, or prevent potential block */
813     if (!gst_pad_start_task (encoder->srcpad,
814             (GstTaskFunction) gst_v4l2_video_enc_loop, self,
815             (GDestroyNotify) gst_v4l2_video_enc_loop_stopped))
816       goto start_task_failed;
817   }
818
819   if (frame->input_buffer) {
820     /* Process force keyframe event if it was passed */
821     if (GST_VIDEO_CODEC_FRAME_IS_FORCE_KEYFRAME (frame)) {
822       struct v4l2_control ctrl = { V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME, 1 };
823       if (self->v4l2output->ioctl (self->v4l2output->video_fd, VIDIOC_S_CTRL,
824               &ctrl) < 0)
825         GST_ELEMENT_WARNING (self, RESOURCE, FAILED,
826             (_("Failed to force keyframe.")),
827             ("VIDIOC_S_CTRL (V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME) failed: %s (%d)",
828                 g_strerror (errno), errno));
829     }
830
831     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
832     GST_LOG_OBJECT (encoder, "Passing buffer with frame number %u",
833         frame->system_frame_number);
834
835     {
836       GstBufferPool *opool = gst_v4l2_object_get_buffer_pool (self->v4l2output);
837       ret = gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (opool),
838           &frame->input_buffer, &frame->system_frame_number);
839       if (opool)
840         gst_object_unref (opool);
841     }
842
843     GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
844
845     if (ret == GST_FLOW_FLUSHING) {
846       if (gst_pad_get_task_state (encoder->srcpad) != GST_TASK_STARTED)
847         ret = self->output_flow;
848       goto drop;
849     } else if (ret != GST_FLOW_OK) {
850       goto process_failed;
851     }
852   }
853
854   gst_video_codec_frame_unref (frame);
855   return ret;
856
857   /* ERRORS */
858 activate_failed:
859   {
860     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
861         (_("Failed to allocate required memory.")),
862         ("Buffer pool activation failed"));
863     return GST_FLOW_ERROR;
864
865   }
866 flushing:
867   {
868     ret = GST_FLOW_FLUSHING;
869     goto drop;
870   }
871 start_task_failed:
872   {
873     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
874         (_("Failed to start encoding thread.")), (NULL));
875     g_atomic_int_set (&self->processing, FALSE);
876     ret = GST_FLOW_ERROR;
877     goto drop;
878   }
879 process_failed:
880   {
881     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
882         (_("Failed to process frame.")),
883         ("Maybe be due to not enough memory or failing driver"));
884     ret = GST_FLOW_ERROR;
885     goto drop;
886   }
887 drop:
888   {
889     gst_video_encoder_finish_frame (encoder, frame);
890     return ret;
891   }
892 }
893
894 static gboolean
895 gst_v4l2_video_enc_decide_allocation (GstVideoEncoder *
896     encoder, GstQuery * query)
897 {
898   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
899   GstVideoCodecState *state = gst_video_encoder_get_output_state (encoder);
900   GstCaps *caps;
901   GstV4l2Error error = GST_V4L2_ERROR_INIT;
902   GstClockTime latency;
903   gboolean ret = FALSE;
904
905   /* We need to set the format here, since this is called right after
906    * GstVideoEncoder have set the width, height and framerate into the state
907    * caps. These are needed by the driver to calculate the buffer size and to
908    * implement bitrate adaptation. */
909   caps = gst_caps_copy (state->caps);
910   gst_structure_remove_field (gst_caps_get_structure (caps, 0), "colorimetry");
911   if (!gst_v4l2_object_set_format (self->v4l2capture, caps, &error)) {
912     gst_v4l2_error (self, &error);
913     gst_caps_unref (caps);
914     ret = FALSE;
915     goto done;
916   }
917   gst_caps_unref (caps);
918
919   /* best effort */
920   gst_v4l2_object_setup_padding (self->v4l2capture);
921
922   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query)) {
923     GstVideoEncoderClass *enc_class = GST_VIDEO_ENCODER_CLASS (parent_class);
924     ret = enc_class->decide_allocation (encoder, query);
925   }
926
927   /* FIXME This may not be entirely correct, as encoder may keep some
928    * observation without delaying the encoding. Linux Media API need some
929    * more work to explicitly expressed the decoder / encoder latency. This
930    * value will then become max latency, and the reported driver latency would
931    * become the min latency. */
932   if (!GST_CLOCK_TIME_IS_VALID (self->v4l2capture->duration))
933     self->v4l2capture->duration = gst_util_uint64_scale_int (GST_SECOND, 1, 25);
934   latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
935   gst_video_encoder_set_latency (encoder, latency, latency);
936   GST_DEBUG_OBJECT (self, "Setting latency: %" GST_TIME_FORMAT,
937       GST_TIME_ARGS (latency));
938
939 done:
940   gst_video_codec_state_unref (state);
941   return ret;
942 }
943
944 static gboolean
945 gst_v4l2_video_enc_propose_allocation (GstVideoEncoder *
946     encoder, GstQuery * query)
947 {
948   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
949   gboolean ret = FALSE;
950
951   GST_DEBUG_OBJECT (self, "called");
952
953   if (query == NULL)
954     ret = TRUE;
955   else
956     ret = gst_v4l2_object_propose_allocation (self->v4l2output, query);
957
958   if (ret)
959     ret = GST_VIDEO_ENCODER_CLASS (parent_class)->propose_allocation (encoder,
960         query);
961
962   return ret;
963 }
964
965 static gboolean
966 gst_v4l2_video_enc_src_query (GstVideoEncoder * encoder, GstQuery * query)
967 {
968   gboolean ret = TRUE;
969   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
970   switch (GST_QUERY_TYPE (query)) {
971     case GST_QUERY_CAPS:{
972       GstCaps *filter, *result = NULL;
973       GstPad *pad = GST_VIDEO_ENCODER_SRC_PAD (encoder);
974
975       gst_query_parse_caps (query, &filter);
976
977       /* FIXME Try and not probe the entire encoder, but only the implement
978        * subclass format */
979       if (self->probed_srccaps) {
980         GstCaps *tmpl = gst_pad_get_pad_template_caps (pad);
981         result = gst_caps_intersect (tmpl, self->probed_srccaps);
982         gst_caps_unref (tmpl);
983       } else
984         result = gst_pad_get_pad_template_caps (pad);
985
986       if (filter) {
987         GstCaps *tmp = result;
988         result =
989             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
990         gst_caps_unref (tmp);
991       }
992
993       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
994
995       gst_query_set_caps_result (query, result);
996       gst_caps_unref (result);
997       break;
998     }
999
1000     default:
1001       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->src_query (encoder, query);
1002       break;
1003   }
1004
1005   return ret;
1006 }
1007
1008 static gboolean
1009 gst_v4l2_video_enc_sink_query (GstVideoEncoder * encoder, GstQuery * query)
1010 {
1011   gboolean ret = TRUE;
1012   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
1013
1014   switch (GST_QUERY_TYPE (query)) {
1015     case GST_QUERY_CAPS:{
1016       GstCaps *filter, *result = NULL;
1017       GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (encoder);
1018
1019       gst_query_parse_caps (query, &filter);
1020
1021       if (self->probed_sinkcaps)
1022         result = gst_caps_ref (self->probed_sinkcaps);
1023       else
1024         result = gst_pad_get_pad_template_caps (pad);
1025
1026       if (filter) {
1027         GstCaps *tmp = result;
1028         result =
1029             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
1030         gst_caps_unref (tmp);
1031       }
1032
1033       GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
1034
1035       gst_query_set_caps_result (query, result);
1036       gst_caps_unref (result);
1037       break;
1038     }
1039
1040     default:
1041       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_query (encoder, query);
1042       break;
1043   }
1044
1045   return ret;
1046 }
1047
1048 static gboolean
1049 gst_v4l2_video_enc_sink_event (GstVideoEncoder * encoder, GstEvent * event)
1050 {
1051   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
1052   gboolean ret;
1053   GstEventType type = GST_EVENT_TYPE (event);
1054
1055   switch (type) {
1056     case GST_EVENT_FLUSH_START:
1057       GST_DEBUG_OBJECT (self, "flush start");
1058       gst_v4l2_object_unlock (self->v4l2output);
1059       gst_v4l2_object_unlock (self->v4l2capture);
1060       break;
1061     default:
1062       break;
1063   }
1064
1065   ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_event (encoder, event);
1066
1067   switch (type) {
1068     case GST_EVENT_FLUSH_START:
1069       gst_pad_stop_task (encoder->srcpad);
1070       GST_DEBUG_OBJECT (self, "flush start done");
1071     default:
1072       break;
1073   }
1074
1075   return ret;
1076 }
1077
1078 static GstStateChangeReturn
1079 gst_v4l2_video_enc_change_state (GstElement * element,
1080     GstStateChange transition)
1081 {
1082   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (element);
1083
1084   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
1085     g_atomic_int_set (&self->active, FALSE);
1086     gst_v4l2_object_unlock (self->v4l2output);
1087     gst_v4l2_object_unlock (self->v4l2capture);
1088   }
1089
1090   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1091 }
1092
1093
1094 static void
1095 gst_v4l2_video_enc_dispose (GObject * object)
1096 {
1097   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1098
1099   gst_caps_replace (&self->probed_sinkcaps, NULL);
1100   gst_caps_replace (&self->probed_srccaps, NULL);
1101
1102   G_OBJECT_CLASS (parent_class)->dispose (object);
1103 }
1104
1105 static void
1106 gst_v4l2_video_enc_finalize (GObject * object)
1107 {
1108   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1109
1110   gst_v4l2_object_destroy (self->v4l2capture);
1111   gst_v4l2_object_destroy (self->v4l2output);
1112
1113   G_OBJECT_CLASS (parent_class)->finalize (object);
1114 }
1115
1116
1117 static void
1118 gst_v4l2_video_enc_init (GstV4l2VideoEnc * self)
1119 {
1120   /* V4L2 object are created in subinstance_init */
1121 }
1122
1123 static void
1124 gst_v4l2_video_enc_subinstance_init (GTypeInstance * instance, gpointer g_class)
1125 {
1126   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1127   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (instance);
1128
1129   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
1130       GST_OBJECT (GST_VIDEO_ENCODER_SINK_PAD (self)),
1131       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
1132       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
1133   self->v4l2output->no_initial_format = TRUE;
1134   self->v4l2output->keep_aspect = FALSE;
1135
1136   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
1137       GST_OBJECT (GST_VIDEO_ENCODER_SRC_PAD (self)),
1138       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
1139       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
1140 }
1141
1142 static void
1143 gst_v4l2_video_enc_class_init (GstV4l2VideoEncClass * klass)
1144 {
1145   GstElementClass *element_class;
1146   GObjectClass *gobject_class;
1147   GstVideoEncoderClass *video_encoder_class;
1148
1149   parent_class = g_type_class_peek_parent (klass);
1150
1151   element_class = (GstElementClass *) klass;
1152   gobject_class = (GObjectClass *) klass;
1153   video_encoder_class = (GstVideoEncoderClass *) klass;
1154
1155   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_enc_debug, "v4l2videoenc", 0,
1156       "V4L2 Video Encoder");
1157
1158   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_dispose);
1159   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finalize);
1160   gobject_class->set_property =
1161       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_property);
1162   gobject_class->get_property =
1163       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_get_property);
1164
1165   video_encoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_open);
1166   video_encoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_close);
1167   video_encoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_start);
1168   video_encoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_stop);
1169   video_encoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finish);
1170   video_encoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_flush);
1171   video_encoder_class->set_format =
1172       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_format);
1173   video_encoder_class->negotiate =
1174       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_negotiate);
1175   video_encoder_class->decide_allocation =
1176       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_decide_allocation);
1177   video_encoder_class->propose_allocation =
1178       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_propose_allocation);
1179   video_encoder_class->sink_query =
1180       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_query);
1181   video_encoder_class->src_query =
1182       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_src_query);
1183   video_encoder_class->sink_event =
1184       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_event);
1185   video_encoder_class->handle_frame =
1186       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_handle_frame);
1187
1188   element_class->change_state =
1189       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_change_state);
1190
1191   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
1192 }
1193
1194 static void
1195 gst_v4l2_video_enc_subclass_init (gpointer g_class, gpointer data)
1196 {
1197   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1198   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1199   GstV4l2VideoEncCData *cdata = data;
1200
1201   klass->default_device = cdata->device;
1202   klass->codec = cdata->codec;
1203
1204   gst_element_class_add_pad_template (element_class,
1205       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
1206           cdata->sink_caps));
1207   gst_element_class_add_pad_template (element_class,
1208       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
1209           cdata->src_caps));
1210
1211   gst_caps_unref (cdata->sink_caps);
1212   gst_caps_unref (cdata->src_caps);
1213   g_free (cdata);
1214 }
1215
1216 /* Probing functions */
1217 gboolean
1218 gst_v4l2_is_video_enc (GstCaps * sink_caps, GstCaps * src_caps,
1219     GstCaps * codec_caps)
1220 {
1221   gboolean ret = FALSE;
1222   gboolean (*check_caps) (const GstCaps *, const GstCaps *);
1223
1224   if (codec_caps) {
1225     check_caps = gst_caps_can_intersect;
1226   } else {
1227     codec_caps = gst_v4l2_object_get_codec_caps ();
1228     check_caps = gst_caps_is_subset;
1229   }
1230
1231   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_raw_caps ())
1232       && check_caps (src_caps, codec_caps))
1233     ret = TRUE;
1234
1235   return ret;
1236 }
1237
1238 void
1239 gst_v4l2_video_enc_register (GstPlugin * plugin, GType type,
1240     const char *codec_name, const gchar * basename, const gchar * device_path,
1241     const GstV4l2Codec * codec, gint video_fd, GstCaps * sink_caps,
1242     GstCaps * codec_caps, GstCaps * src_caps)
1243 {
1244   GstCaps *filtered_caps;
1245   GTypeQuery type_query;
1246   GTypeInfo type_info = { 0, };
1247   GType subtype;
1248   gchar *type_name;
1249   GstV4l2VideoEncCData *cdata;
1250   GValue value = G_VALUE_INIT;
1251
1252   filtered_caps = gst_caps_intersect (src_caps, codec_caps);
1253
1254   if (codec != NULL && video_fd != -1) {
1255     if (gst_v4l2_codec_probe_levels (codec, video_fd, &value)) {
1256       gst_caps_set_value (filtered_caps, "level", &value);
1257       g_value_unset (&value);
1258     }
1259
1260     if (gst_v4l2_codec_probe_profiles (codec, video_fd, &value)) {
1261       gst_caps_set_value (filtered_caps, "profile", &value);
1262       g_value_unset (&value);
1263     }
1264   }
1265
1266   cdata = g_new0 (GstV4l2VideoEncCData, 1);
1267   cdata->device = g_strdup (device_path);
1268   cdata->sink_caps = gst_caps_ref (sink_caps);
1269   cdata->src_caps = gst_caps_ref (filtered_caps);
1270   cdata->codec = codec;
1271
1272   g_type_query (type, &type_query);
1273   memset (&type_info, 0, sizeof (type_info));
1274   type_info.class_size = type_query.class_size;
1275   type_info.instance_size = type_query.instance_size;
1276   type_info.class_init = gst_v4l2_video_enc_subclass_init;
1277   type_info.class_data = cdata;
1278   type_info.instance_init = gst_v4l2_video_enc_subinstance_init;
1279
1280   /* The first encoder to be registered should use a constant name, like
1281    * v4l2h264enc, for any additional encoders, we create unique names. Encoder
1282    * names may change between boots, so this should help gain stable names for
1283    * the most common use cases. */
1284   type_name = g_strdup_printf ("v4l2%senc", codec_name);
1285
1286   if (g_type_from_name (type_name) != 0) {
1287     g_free (type_name);
1288     type_name = g_strdup_printf ("v4l2%s%senc", basename, codec_name);
1289   }
1290
1291   subtype = g_type_register_static (type, type_name, &type_info, 0);
1292
1293   if (!gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1, subtype))
1294     GST_WARNING ("Failed to register plugin '%s'", type_name);
1295
1296   g_free (type_name);
1297 }