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