v4l2videoenc: Fix driver capability dectection
[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->v4l2output,
99           PROP_IO_MODE, 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->v4l2output->pool)
222     gst_v4l2_buffer_pool_flush (self->v4l2output->pool);
223   if (self->v4l2capture->pool)
224     gst_v4l2_buffer_pool_flush (self->v4l2capture->pool);
225
226   if (self->input_state) {
227     gst_video_codec_state_unref (self->input_state);
228     self->input_state = NULL;
229   }
230
231   GST_DEBUG_OBJECT (self, "Stopped");
232
233   return TRUE;
234 }
235
236 static gboolean
237 gst_v4l2_encoder_cmd (GstV4l2Object * v4l2object, guint cmd, guint flags)
238 {
239   struct v4l2_encoder_cmd ecmd = { 0, };
240
241   GST_DEBUG_OBJECT (v4l2object->element,
242       "sending v4l2 encoder command %u with flags %u", cmd, flags);
243
244   if (!GST_V4L2_IS_OPEN (v4l2object))
245     return FALSE;
246
247   ecmd.cmd = cmd;
248   ecmd.flags = flags;
249   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_ENCODER_CMD, &ecmd) < 0)
250     goto ecmd_failed;
251
252   return TRUE;
253
254 ecmd_failed:
255   if (errno == ENOTTY) {
256     GST_INFO_OBJECT (v4l2object->element,
257         "Failed to send encoder command %u with flags %u for '%s'. (%s)",
258         cmd, flags, v4l2object->videodev, g_strerror (errno));
259   } else {
260     GST_ERROR_OBJECT (v4l2object->element,
261         "Failed to send encoder command %u with flags %u for '%s'. (%s)",
262         cmd, flags, v4l2object->videodev, g_strerror (errno));
263   }
264   return FALSE;
265 }
266
267 static GstFlowReturn
268 gst_v4l2_video_enc_finish (GstVideoEncoder * encoder)
269 {
270   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
271   GstFlowReturn ret = GST_FLOW_OK;
272
273   if (gst_pad_get_task_state (encoder->srcpad) != GST_TASK_STARTED)
274     goto done;
275
276   GST_DEBUG_OBJECT (self, "Finishing encoding");
277
278   /* drop the stream lock while draining, so remaining buffers can be
279    * pushed from the src pad task thread */
280   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
281
282   if (gst_v4l2_encoder_cmd (self->v4l2capture, V4L2_ENC_CMD_STOP, 0)) {
283     GstTask *task = encoder->srcpad->task;
284
285     /* Wait for the task to be drained */
286     GST_OBJECT_LOCK (task);
287     while (GST_TASK_STATE (task) == GST_TASK_STARTED)
288       GST_TASK_WAIT (task);
289     GST_OBJECT_UNLOCK (task);
290     ret = GST_FLOW_FLUSHING;
291   }
292
293   /* and ensure the processing thread has stopped in case another error
294    * occured. */
295   gst_v4l2_object_unlock (self->v4l2capture);
296   gst_pad_stop_task (encoder->srcpad);
297   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
298
299   if (ret == GST_FLOW_FLUSHING)
300     ret = self->output_flow;
301
302   GST_DEBUG_OBJECT (encoder, "Done draining buffers");
303
304 done:
305   return ret;
306 }
307
308 static gboolean
309 gst_v4l2_video_enc_set_format (GstVideoEncoder * encoder,
310     GstVideoCodecState * state)
311 {
312   gboolean ret = TRUE;
313   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
314   GstV4l2Error error = GST_V4L2_ERROR_INIT;
315   GstCaps *outcaps;
316   GstVideoCodecState *output;
317
318   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
319
320   if (self->input_state) {
321     if (gst_v4l2_object_caps_equal (self->v4l2output, state->caps)) {
322       GST_DEBUG_OBJECT (self, "Compatible caps");
323       return TRUE;
324     }
325
326     if (gst_v4l2_video_enc_finish (encoder) != GST_FLOW_OK)
327       return FALSE;
328
329     gst_video_codec_state_unref (self->input_state);
330     self->input_state = NULL;
331   }
332
333   outcaps = gst_pad_get_pad_template_caps (encoder->srcpad);
334   outcaps = gst_caps_make_writable (outcaps);
335   output = gst_video_encoder_set_output_state (encoder, outcaps, state);
336   gst_video_codec_state_unref (output);
337
338   if (!gst_video_encoder_negotiate (encoder))
339     return FALSE;
340
341   if (!gst_v4l2_object_set_format (self->v4l2output, state->caps, &error)) {
342     gst_v4l2_error (self, &error);
343     return FALSE;
344   }
345
346   self->input_state = gst_video_codec_state_ref (state);
347
348   GST_DEBUG_OBJECT (self, "output caps: %" GST_PTR_FORMAT, state->caps);
349
350   return ret;
351 }
352
353 static gboolean
354 gst_v4l2_video_enc_flush (GstVideoEncoder * encoder)
355 {
356   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
357
358   GST_DEBUG_OBJECT (self, "Flushing");
359
360   /* Ensure the processing thread has stopped for the reverse playback
361    * iscount case */
362   if (g_atomic_int_get (&self->processing)) {
363     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
364
365     gst_v4l2_object_unlock_stop (self->v4l2output);
366     gst_v4l2_object_unlock_stop (self->v4l2capture);
367     gst_pad_stop_task (encoder->srcpad);
368
369     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
370
371   }
372
373   self->output_flow = GST_FLOW_OK;
374
375   gst_v4l2_object_unlock_stop (self->v4l2output);
376   gst_v4l2_object_unlock_stop (self->v4l2capture);
377
378   return TRUE;
379 }
380
381 struct ProfileLevelCtx
382 {
383   GstV4l2VideoEnc *self;
384   const gchar *profile;
385   const gchar *level;
386 };
387
388 static gboolean
389 get_string_list (GstStructure * s, const gchar * field, GQueue * queue)
390 {
391   const GValue *value;
392
393   value = gst_structure_get_value (s, field);
394
395   if (!value)
396     return FALSE;
397
398   if (GST_VALUE_HOLDS_LIST (value)) {
399     guint i;
400
401     if (gst_value_list_get_size (value) == 0)
402       return FALSE;
403
404     for (i = 0; i < gst_value_list_get_size (value); i++) {
405       const GValue *item = gst_value_list_get_value (value, i);
406
407       if (G_VALUE_HOLDS_STRING (item))
408         g_queue_push_tail (queue, g_value_dup_string (item));
409     }
410   } else if (G_VALUE_HOLDS_STRING (value)) {
411     g_queue_push_tail (queue, g_value_dup_string (value));
412   }
413
414   return TRUE;
415 }
416
417 static gboolean
418 negotiate_profile_and_level (GstCapsFeatures * features, GstStructure * s,
419     gpointer user_data)
420 {
421   struct ProfileLevelCtx *ctx = user_data;
422   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (ctx->self);
423   GstV4l2Object *v4l2object = GST_V4L2_VIDEO_ENC (ctx->self)->v4l2output;
424   GQueue profiles = G_QUEUE_INIT;
425   GQueue levels = G_QUEUE_INIT;
426   gboolean failed = FALSE;
427
428   if (klass->profile_cid && get_string_list (s, "profile", &profiles)) {
429     GList *l;
430
431     for (l = profiles.head; l; l = l->next) {
432       struct v4l2_control control = { 0, };
433       gint v4l2_profile;
434       const gchar *profile = l->data;
435
436       GST_TRACE_OBJECT (ctx->self, "Trying profile %s", profile);
437
438       control.id = klass->profile_cid;
439       control.value = v4l2_profile = klass->profile_from_string (profile);
440
441       if (control.value < 0)
442         continue;
443
444       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
445         GST_WARNING_OBJECT (ctx->self, "Failed to set %s profile: '%s'",
446             klass->codec_name, g_strerror (errno));
447         break;
448       }
449
450       profile = klass->profile_to_string (control.value);
451
452       if (control.value == v4l2_profile) {
453         ctx->profile = profile;
454         break;
455       }
456
457       if (g_list_find_custom (l, profile, g_str_equal)) {
458         ctx->profile = profile;
459         break;
460       }
461     }
462
463     if (profiles.length && !ctx->profile)
464       failed = TRUE;
465
466     g_queue_foreach (&profiles, (GFunc) g_free, NULL);
467     g_queue_clear (&profiles);
468   }
469
470   if (!failed && klass->level_cid && get_string_list (s, "level", &levels)) {
471     GList *l;
472
473     for (l = levels.head; l; l = l->next) {
474       struct v4l2_control control = { 0, };
475       gint v4l2_level;
476       const gchar *level = l->data;
477
478       GST_TRACE_OBJECT (ctx->self, "Trying level %s", level);
479
480       control.id = klass->level_cid;
481       control.value = v4l2_level = klass->level_from_string (level);
482
483       if (control.value < 0)
484         continue;
485
486       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
487         GST_WARNING_OBJECT (ctx->self, "Failed to set %s level: '%s'",
488             klass->codec_name, g_strerror (errno));
489         break;
490       }
491
492       level = klass->level_to_string (control.value);
493
494       if (control.value == v4l2_level) {
495         ctx->level = level;
496         break;
497       }
498
499       if (g_list_find_custom (l, level, g_str_equal)) {
500         ctx->level = level;
501         break;
502       }
503     }
504
505     if (levels.length && !ctx->level)
506       failed = TRUE;
507
508     g_queue_foreach (&levels, (GFunc) g_free, NULL);
509     g_queue_clear (&levels);
510   }
511
512   /* If it failed, we continue */
513   return failed;
514 }
515
516 static gboolean
517 gst_v4l2_video_enc_negotiate (GstVideoEncoder * encoder)
518 {
519   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (encoder);
520   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
521   GstV4l2Object *v4l2object = self->v4l2output;
522   GstCaps *allowed_caps;
523   struct ProfileLevelCtx ctx = { self, NULL, NULL };
524   GstVideoCodecState *state;
525   GstStructure *s;
526
527   GST_DEBUG_OBJECT (self, "Negotiating %s profile and level.",
528       klass->codec_name);
529
530   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (encoder));
531
532   if (allowed_caps) {
533
534     if (gst_caps_is_empty (allowed_caps))
535       goto not_negotiated;
536
537     allowed_caps = gst_caps_make_writable (allowed_caps);
538
539     /* negotiate_profile_and_level() will return TRUE on failure to keep
540      * iterating, if gst_caps_foreach() returns TRUE it means there was no
541      * compatible profile and level in any of the structure */
542     if (gst_caps_foreach (allowed_caps, negotiate_profile_and_level, &ctx)) {
543       goto no_profile_level;
544     }
545   }
546
547   if (klass->profile_cid && !ctx.profile) {
548     struct v4l2_control control = { 0, };
549
550     control.id = klass->profile_cid;
551
552     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
553       goto g_ctrl_failed;
554
555     ctx.profile = klass->profile_to_string (control.value);
556   }
557
558   if (klass->level_cid && !ctx.level) {
559     struct v4l2_control control = { 0, };
560
561     control.id = klass->level_cid;
562
563     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
564       goto g_ctrl_failed;
565
566     ctx.level = klass->level_to_string (control.value);
567   }
568
569   GST_DEBUG_OBJECT (self, "Selected %s profile %s at level %s",
570       klass->codec_name, ctx.profile, ctx.level);
571
572   state = gst_video_encoder_get_output_state (encoder);
573   s = gst_caps_get_structure (state->caps, 0);
574
575   if (klass->profile_cid)
576     gst_structure_set (s, "profile", G_TYPE_STRING, ctx.profile, NULL);
577
578   if (klass->level_cid)
579     gst_structure_set (s, "level", G_TYPE_STRING, ctx.level, NULL);
580
581   if (!GST_VIDEO_ENCODER_CLASS (parent_class)->negotiate (encoder))
582     return FALSE;
583
584   if (!gst_buffer_pool_set_active (GST_BUFFER_POOL (self->v4l2capture->pool),
585           TRUE)) {
586     GST_WARNING_OBJECT (self, "Could not activate capture buffer pool.");
587     return FALSE;
588   }
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
715   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
716
717   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
718     goto flushing;
719
720   if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) ==
721       GST_TASK_STOPPED) {
722     GstBufferPool *pool = GST_BUFFER_POOL (self->v4l2output->pool);
723
724     /* It possible that the processing thread stopped due to an error */
725     if (self->output_flow != GST_FLOW_OK &&
726         self->output_flow != GST_FLOW_FLUSHING) {
727       GST_DEBUG_OBJECT (self, "Processing loop stopped with error, leaving");
728       ret = self->output_flow;
729       goto drop;
730     }
731
732     /* Ensure input internal pool is active */
733     if (!gst_buffer_pool_is_active (pool)) {
734       GstStructure *config = gst_buffer_pool_get_config (pool);
735       guint min = MAX (self->v4l2output->min_buffers, GST_V4L2_MIN_BUFFERS);
736
737       gst_buffer_pool_config_set_params (config, self->input_state->caps,
738           self->v4l2output->info.size, min, min);
739
740       /* There is no reason to refuse this config */
741       if (!gst_buffer_pool_set_config (pool, config))
742         goto activate_failed;
743
744       if (!gst_buffer_pool_set_active (pool, TRUE))
745         goto activate_failed;
746     }
747
748     GST_DEBUG_OBJECT (self, "Starting encoding thread");
749
750     /* Start the processing task, when it quits, the task will disable input
751      * processing to unlock input if draining, or prevent potential block */
752     if (!gst_pad_start_task (encoder->srcpad,
753             (GstTaskFunction) gst_v4l2_video_enc_loop, self,
754             (GDestroyNotify) gst_v4l2_video_enc_loop_stopped))
755       goto start_task_failed;
756   }
757
758   if (frame->input_buffer) {
759     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
760     ret =
761         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL
762         (self->v4l2output->pool), &frame->input_buffer);
763     GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
764
765     if (ret == GST_FLOW_FLUSHING) {
766       if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) !=
767           GST_TASK_STARTED)
768         ret = self->output_flow;
769       goto drop;
770     } else if (ret != GST_FLOW_OK) {
771       goto process_failed;
772     }
773   }
774
775   gst_video_codec_frame_unref (frame);
776   return ret;
777
778   /* ERRORS */
779 activate_failed:
780   {
781     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
782         (_("Failed to allocate required memory.")),
783         ("Buffer pool activation failed"));
784     return GST_FLOW_ERROR;
785
786   }
787 flushing:
788   {
789     ret = GST_FLOW_FLUSHING;
790     goto drop;
791   }
792 start_task_failed:
793   {
794     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
795         (_("Failed to start encoding thread.")), (NULL));
796     g_atomic_int_set (&self->processing, FALSE);
797     ret = GST_FLOW_ERROR;
798     goto drop;
799   }
800 process_failed:
801   {
802     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
803         (_("Failed to process frame.")),
804         ("Maybe be due to not enough memory or failing driver"));
805     ret = GST_FLOW_ERROR;
806     goto drop;
807   }
808 drop:
809   {
810     gst_video_encoder_finish_frame (encoder, frame);
811     return ret;
812   }
813 }
814
815 static gboolean
816 gst_v4l2_video_enc_decide_allocation (GstVideoEncoder *
817     encoder, GstQuery * query)
818 {
819   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
820   GstVideoCodecState *state = gst_video_encoder_get_output_state (encoder);
821   GstV4l2Error error = GST_V4L2_ERROR_INIT;
822   GstClockTime latency;
823   gboolean ret = FALSE;
824
825   /* We need to set the format here, since this is called right after
826    * GstVideoEncoder have set the width, height and framerate into the state
827    * caps. These are needed by the driver to calculate the buffer size and to
828    * implement bitrate adaptation. */
829   if (!gst_v4l2_object_set_format (self->v4l2capture, state->caps, &error)) {
830     gst_v4l2_error (self, &error);
831     ret = FALSE;
832     goto done;
833   }
834
835   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query)) {
836     GstVideoEncoderClass *enc_class = GST_VIDEO_ENCODER_CLASS (parent_class);
837     ret = enc_class->decide_allocation (encoder, query);
838   }
839
840   /* FIXME This may not be entirely correct, as encoder may keep some
841    * observation withouth delaying the encoding. Linux Media API need some
842    * more work to explicitly expressed the decoder / encoder latency. This
843    * value will then become max latency, and the reported driver latency would
844    * become the min latency. */
845   latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
846   gst_video_encoder_set_latency (encoder, latency, latency);
847
848 done:
849   gst_video_codec_state_unref (state);
850   return ret;
851 }
852
853 static gboolean
854 gst_v4l2_video_enc_propose_allocation (GstVideoEncoder *
855     encoder, GstQuery * query)
856 {
857   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
858   gboolean ret = FALSE;
859
860   GST_DEBUG_OBJECT (self, "called");
861
862   if (query == NULL)
863     ret = TRUE;
864   else
865     ret = gst_v4l2_object_propose_allocation (self->v4l2output, query);
866
867   if (ret)
868     ret = GST_VIDEO_ENCODER_CLASS (parent_class)->propose_allocation (encoder,
869         query);
870
871   return ret;
872 }
873
874 static gboolean
875 gst_v4l2_video_enc_src_query (GstVideoEncoder * encoder, GstQuery * query)
876 {
877   gboolean ret = TRUE;
878   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
879   switch (GST_QUERY_TYPE (query)) {
880     case GST_QUERY_CAPS:{
881       GstCaps *filter, *result = NULL;
882       GstPad *pad = GST_VIDEO_ENCODER_SRC_PAD (encoder);
883
884       gst_query_parse_caps (query, &filter);
885
886       /* FIXME Try and not probe the entire encoder, but only the implement
887        * subclass format */
888       if (self->probed_srccaps) {
889         GstCaps *tmpl = gst_pad_get_pad_template_caps (pad);
890         result = gst_caps_intersect (tmpl, self->probed_srccaps);
891         gst_caps_unref (tmpl);
892       } else
893         result = gst_pad_get_pad_template_caps (pad);
894
895       if (filter) {
896         GstCaps *tmp = result;
897         result =
898             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
899         gst_caps_unref (tmp);
900       }
901
902       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
903
904       gst_query_set_caps_result (query, result);
905       gst_caps_unref (result);
906       break;
907     }
908
909     default:
910       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->src_query (encoder, query);
911       break;
912   }
913
914   return ret;
915 }
916
917 static gboolean
918 gst_v4l2_video_enc_sink_query (GstVideoEncoder * encoder, GstQuery * query)
919 {
920   gboolean ret = TRUE;
921   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
922
923   switch (GST_QUERY_TYPE (query)) {
924     case GST_QUERY_CAPS:{
925       GstCaps *filter, *result = NULL;
926       GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (encoder);
927
928       gst_query_parse_caps (query, &filter);
929
930       if (self->probed_sinkcaps)
931         result = gst_caps_ref (self->probed_sinkcaps);
932       else
933         result = gst_pad_get_pad_template_caps (pad);
934
935       if (filter) {
936         GstCaps *tmp = result;
937         result =
938             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
939         gst_caps_unref (tmp);
940       }
941
942       GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
943
944       gst_query_set_caps_result (query, result);
945       gst_caps_unref (result);
946       break;
947     }
948
949     default:
950       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_query (encoder, query);
951       break;
952   }
953
954   return ret;
955 }
956
957 static gboolean
958 gst_v4l2_video_enc_sink_event (GstVideoEncoder * encoder, GstEvent * event)
959 {
960   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
961   gboolean ret;
962
963   switch (GST_EVENT_TYPE (event)) {
964     case GST_EVENT_FLUSH_START:
965       GST_DEBUG_OBJECT (self, "flush start");
966       gst_v4l2_object_unlock (self->v4l2output);
967       gst_v4l2_object_unlock (self->v4l2capture);
968       break;
969     default:
970       break;
971   }
972
973   ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_event (encoder, event);
974
975   switch (GST_EVENT_TYPE (event)) {
976     case GST_EVENT_FLUSH_START:
977       gst_pad_stop_task (encoder->srcpad);
978       GST_DEBUG_OBJECT (self, "flush start done");
979     default:
980       break;
981   }
982
983   return ret;
984 }
985
986 static GstStateChangeReturn
987 gst_v4l2_video_enc_change_state (GstElement * element,
988     GstStateChange transition)
989 {
990   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (element);
991
992   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
993     g_atomic_int_set (&self->active, FALSE);
994     gst_v4l2_object_unlock (self->v4l2output);
995     gst_v4l2_object_unlock (self->v4l2capture);
996   }
997
998   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
999 }
1000
1001
1002 static void
1003 gst_v4l2_video_enc_dispose (GObject * object)
1004 {
1005   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1006
1007   gst_caps_replace (&self->probed_sinkcaps, NULL);
1008   gst_caps_replace (&self->probed_srccaps, NULL);
1009
1010   G_OBJECT_CLASS (parent_class)->dispose (object);
1011 }
1012
1013 static void
1014 gst_v4l2_video_enc_finalize (GObject * object)
1015 {
1016   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1017
1018   gst_v4l2_object_destroy (self->v4l2capture);
1019   gst_v4l2_object_destroy (self->v4l2output);
1020
1021   G_OBJECT_CLASS (parent_class)->finalize (object);
1022 }
1023
1024
1025 static void
1026 gst_v4l2_video_enc_init (GstV4l2VideoEnc * self)
1027 {
1028   /* V4L2 object are created in subinstance_init */
1029 }
1030
1031 static void
1032 gst_v4l2_video_enc_subinstance_init (GTypeInstance * instance, gpointer g_class)
1033 {
1034   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1035   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (instance);
1036
1037   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
1038       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
1039       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
1040   self->v4l2output->no_initial_format = TRUE;
1041   self->v4l2output->keep_aspect = FALSE;
1042
1043   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
1044       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
1045       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
1046   self->v4l2capture->no_initial_format = TRUE;
1047   self->v4l2output->keep_aspect = FALSE;
1048 }
1049
1050 static void
1051 gst_v4l2_video_enc_class_init (GstV4l2VideoEncClass * klass)
1052 {
1053   GstElementClass *element_class;
1054   GObjectClass *gobject_class;
1055   GstVideoEncoderClass *video_encoder_class;
1056
1057   parent_class = g_type_class_peek_parent (klass);
1058
1059   element_class = (GstElementClass *) klass;
1060   gobject_class = (GObjectClass *) klass;
1061   video_encoder_class = (GstVideoEncoderClass *) klass;
1062
1063   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_enc_debug, "v4l2videoenc", 0,
1064       "V4L2 Video Encoder");
1065
1066   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_dispose);
1067   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finalize);
1068   gobject_class->set_property =
1069       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_property);
1070   gobject_class->get_property =
1071       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_get_property);
1072
1073   video_encoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_open);
1074   video_encoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_close);
1075   video_encoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_start);
1076   video_encoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_stop);
1077   video_encoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finish);
1078   video_encoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_flush);
1079   video_encoder_class->set_format =
1080       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_format);
1081   video_encoder_class->negotiate =
1082       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_negotiate);
1083   video_encoder_class->decide_allocation =
1084       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_decide_allocation);
1085   video_encoder_class->propose_allocation =
1086       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_propose_allocation);
1087   video_encoder_class->sink_query =
1088       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_query);
1089   video_encoder_class->src_query =
1090       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_src_query);
1091   video_encoder_class->sink_event =
1092       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_event);
1093   video_encoder_class->handle_frame =
1094       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_handle_frame);
1095
1096   element_class->change_state =
1097       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_change_state);
1098
1099   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
1100 }
1101
1102 static void
1103 gst_v4l2_video_enc_subclass_init (gpointer g_class, gpointer data)
1104 {
1105   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1106   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1107   GstV4l2VideoEncCData *cdata = data;
1108
1109   klass->default_device = cdata->device;
1110
1111   /* Note: gst_pad_template_new() take the floating ref from the caps */
1112   gst_element_class_add_pad_template (element_class,
1113       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
1114           cdata->sink_caps));
1115   gst_element_class_add_pad_template (element_class,
1116       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
1117           cdata->src_caps));
1118
1119   gst_caps_unref (cdata->sink_caps);
1120   gst_caps_unref (cdata->src_caps);
1121   g_free (cdata);
1122 }
1123
1124 /* Probing functions */
1125 gboolean
1126 gst_v4l2_is_video_enc (GstCaps * sink_caps, GstCaps * src_caps,
1127     GstCaps * codec_caps)
1128 {
1129   gboolean ret = FALSE;
1130   gboolean (*check_caps) (const GstCaps *, const GstCaps *);
1131
1132   if (codec_caps) {
1133     check_caps = gst_caps_can_intersect;
1134   } else {
1135     codec_caps = gst_v4l2_object_get_codec_caps ();
1136     check_caps = gst_caps_is_subset;
1137   }
1138
1139   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_raw_caps ())
1140       && check_caps (src_caps, codec_caps))
1141     ret = TRUE;
1142
1143   return ret;
1144 }
1145
1146 void
1147 gst_v4l2_video_enc_register (GstPlugin * plugin, GType type,
1148     const char *codec, const gchar * basename, const gchar * device_path,
1149     GstCaps * sink_caps, GstCaps * codec_caps, GstCaps * src_caps)
1150 {
1151   GstCaps *filtered_caps;
1152   GTypeQuery type_query;
1153   GTypeInfo type_info = { 0, };
1154   GType subtype;
1155   gchar *type_name;
1156   GstV4l2VideoEncCData *cdata;
1157
1158   filtered_caps = gst_caps_intersect (src_caps, codec_caps);
1159
1160   cdata = g_new0 (GstV4l2VideoEncCData, 1);
1161   cdata->device = g_strdup (device_path);
1162   cdata->sink_caps = gst_caps_ref (sink_caps);
1163   cdata->src_caps = gst_caps_ref (filtered_caps);
1164
1165   g_type_query (type, &type_query);
1166   memset (&type_info, 0, sizeof (type_info));
1167   type_info.class_size = type_query.class_size;
1168   type_info.instance_size = type_query.instance_size;
1169   type_info.class_init = gst_v4l2_video_enc_subclass_init;
1170   type_info.class_data = cdata;
1171   type_info.instance_init = gst_v4l2_video_enc_subinstance_init;
1172
1173   /* The first encoder to be registered should use a constant name, like
1174    * v4l2h264enc, for any additional encoders, we create unique names. Encoder
1175    * names may change between boots, so this should help gain stable names for
1176    * the most common use cases. */
1177   type_name = g_strdup_printf ("v4l2%senc", codec);
1178
1179   if (g_type_from_name (type_name) != 0) {
1180     g_free (type_name);
1181     type_name = g_strdup_printf ("v4l2%s%senc", basename, codec);
1182   }
1183
1184   subtype = g_type_register_static (type, type_name, &type_info, 0);
1185
1186   if (!gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1, subtype))
1187     GST_WARNING ("Failed to register plugin '%s'", type_name);
1188
1189   g_free (type_name);
1190 }