v4l2videoenc: fix capture-io-mode property get
[platform/upstream/gst-plugins-good.git] / 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 <gst/gst-i18n-plugin.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 } GstV4l2VideoEncCData;
49
50 enum
51 {
52   PROP_0,
53   V4L2_STD_OBJECT_PROPS,
54 };
55
56 #define gst_v4l2_video_enc_parent_class parent_class
57 G_DEFINE_ABSTRACT_TYPE (GstV4l2VideoEnc, gst_v4l2_video_enc,
58     GST_TYPE_VIDEO_ENCODER);
59
60 static void
61 gst_v4l2_video_enc_set_property (GObject * object,
62     guint prop_id, const GValue * value, GParamSpec * pspec)
63 {
64   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
65
66   switch (prop_id) {
67     case PROP_OUTPUT_IO_MODE:
68       gst_v4l2_object_set_property_helper (self->v4l2output,
69           prop_id, value, pspec);
70       break;
71     case PROP_CAPTURE_IO_MODE:
72       gst_v4l2_object_set_property_helper (self->v4l2capture,
73           prop_id, value, pspec);
74       break;
75
76       /* By default, only set on output */
77     default:
78       if (!gst_v4l2_object_set_property_helper (self->v4l2output,
79               prop_id, value, pspec)) {
80         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
81       }
82       break;
83   }
84 }
85
86 static void
87 gst_v4l2_video_enc_get_property (GObject * object,
88     guint prop_id, GValue * value, GParamSpec * pspec)
89 {
90   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
91
92   switch (prop_id) {
93     case PROP_OUTPUT_IO_MODE:
94       gst_v4l2_object_get_property_helper (self->v4l2output,
95           prop_id, value, pspec);
96       break;
97     case PROP_CAPTURE_IO_MODE:
98       gst_v4l2_object_get_property_helper (self->v4l2capture,
99           prop_id, value, pspec);
100       break;
101
102       /* By default read from output */
103     default:
104       if (!gst_v4l2_object_get_property_helper (self->v4l2output,
105               prop_id, value, pspec)) {
106         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
107       }
108       break;
109   }
110 }
111
112 static gboolean
113 gst_v4l2_video_enc_open (GstVideoEncoder * encoder)
114 {
115   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
116   GstCaps *codec_caps;
117
118   GST_DEBUG_OBJECT (self, "Opening");
119
120   if (!gst_v4l2_object_open (self->v4l2output))
121     goto failure;
122
123   if (!gst_v4l2_object_open_shared (self->v4l2capture, self->v4l2output))
124     goto failure;
125
126   self->probed_sinkcaps = gst_v4l2_object_probe_caps (self->v4l2output,
127       gst_v4l2_object_get_raw_caps ());
128
129   if (gst_caps_is_empty (self->probed_sinkcaps))
130     goto no_raw_format;
131
132   codec_caps = gst_pad_get_pad_template_caps (encoder->srcpad);
133   self->probed_srccaps = gst_v4l2_object_probe_caps (self->v4l2capture,
134       codec_caps);
135   gst_caps_unref (codec_caps);
136
137   if (gst_caps_is_empty (self->probed_srccaps))
138     goto no_encoded_format;
139
140   return TRUE;
141
142 no_encoded_format:
143   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
144       (_("Encoder on device %s has no supported output format"),
145           self->v4l2output->videodev), (NULL));
146   goto failure;
147
148
149 no_raw_format:
150   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
151       (_("Encoder on device %s has no supported input format"),
152           self->v4l2output->videodev), (NULL));
153   goto failure;
154
155 failure:
156   if (GST_V4L2_IS_OPEN (self->v4l2output))
157     gst_v4l2_object_close (self->v4l2output);
158
159   if (GST_V4L2_IS_OPEN (self->v4l2capture))
160     gst_v4l2_object_close (self->v4l2capture);
161
162   gst_caps_replace (&self->probed_srccaps, NULL);
163   gst_caps_replace (&self->probed_sinkcaps, NULL);
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_OBJECT_LOCK (task);
282     while (GST_TASK_STATE (task) == GST_TASK_STARTED)
283       GST_TASK_WAIT (task);
284     GST_OBJECT_UNLOCK (task);
285     ret = GST_FLOW_FLUSHING;
286   }
287
288   /* and ensure the processing thread has stopped in case another error
289    * occured. */
290   gst_v4l2_object_unlock (self->v4l2capture);
291   gst_pad_stop_task (encoder->srcpad);
292   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
293
294   if (ret == GST_FLOW_FLUSHING)
295     ret = self->output_flow;
296
297   GST_DEBUG_OBJECT (encoder, "Done draining buffers");
298
299 done:
300   return ret;
301 }
302
303 static gboolean
304 gst_v4l2_video_enc_set_format (GstVideoEncoder * encoder,
305     GstVideoCodecState * state)
306 {
307   gboolean ret = TRUE;
308   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
309   GstV4l2Error error = GST_V4L2_ERROR_INIT;
310   GstCaps *outcaps;
311   GstVideoCodecState *output;
312
313   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
314
315   if (self->input_state) {
316     if (gst_v4l2_object_caps_equal (self->v4l2output, state->caps)) {
317       GST_DEBUG_OBJECT (self, "Compatible caps");
318       return TRUE;
319     }
320
321     if (gst_v4l2_video_enc_finish (encoder) != GST_FLOW_OK)
322       return FALSE;
323
324     gst_v4l2_object_stop (self->v4l2output);
325     gst_v4l2_object_stop (self->v4l2capture);
326
327     gst_video_codec_state_unref (self->input_state);
328     self->input_state = NULL;
329   }
330
331   outcaps = gst_pad_get_pad_template_caps (encoder->srcpad);
332   outcaps = gst_caps_make_writable (outcaps);
333   output = gst_video_encoder_set_output_state (encoder, outcaps, state);
334   gst_video_codec_state_unref (output);
335
336   if (!gst_video_encoder_negotiate (encoder))
337     return FALSE;
338
339   if (!gst_v4l2_object_set_format (self->v4l2output, state->caps, &error)) {
340     gst_v4l2_error (self, &error);
341     return FALSE;
342   }
343
344   /* activating a capture pool will also call STREAMON. CODA driver will
345    * refuse to configure the output if the capture is stremaing. */
346   if (!gst_buffer_pool_set_active (GST_BUFFER_POOL (self->v4l2capture->pool),
347           TRUE)) {
348     GST_WARNING_OBJECT (self, "Could not activate capture buffer pool.");
349     return FALSE;
350   }
351
352   self->input_state = gst_video_codec_state_ref (state);
353
354   GST_DEBUG_OBJECT (self, "output caps: %" GST_PTR_FORMAT, state->caps);
355
356   return ret;
357 }
358
359 static gboolean
360 gst_v4l2_video_enc_flush (GstVideoEncoder * encoder)
361 {
362   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
363
364   GST_DEBUG_OBJECT (self, "Flushing");
365
366   /* Ensure the processing thread has stopped for the reverse playback
367    * iscount case */
368   if (g_atomic_int_get (&self->processing)) {
369     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
370
371     gst_v4l2_object_unlock_stop (self->v4l2output);
372     gst_v4l2_object_unlock_stop (self->v4l2capture);
373     gst_pad_stop_task (encoder->srcpad);
374
375     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
376
377   }
378
379   self->output_flow = GST_FLOW_OK;
380
381   gst_v4l2_object_unlock_stop (self->v4l2output);
382   gst_v4l2_object_unlock_stop (self->v4l2capture);
383
384   return TRUE;
385 }
386
387 struct ProfileLevelCtx
388 {
389   GstV4l2VideoEnc *self;
390   const gchar *profile;
391   const gchar *level;
392 };
393
394 static gboolean
395 get_string_list (GstStructure * s, const gchar * field, GQueue * queue)
396 {
397   const GValue *value;
398
399   value = gst_structure_get_value (s, field);
400
401   if (!value)
402     return FALSE;
403
404   if (GST_VALUE_HOLDS_LIST (value)) {
405     guint i;
406
407     if (gst_value_list_get_size (value) == 0)
408       return FALSE;
409
410     for (i = 0; i < gst_value_list_get_size (value); i++) {
411       const GValue *item = gst_value_list_get_value (value, i);
412
413       if (G_VALUE_HOLDS_STRING (item))
414         g_queue_push_tail (queue, g_value_dup_string (item));
415     }
416   } else if (G_VALUE_HOLDS_STRING (value)) {
417     g_queue_push_tail (queue, g_value_dup_string (value));
418   }
419
420   return TRUE;
421 }
422
423 static gboolean
424 negotiate_profile_and_level (GstCapsFeatures * features, GstStructure * s,
425     gpointer user_data)
426 {
427   struct ProfileLevelCtx *ctx = user_data;
428   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (ctx->self);
429   GstV4l2Object *v4l2object = GST_V4L2_VIDEO_ENC (ctx->self)->v4l2output;
430   GQueue profiles = G_QUEUE_INIT;
431   GQueue levels = G_QUEUE_INIT;
432   gboolean failed = FALSE;
433
434   if (klass->profile_cid && get_string_list (s, "profile", &profiles)) {
435     GList *l;
436
437     for (l = profiles.head; l; l = l->next) {
438       struct v4l2_control control = { 0, };
439       gint v4l2_profile;
440       const gchar *profile = l->data;
441
442       GST_TRACE_OBJECT (ctx->self, "Trying profile %s", profile);
443
444       control.id = klass->profile_cid;
445       control.value = v4l2_profile = klass->profile_from_string (profile);
446
447       if (control.value < 0)
448         continue;
449
450       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
451         GST_WARNING_OBJECT (ctx->self, "Failed to set %s profile: '%s'",
452             klass->codec_name, g_strerror (errno));
453         break;
454       }
455
456       profile = klass->profile_to_string (control.value);
457
458       if (control.value == v4l2_profile) {
459         ctx->profile = profile;
460         break;
461       }
462
463       if (g_list_find_custom (l, profile, g_str_equal)) {
464         ctx->profile = profile;
465         break;
466       }
467     }
468
469     if (profiles.length && !ctx->profile)
470       failed = TRUE;
471
472     g_queue_foreach (&profiles, (GFunc) g_free, NULL);
473     g_queue_clear (&profiles);
474   }
475
476   if (!failed && klass->level_cid && get_string_list (s, "level", &levels)) {
477     GList *l;
478
479     for (l = levels.head; l; l = l->next) {
480       struct v4l2_control control = { 0, };
481       gint v4l2_level;
482       const gchar *level = l->data;
483
484       GST_TRACE_OBJECT (ctx->self, "Trying level %s", level);
485
486       control.id = klass->level_cid;
487       control.value = v4l2_level = klass->level_from_string (level);
488
489       if (control.value < 0)
490         continue;
491
492       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
493         GST_WARNING_OBJECT (ctx->self, "Failed to set %s level: '%s'",
494             klass->codec_name, g_strerror (errno));
495         break;
496       }
497
498       level = klass->level_to_string (control.value);
499
500       if (control.value == v4l2_level) {
501         ctx->level = level;
502         break;
503       }
504
505       if (g_list_find_custom (l, level, g_str_equal)) {
506         ctx->level = level;
507         break;
508       }
509     }
510
511     if (levels.length && !ctx->level)
512       failed = TRUE;
513
514     g_queue_foreach (&levels, (GFunc) g_free, NULL);
515     g_queue_clear (&levels);
516   }
517
518   /* If it failed, we continue */
519   return failed;
520 }
521
522 static gboolean
523 gst_v4l2_video_enc_negotiate (GstVideoEncoder * encoder)
524 {
525   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (encoder);
526   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
527   GstV4l2Object *v4l2object = self->v4l2output;
528   GstCaps *allowed_caps;
529   struct ProfileLevelCtx ctx = { self, NULL, NULL };
530   GstVideoCodecState *state;
531   GstStructure *s;
532
533   GST_DEBUG_OBJECT (self, "Negotiating %s profile and level.",
534       klass->codec_name);
535
536   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (encoder));
537
538   if (allowed_caps) {
539
540     if (gst_caps_is_empty (allowed_caps))
541       goto not_negotiated;
542
543     allowed_caps = gst_caps_make_writable (allowed_caps);
544
545     /* negotiate_profile_and_level() will return TRUE on failure to keep
546      * iterating, if gst_caps_foreach() returns TRUE it means there was no
547      * compatible profile and level in any of the structure */
548     if (gst_caps_foreach (allowed_caps, negotiate_profile_and_level, &ctx)) {
549       goto no_profile_level;
550     }
551   }
552
553   if (klass->profile_cid && !ctx.profile) {
554     struct v4l2_control control = { 0, };
555
556     control.id = klass->profile_cid;
557
558     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
559       goto g_ctrl_failed;
560
561     ctx.profile = klass->profile_to_string (control.value);
562   }
563
564   if (klass->level_cid && !ctx.level) {
565     struct v4l2_control control = { 0, };
566
567     control.id = klass->level_cid;
568
569     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
570       goto g_ctrl_failed;
571
572     ctx.level = klass->level_to_string (control.value);
573   }
574
575   GST_DEBUG_OBJECT (self, "Selected %s profile %s at level %s",
576       klass->codec_name, ctx.profile, ctx.level);
577
578   state = gst_video_encoder_get_output_state (encoder);
579   s = gst_caps_get_structure (state->caps, 0);
580
581   if (klass->profile_cid)
582     gst_structure_set (s, "profile", G_TYPE_STRING, ctx.profile, NULL);
583
584   if (klass->level_cid)
585     gst_structure_set (s, "level", G_TYPE_STRING, ctx.level, NULL);
586
587   if (!GST_VIDEO_ENCODER_CLASS (parent_class)->negotiate (encoder))
588     return FALSE;
589
590   return TRUE;
591
592 g_ctrl_failed:
593   GST_WARNING_OBJECT (self, "Failed to get %s profile and level: '%s'",
594       klass->codec_name, g_strerror (errno));
595   goto not_negotiated;
596
597 no_profile_level:
598   GST_WARNING_OBJECT (self, "No compatible level and profile in caps: %"
599       GST_PTR_FORMAT, allowed_caps);
600   goto not_negotiated;
601
602 not_negotiated:
603   if (allowed_caps)
604     gst_caps_unref (allowed_caps);
605   return FALSE;
606 }
607
608 static GstVideoCodecFrame *
609 gst_v4l2_video_enc_get_oldest_frame (GstVideoEncoder * encoder)
610 {
611   GstVideoCodecFrame *frame = NULL;
612   GList *frames, *l;
613   gint count = 0;
614
615   frames = gst_video_encoder_get_frames (encoder);
616
617   for (l = frames; l != NULL; l = l->next) {
618     GstVideoCodecFrame *f = l->data;
619
620     if (!frame || frame->pts > f->pts)
621       frame = f;
622
623     count++;
624   }
625
626   if (frame) {
627     GST_LOG_OBJECT (encoder,
628         "Oldest frame is %d %" GST_TIME_FORMAT
629         " and %d frames left",
630         frame->system_frame_number, GST_TIME_ARGS (frame->pts), count - 1);
631     gst_video_codec_frame_ref (frame);
632   }
633
634   g_list_free_full (frames, (GDestroyNotify) gst_video_codec_frame_unref);
635
636   return frame;
637 }
638
639 static void
640 gst_v4l2_video_enc_loop (GstVideoEncoder * encoder)
641 {
642   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
643   GstVideoCodecFrame *frame;
644   GstBuffer *buffer = NULL;
645   GstFlowReturn ret;
646
647   GST_LOG_OBJECT (encoder, "Allocate output buffer");
648
649   buffer = gst_video_encoder_allocate_output_buffer (encoder,
650       self->v4l2capture->info.size);
651
652   if (NULL == buffer) {
653     ret = GST_FLOW_FLUSHING;
654     goto beach;
655   }
656
657
658   /* FIXME Check if buffer isn't the last one here */
659
660   GST_LOG_OBJECT (encoder, "Process output buffer");
661   ret =
662       gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL
663       (self->v4l2capture->pool), &buffer);
664
665   if (ret != GST_FLOW_OK)
666     goto beach;
667
668   frame = gst_v4l2_video_enc_get_oldest_frame (encoder);
669
670   if (frame) {
671     frame->output_buffer = buffer;
672     buffer = NULL;
673     ret = gst_video_encoder_finish_frame (encoder, frame);
674
675     if (ret != GST_FLOW_OK)
676       goto beach;
677   } else {
678     GST_WARNING_OBJECT (encoder, "Encoder is producing too many buffers");
679     gst_buffer_unref (buffer);
680   }
681
682   return;
683
684 beach:
685   GST_DEBUG_OBJECT (encoder, "Leaving output thread");
686
687   gst_buffer_replace (&buffer, NULL);
688   self->output_flow = ret;
689   g_atomic_int_set (&self->processing, FALSE);
690   gst_v4l2_object_unlock (self->v4l2output);
691   gst_pad_pause_task (encoder->srcpad);
692 }
693
694 static void
695 gst_v4l2_video_enc_loop_stopped (GstV4l2VideoEnc * self)
696 {
697   if (g_atomic_int_get (&self->processing)) {
698     GST_DEBUG_OBJECT (self, "Early stop of encoding thread");
699     self->output_flow = GST_FLOW_FLUSHING;
700     g_atomic_int_set (&self->processing, FALSE);
701   }
702
703   GST_DEBUG_OBJECT (self, "Encoding task destroyed: %s",
704       gst_flow_get_name (self->output_flow));
705
706 }
707
708 static GstFlowReturn
709 gst_v4l2_video_enc_handle_frame (GstVideoEncoder * encoder,
710     GstVideoCodecFrame * frame)
711 {
712   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
713   GstFlowReturn ret = GST_FLOW_OK;
714   GstTaskState task_state;
715
716   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
717
718   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
719     goto flushing;
720
721   task_state = gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self));
722   if (task_state == GST_TASK_STOPPED || task_state == GST_TASK_PAUSED) {
723     GstBufferPool *pool = GST_BUFFER_POOL (self->v4l2output->pool);
724
725     /* It possible that the processing thread stopped due to an error */
726     if (self->output_flow != GST_FLOW_OK &&
727         self->output_flow != GST_FLOW_FLUSHING) {
728       GST_DEBUG_OBJECT (self, "Processing loop stopped with error, leaving");
729       ret = self->output_flow;
730       goto drop;
731     }
732
733     /* Ensure input internal pool is active */
734     if (!gst_buffer_pool_is_active (pool)) {
735       GstStructure *config = gst_buffer_pool_get_config (pool);
736       guint min = MAX (self->v4l2output->min_buffers, GST_V4L2_MIN_BUFFERS);
737
738       gst_buffer_pool_config_set_params (config, self->input_state->caps,
739           self->v4l2output->info.size, min, min);
740
741       /* There is no reason to refuse this config */
742       if (!gst_buffer_pool_set_config (pool, config))
743         goto activate_failed;
744
745       if (!gst_buffer_pool_set_active (pool, TRUE))
746         goto activate_failed;
747     }
748
749     GST_DEBUG_OBJECT (self, "Starting encoding thread");
750
751     /* Start the processing task, when it quits, the task will disable input
752      * processing to unlock input if draining, or prevent potential block */
753     if (!gst_pad_start_task (encoder->srcpad,
754             (GstTaskFunction) gst_v4l2_video_enc_loop, self,
755             (GDestroyNotify) gst_v4l2_video_enc_loop_stopped))
756       goto start_task_failed;
757   }
758
759   if (frame->input_buffer) {
760     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
761     ret =
762         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL
763         (self->v4l2output->pool), &frame->input_buffer);
764     GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
765
766     if (ret == GST_FLOW_FLUSHING) {
767       if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) !=
768           GST_TASK_STARTED)
769         ret = self->output_flow;
770       goto drop;
771     } else if (ret != GST_FLOW_OK) {
772       goto process_failed;
773     }
774   }
775
776   gst_video_codec_frame_unref (frame);
777   return ret;
778
779   /* ERRORS */
780 activate_failed:
781   {
782     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
783         (_("Failed to allocate required memory.")),
784         ("Buffer pool activation failed"));
785     return GST_FLOW_ERROR;
786
787   }
788 flushing:
789   {
790     ret = GST_FLOW_FLUSHING;
791     goto drop;
792   }
793 start_task_failed:
794   {
795     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
796         (_("Failed to start encoding thread.")), (NULL));
797     g_atomic_int_set (&self->processing, FALSE);
798     ret = GST_FLOW_ERROR;
799     goto drop;
800   }
801 process_failed:
802   {
803     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
804         (_("Failed to process frame.")),
805         ("Maybe be due to not enough memory or failing driver"));
806     ret = GST_FLOW_ERROR;
807     goto drop;
808   }
809 drop:
810   {
811     gst_video_encoder_finish_frame (encoder, frame);
812     return ret;
813   }
814 }
815
816 static gboolean
817 gst_v4l2_video_enc_decide_allocation (GstVideoEncoder *
818     encoder, GstQuery * query)
819 {
820   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
821   GstVideoCodecState *state = gst_video_encoder_get_output_state (encoder);
822   GstV4l2Error error = GST_V4L2_ERROR_INIT;
823   GstClockTime latency;
824   gboolean ret = FALSE;
825
826   /* We need to set the format here, since this is called right after
827    * GstVideoEncoder have set the width, height and framerate into the state
828    * caps. These are needed by the driver to calculate the buffer size and to
829    * implement bitrate adaptation. */
830   if (!gst_v4l2_object_set_format (self->v4l2capture, state->caps, &error)) {
831     gst_v4l2_error (self, &error);
832     ret = FALSE;
833     goto done;
834   }
835
836   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query)) {
837     GstVideoEncoderClass *enc_class = GST_VIDEO_ENCODER_CLASS (parent_class);
838     ret = enc_class->decide_allocation (encoder, query);
839   }
840
841   /* FIXME This may not be entirely correct, as encoder may keep some
842    * observation withouth delaying the encoding. Linux Media API need some
843    * more work to explicitly expressed the decoder / encoder latency. This
844    * value will then become max latency, and the reported driver latency would
845    * become the min latency. */
846   latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
847   gst_video_encoder_set_latency (encoder, latency, latency);
848
849 done:
850   gst_video_codec_state_unref (state);
851   return ret;
852 }
853
854 static gboolean
855 gst_v4l2_video_enc_propose_allocation (GstVideoEncoder *
856     encoder, GstQuery * query)
857 {
858   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
859   gboolean ret = FALSE;
860
861   GST_DEBUG_OBJECT (self, "called");
862
863   if (query == NULL)
864     ret = TRUE;
865   else
866     ret = gst_v4l2_object_propose_allocation (self->v4l2output, query);
867
868   if (ret)
869     ret = GST_VIDEO_ENCODER_CLASS (parent_class)->propose_allocation (encoder,
870         query);
871
872   return ret;
873 }
874
875 static gboolean
876 gst_v4l2_video_enc_src_query (GstVideoEncoder * encoder, GstQuery * query)
877 {
878   gboolean ret = TRUE;
879   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
880   switch (GST_QUERY_TYPE (query)) {
881     case GST_QUERY_CAPS:{
882       GstCaps *filter, *result = NULL;
883       GstPad *pad = GST_VIDEO_ENCODER_SRC_PAD (encoder);
884
885       gst_query_parse_caps (query, &filter);
886
887       /* FIXME Try and not probe the entire encoder, but only the implement
888        * subclass format */
889       if (self->probed_srccaps) {
890         GstCaps *tmpl = gst_pad_get_pad_template_caps (pad);
891         result = gst_caps_intersect (tmpl, self->probed_srccaps);
892         gst_caps_unref (tmpl);
893       } else
894         result = gst_pad_get_pad_template_caps (pad);
895
896       if (filter) {
897         GstCaps *tmp = result;
898         result =
899             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
900         gst_caps_unref (tmp);
901       }
902
903       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
904
905       gst_query_set_caps_result (query, result);
906       gst_caps_unref (result);
907       break;
908     }
909
910     default:
911       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->src_query (encoder, query);
912       break;
913   }
914
915   return ret;
916 }
917
918 static gboolean
919 gst_v4l2_video_enc_sink_query (GstVideoEncoder * encoder, GstQuery * query)
920 {
921   gboolean ret = TRUE;
922   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
923
924   switch (GST_QUERY_TYPE (query)) {
925     case GST_QUERY_CAPS:{
926       GstCaps *filter, *result = NULL;
927       GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (encoder);
928
929       gst_query_parse_caps (query, &filter);
930
931       if (self->probed_sinkcaps)
932         result = gst_caps_ref (self->probed_sinkcaps);
933       else
934         result = gst_pad_get_pad_template_caps (pad);
935
936       if (filter) {
937         GstCaps *tmp = result;
938         result =
939             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
940         gst_caps_unref (tmp);
941       }
942
943       GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
944
945       gst_query_set_caps_result (query, result);
946       gst_caps_unref (result);
947       break;
948     }
949
950     default:
951       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_query (encoder, query);
952       break;
953   }
954
955   return ret;
956 }
957
958 static gboolean
959 gst_v4l2_video_enc_sink_event (GstVideoEncoder * encoder, GstEvent * event)
960 {
961   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
962   gboolean ret;
963
964   switch (GST_EVENT_TYPE (event)) {
965     case GST_EVENT_FLUSH_START:
966       GST_DEBUG_OBJECT (self, "flush start");
967       gst_v4l2_object_unlock (self->v4l2output);
968       gst_v4l2_object_unlock (self->v4l2capture);
969       break;
970     default:
971       break;
972   }
973
974   ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_event (encoder, event);
975
976   switch (GST_EVENT_TYPE (event)) {
977     case GST_EVENT_FLUSH_START:
978       gst_pad_stop_task (encoder->srcpad);
979       GST_DEBUG_OBJECT (self, "flush start done");
980     default:
981       break;
982   }
983
984   return ret;
985 }
986
987 static GstStateChangeReturn
988 gst_v4l2_video_enc_change_state (GstElement * element,
989     GstStateChange transition)
990 {
991   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (element);
992
993   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
994     g_atomic_int_set (&self->active, FALSE);
995     gst_v4l2_object_unlock (self->v4l2output);
996     gst_v4l2_object_unlock (self->v4l2capture);
997   }
998
999   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1000 }
1001
1002
1003 static void
1004 gst_v4l2_video_enc_dispose (GObject * object)
1005 {
1006   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1007
1008   gst_caps_replace (&self->probed_sinkcaps, NULL);
1009   gst_caps_replace (&self->probed_srccaps, NULL);
1010
1011   G_OBJECT_CLASS (parent_class)->dispose (object);
1012 }
1013
1014 static void
1015 gst_v4l2_video_enc_finalize (GObject * object)
1016 {
1017   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1018
1019   gst_v4l2_object_destroy (self->v4l2capture);
1020   gst_v4l2_object_destroy (self->v4l2output);
1021
1022   G_OBJECT_CLASS (parent_class)->finalize (object);
1023 }
1024
1025
1026 static void
1027 gst_v4l2_video_enc_init (GstV4l2VideoEnc * self)
1028 {
1029   /* V4L2 object are created in subinstance_init */
1030 }
1031
1032 static void
1033 gst_v4l2_video_enc_subinstance_init (GTypeInstance * instance, gpointer g_class)
1034 {
1035   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1036   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (instance);
1037
1038   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
1039       GST_OBJECT (GST_VIDEO_ENCODER_SINK_PAD (self)),
1040       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
1041       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
1042   self->v4l2output->no_initial_format = TRUE;
1043   self->v4l2output->keep_aspect = FALSE;
1044
1045   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
1046       GST_OBJECT (GST_VIDEO_ENCODER_SRC_PAD (self)),
1047       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
1048       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
1049   self->v4l2capture->no_initial_format = TRUE;
1050   self->v4l2output->keep_aspect = FALSE;
1051 }
1052
1053 static void
1054 gst_v4l2_video_enc_class_init (GstV4l2VideoEncClass * klass)
1055 {
1056   GstElementClass *element_class;
1057   GObjectClass *gobject_class;
1058   GstVideoEncoderClass *video_encoder_class;
1059
1060   parent_class = g_type_class_peek_parent (klass);
1061
1062   element_class = (GstElementClass *) klass;
1063   gobject_class = (GObjectClass *) klass;
1064   video_encoder_class = (GstVideoEncoderClass *) klass;
1065
1066   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_enc_debug, "v4l2videoenc", 0,
1067       "V4L2 Video Encoder");
1068
1069   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_dispose);
1070   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finalize);
1071   gobject_class->set_property =
1072       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_property);
1073   gobject_class->get_property =
1074       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_get_property);
1075
1076   video_encoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_open);
1077   video_encoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_close);
1078   video_encoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_start);
1079   video_encoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_stop);
1080   video_encoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finish);
1081   video_encoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_flush);
1082   video_encoder_class->set_format =
1083       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_format);
1084   video_encoder_class->negotiate =
1085       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_negotiate);
1086   video_encoder_class->decide_allocation =
1087       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_decide_allocation);
1088   video_encoder_class->propose_allocation =
1089       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_propose_allocation);
1090   video_encoder_class->sink_query =
1091       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_query);
1092   video_encoder_class->src_query =
1093       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_src_query);
1094   video_encoder_class->sink_event =
1095       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_event);
1096   video_encoder_class->handle_frame =
1097       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_handle_frame);
1098
1099   element_class->change_state =
1100       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_change_state);
1101
1102   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
1103 }
1104
1105 static void
1106 gst_v4l2_video_enc_subclass_init (gpointer g_class, gpointer data)
1107 {
1108   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1109   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1110   GstV4l2VideoEncCData *cdata = data;
1111
1112   klass->default_device = cdata->device;
1113
1114   /* Note: gst_pad_template_new() take the floating ref from the caps */
1115   gst_element_class_add_pad_template (element_class,
1116       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
1117           cdata->sink_caps));
1118   gst_element_class_add_pad_template (element_class,
1119       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
1120           cdata->src_caps));
1121
1122   gst_caps_unref (cdata->sink_caps);
1123   gst_caps_unref (cdata->src_caps);
1124   g_free (cdata);
1125 }
1126
1127 /* Probing functions */
1128 gboolean
1129 gst_v4l2_is_video_enc (GstCaps * sink_caps, GstCaps * src_caps,
1130     GstCaps * codec_caps)
1131 {
1132   gboolean ret = FALSE;
1133   gboolean (*check_caps) (const GstCaps *, const GstCaps *);
1134
1135   if (codec_caps) {
1136     check_caps = gst_caps_can_intersect;
1137   } else {
1138     codec_caps = gst_v4l2_object_get_codec_caps ();
1139     check_caps = gst_caps_is_subset;
1140   }
1141
1142   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_raw_caps ())
1143       && check_caps (src_caps, codec_caps))
1144     ret = TRUE;
1145
1146   return ret;
1147 }
1148
1149 void
1150 gst_v4l2_video_enc_register (GstPlugin * plugin, GType type,
1151     const char *codec, const gchar * basename, const gchar * device_path,
1152     GstCaps * sink_caps, GstCaps * codec_caps, GstCaps * src_caps)
1153 {
1154   GstCaps *filtered_caps;
1155   GTypeQuery type_query;
1156   GTypeInfo type_info = { 0, };
1157   GType subtype;
1158   gchar *type_name;
1159   GstV4l2VideoEncCData *cdata;
1160
1161   filtered_caps = gst_caps_intersect (src_caps, codec_caps);
1162
1163   cdata = g_new0 (GstV4l2VideoEncCData, 1);
1164   cdata->device = g_strdup (device_path);
1165   cdata->sink_caps = gst_caps_ref (sink_caps);
1166   cdata->src_caps = gst_caps_ref (filtered_caps);
1167
1168   g_type_query (type, &type_query);
1169   memset (&type_info, 0, sizeof (type_info));
1170   type_info.class_size = type_query.class_size;
1171   type_info.instance_size = type_query.instance_size;
1172   type_info.class_init = gst_v4l2_video_enc_subclass_init;
1173   type_info.class_data = cdata;
1174   type_info.instance_init = gst_v4l2_video_enc_subinstance_init;
1175
1176   /* The first encoder to be registered should use a constant name, like
1177    * v4l2h264enc, for any additional encoders, we create unique names. Encoder
1178    * names may change between boots, so this should help gain stable names for
1179    * the most common use cases. */
1180   type_name = g_strdup_printf ("v4l2%senc", codec);
1181
1182   if (g_type_from_name (type_name) != 0) {
1183     g_free (type_name);
1184     type_name = g_strdup_printf ("v4l2%s%senc", basename, codec);
1185   }
1186
1187   subtype = g_type_register_static (type, type_name, &type_info, 0);
1188
1189   if (!gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1, subtype))
1190     GST_WARNING ("Failed to register plugin '%s'", type_name);
1191
1192   g_free (type_name);
1193 }